public void Init(MyStringHash sourceGroup, List<MyResourceSourceInfo> sourceResourceData) { Group = sourceGroup; var resourceData = sourceResourceData; bool hasResourceData = resourceData != null && resourceData.Count != 0; int resourceCount = hasResourceData ? resourceData.Count : 1; Enabled = true; if(resourceCount != m_allocatedTypeCount) AllocateData(resourceCount); int resourceIndexCounter = 0; if (!hasResourceData) { m_resourceTypeToIndex.Add(MyResourceDistributorComponent.ElectricityId, resourceIndexCounter++); m_resourceIds.Add(MyResourceDistributorComponent.ElectricityId); } else { foreach (var resourceInfo in resourceData) { m_resourceTypeToIndex.Add(resourceInfo.ResourceTypeId, resourceIndexCounter++); m_resourceIds.Add(resourceInfo.ResourceTypeId); m_dataPerType[resourceIndexCounter - 1].DefinedOutput = resourceInfo.DefinedOutput; SetOutputByType(resourceInfo.ResourceTypeId, 0f); SetMaxOutputByType(resourceInfo.ResourceTypeId, m_dataPerType[GetTypeIndex(resourceInfo.ResourceTypeId)].DefinedOutput); SetProductionEnabledByType(resourceInfo.ResourceTypeId, true); m_dataPerType[resourceIndexCounter - 1].ProductionToCapacityMultiplier = (resourceInfo.ProductionToCapacityMultiplier != 0f ? resourceInfo.ProductionToCapacityMultiplier : 1f); if(resourceInfo.IsInfiniteCapacity) SetRemainingCapacityByType(resourceInfo.ResourceTypeId, float.PositiveInfinity); } } }
public virtual void Init(MyObjectBuilder_Base objectBuilder) { var builder = (MyObjectBuilder_EntityStat) objectBuilder; MyEntityStatDefinition definition; MyDefinitionManager.Static.TryGetDefinition<MyEntityStatDefinition>(new MyDefinitionId(builder.TypeId, builder.SubtypeId), out definition); Debug.Assert(definition != null); StatDefinition = definition; System.Diagnostics.Debug.Assert(!float.IsNaN(definition.MaxValue) && !float.IsNaN(definition.MinValue) && !float.IsNaN(definition.DefaultValue), "Invalid values in stat definition!"); m_maxValue = definition.MaxValue; m_minValue = definition.MinValue; m_currentValue = builder.Value * m_maxValue; m_defaultValue = definition.DefaultValue; m_lastSyncValue = m_currentValue; m_statId = MyStringHash.GetOrCompute(definition.Name); m_regenAmountMultiplier = builder.StatRegenAmountMultiplier; m_regenAmountMultiplierDuration = builder.StatRegenAmountMultiplierDuration; m_regenAmountMultiplierTimeStart = MySandboxGame.TotalGamePlayTimeInMilliseconds; m_regenAmountMultiplierTimeAlive = 0; m_regenAmountMultiplierActive = m_regenAmountMultiplierDuration > 0; ClearEffects(); if (builder.Effects != null) { foreach (var effectBuilder in builder.Effects) { AddEffect(effectBuilder); } } }
/// <param name="damage">Not used for now but could be used as a multiplier instead of random decal size</param> public static void HandleAddDecal(IMyEntity entity, MyHitInfo hitInfo, MyStringHash source = default(MyStringHash), object customdata = null, float damage = -1) { IMyDecalProxy proxy = entity as IMyDecalProxy; if (proxy != null) { AddDecal(proxy, ref hitInfo, damage, source, customdata); return; } MyCubeGrid grid = entity as MyCubeGrid; if (grid != null) { var block = grid.GetTargetedBlock(hitInfo.Position); if (block != null) { var compoundBlock = block.FatBlock as MyCompoundCubeBlock; if (compoundBlock == null) proxy = block; else proxy = compoundBlock; } } if (proxy == null) return; AddDecal(proxy, ref hitInfo, damage, source, customdata); }
/// <param name="damage">Not used for now but could be used as a multiplier instead of random decal size</param> public static void HandleAddDecal(IMyEntity entity, MyHitInfo hitInfo, MyStringHash source = default(MyStringHash), float damage = -1) { if (entity == null) DebugNullEntity(); IMyDecalProxy proxy = entity as IMyDecalProxy; if (proxy != null) { AddDecal(proxy, ref hitInfo, damage, source); return; } MyCubeGrid grid = entity.GetTopMostParent() as MyCubeGrid; if (grid != null) { var block = grid.GetTargetedBlock(hitInfo.Position); if (block != null) { var compoundBlock = block.FatBlock as MyCompoundCubeBlock; if (compoundBlock == null) proxy = block; else proxy = compoundBlock; } } if (proxy != null) AddDecal(proxy, ref hitInfo, damage, source); }
public MyModelInstanceData(MyStringHash subtypeId, MyInstanceFlagsEnum flags, float maxViewDistance, BoundingBox modelBox) { SubtypeId = subtypeId; Flags = flags; MaxViewDistance = maxViewDistance; ModelBox = modelBox; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_OreDetectorDefinition; ResourceSinkGroup = MyStringHash.GetOrCompute(ob.ResourceSinkGroup); MaximumRange = ob.MaximumRange; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_PhysicalItemDefinition; MyDebug.AssertDebug(ob != null); this.Size = ob.Size; this.Mass = ob.Mass; this.Model = ob.Model; this.Models = ob.Models; this.Volume = ob.Volume.HasValue? ob.Volume.Value / 1000f : ob.Size.Volume; if (string.IsNullOrEmpty(ob.IconSymbol)) this.IconSymbol = null; else this.IconSymbol = MyStringId.GetOrCompute(ob.IconSymbol); PhysicalMaterial = MyStringHash.GetOrCompute(ob.PhysicalMaterial); VoxelMaterial = MyStringHash.GetOrCompute(ob.VoxelMaterial); CanSpawnFromScreen = ob.CanSpawnFromScreen; RotateOnSpawnX = ob.RotateOnSpawnX; RotateOnSpawnY = ob.RotateOnSpawnY; RotateOnSpawnZ = ob.RotateOnSpawnZ; Health = ob.Health; if (ob.DestroyedPieceId.HasValue) { DestroyedPieceId = ob.DestroyedPieceId.Value; } DestroyedPieces = ob.DestroyedPieces; if (ob.ExtraInventoryTooltipLine != null) ExtraInventoryTooltipLine = new StringBuilder().Append(Environment.NewLine).Append(ob.ExtraInventoryTooltipLine); else ExtraInventoryTooltipLine = new StringBuilder(); }
public void Init(MyStringHash sourceGroup, MyResourceSourceInfo sourceResourceData) { MyUtils.Init(ref m_singleHelperList); m_singleHelperList.Add(sourceResourceData); Init(sourceGroup, m_singleHelperList); m_singleHelperList.Clear(); }
public override void DoDamage(float damage, int itemInstanceId, Vector3D position, Vector3 normal, MyStringHash type) { MyEnvironmentItemData itemData = m_itemsData[itemInstanceId]; MyDefinitionId id = new MyDefinitionId(Definition.ItemDefinitionType, itemData.SubtypeId); var itemDefinition = (MyTreeDefinition)MyDefinitionManager.Static.GetEnvironmentItemDefinition(id); int effectId; if (itemDefinition.CutEffect != null && MyParticlesLibrary.GetParticleEffectsID(itemDefinition.CutEffect, out effectId)) { MyParticleEffect effect; if (MyParticlesManager.TryCreateParticleEffect(effectId, out effect)) { effect.WorldMatrix = MatrixD.CreateWorld(position, Vector3.CalculatePerpendicularVector(normal), normal); } } if (!Sync.IsServer) { return; } MyCutTreeInfo cutTreeInfo = default(MyCutTreeInfo); int index = -1; for (int i = 0; i < m_cutTreeInfos.Count; ++i) { cutTreeInfo = m_cutTreeInfos[i]; if (itemInstanceId == cutTreeInfo.ItemInstanceId) { index = i; break; } } if (index == -1) { cutTreeInfo = new MyCutTreeInfo(); cutTreeInfo.ItemInstanceId = itemInstanceId; cutTreeInfo.MaxPoints = cutTreeInfo.HitPoints = itemDefinition.HitPoints; index = m_cutTreeInfos.Count; m_cutTreeInfos.Add(cutTreeInfo); } cutTreeInfo.LastHit = MySandboxGame.TotalGamePlayTimeInMilliseconds; cutTreeInfo.HitPoints -= damage; if (cutTreeInfo.Progress >= 1) { CutTree(itemInstanceId, position, normal, type == MyDamageType.Drill ? 1.0f : 4.0f); m_cutTreeInfos.RemoveAtFast(index); } else { m_cutTreeInfos[index] = cutTreeInfo; } return; }
public MyRepairBlueprintToProduce(MyFixedPoint amount, MyBlueprintDefinitionBase blueprint, uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId) : base(amount, blueprint) { System.Diagnostics.Debug.Assert(Blueprint is MyRepairBlueprintDefinition, "MyRepairBlueprintToProduce class should be used together with blueprints type of MyRepairBlueprintDefinition only!"); InventoryItemId = inventoryItemId; InventoryItemType = inventoryItemType; InventoryItemSubtypeId = inventoryItemSubtypeId; }
public MyDamageInformation(bool isDeformation, float amount, MyStringHash type, long attackerId) { IsDeformation = isDeformation; Amount = amount; Type = type; AttackerId = attackerId; }
public static MyInventoryBase GetInventory(this MyEntity entity, MyStringHash inventoryId) { MyInventoryBase inventory = null; inventory = entity.Components.Get<MyInventoryBase>(); if (inventory != null) { if (inventoryId.Equals(MyStringHash.GetOrCompute(inventory.InventoryId.ToString()))) { return inventory; } } if (inventory is MyInventoryAggregate) { var aggregate = inventory as MyInventoryAggregate; m_tmpList.Clear(); aggregate.GetComponentsFlattened(m_tmpList); foreach (var component in m_tmpList) { var componentInventory = component as MyInventoryBase; if (inventoryId.Equals(MyStringHash.GetOrCompute(componentInventory.InventoryId.ToString()))) { return componentInventory; } } } return null; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var thrustBuilder = builder as MyObjectBuilder_ThrustDefinition; MyDebug.AssertDebug(thrustBuilder != null, "Initializing thrust definition using wrong object builder."); ResourceSinkGroup = MyStringHash.GetOrCompute(thrustBuilder.ResourceSinkGroup); FuelConverter = thrustBuilder.FuelConverter; SlowdownFactor = thrustBuilder.SlowdownFactor; ForceMagnitude = thrustBuilder.ForceMagnitude; MaxPowerConsumption = thrustBuilder.MaxPowerConsumption; MinPowerConsumption = thrustBuilder.MinPowerConsumption; FlameDamageLengthScale = thrustBuilder.FlameDamageLengthScale; FlameDamage = thrustBuilder.FlameDamage; FlameLengthScale = thrustBuilder.FlameLengthScale; FlameFullColor = thrustBuilder.FlameFullColor; FlameIdleColor = thrustBuilder.FlameIdleColor; FlamePointMaterial = thrustBuilder.FlamePointMaterial; FlameLengthMaterial = thrustBuilder.FlameLengthMaterial; FlameGlareMaterial = thrustBuilder.FlameGlareMaterial; FlameVisibilityDistance = thrustBuilder.FlameVisibilityDistance; FlameGlareSize = thrustBuilder.FlameGlareSize; FlameGlareQuerySize = thrustBuilder.FlameGlareQuerySize; EffectivenessAtMinInfluence = thrustBuilder.EffectivenessAtMinInfluence; EffectivenessAtMaxInfluence = thrustBuilder.EffectivenessAtMaxInfluence; }
public virtual void Init(MyObjectBuilder_Base objectBuilder) { var builder = (MyObjectBuilder_EntityStat) objectBuilder; MyEntityStatDefinition definition; MyDefinitionManager.Static.TryGetDefinition<MyEntityStatDefinition>(new MyDefinitionId(builder.TypeId, builder.SubtypeId), out definition); Debug.Assert(definition != null); StatDefinition = definition; m_maxValue = builder.MaxValue * 100.0f; m_minValue = 0.0f; m_currentValue = builder.Value * m_maxValue; m_lastSyncValue = m_currentValue; m_statId = MyStringHash.GetOrCompute(definition.Name); if (builder.Effects != null) { foreach (var effectBuilder in builder.Effects) { AddEffect(effectBuilder); } } }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); MyDebug.AssertDebug(builder is MyObjectBuilder_ProductionBlockDefinition); var obDefinition = builder as MyObjectBuilder_ProductionBlockDefinition; this.InventoryMaxVolume = obDefinition.InventoryMaxVolume; this.InventorySize = obDefinition.InventorySize; ResourceSinkGroup = MyStringHash.GetOrCompute(obDefinition.ResourceSinkGroup); this.StandbyPowerConsumption = obDefinition.StandbyPowerConsumption; this.OperationalPowerConsumption = obDefinition.OperationalPowerConsumption; System.Diagnostics.Debug.Assert(obDefinition.BlueprintClasses != null, "Production block has no blueprint classes specified"); if (obDefinition.BlueprintClasses == null) InitializeLegacyBlueprintClasses(obDefinition); BlueprintClasses = new List<MyBlueprintClassDefinition>(); for (int i = 0; i < obDefinition.BlueprintClasses.Length; ++i) { var className = obDefinition.BlueprintClasses[i]; var classDef = MyDefinitionManager.Static.GetBlueprintClass(className); System.Diagnostics.Debug.Assert(classDef != null, "Production block references non-existent blueprint class"); if (classDef == null) continue; BlueprintClasses.Add(classDef); } }
public void AddItemDefinition(MyStringHash definition) { Debug.Assert(!m_itemDefinitions.Contains(definition)); if (m_itemDefinitions.Contains(definition)) return; m_itemDefinitions.Add(definition); m_definitionList.Add(definition); }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var obRemote = builder as MyObjectBuilder_RemoteControlDefinition; MyDebug.AssertDebug(obRemote != null, "Initializing remote control using wrong definition"); ResourceSinkGroup = MyStringHash.GetOrCompute(obRemote.ResourceSinkGroup); RequiredPowerInput = obRemote.RequiredPowerInput; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var obProjector = builder as MyObjectBuilder_ProjectorDefinition; MyDebug.AssertDebug(obProjector != null, "Initializing camera definition using wrong object builder.!"); ResourceSinkGroup = MyStringHash.GetOrCompute(obProjector.ResourceSinkGroup); RequiredPowerInput = obProjector.RequiredPowerInput; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var soundBlockBuilder = (MyObjectBuilder_SoundBlockDefinition)builder; Debug.Assert(soundBlockBuilder != null); ResourceSinkGroup = MyStringHash.GetOrCompute(soundBlockBuilder.ResourceSinkGroup); }
public MyModelInstanceData(MyEnvironmentSector parent, MyStringHash subtypeId, ModelId model, MyInstanceFlagsEnum flags, float maxViewDistance, BoundingBox modelBox) { Parent = parent; SubtypeId = subtypeId; Flags = flags; MaxViewDistance = maxViewDistance; ModelBox = modelBox; Model = model; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var antennaBuilder = (MyObjectBuilder_RadioAntennaDefinition)builder; Debug.Assert(antennaBuilder != null); ResourceSinkGroup = MyStringHash.GetOrCompute(antennaBuilder.ResourceSinkGroup); }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var obGenerator = builder as MyObjectBuilder_GravityGeneratorBaseDefinition; MyDebug.AssertDebug(obGenerator != null, "Initializing definition using wrong object builder."); ResourceSinkGroup = MyStringHash.GetOrCompute(obGenerator.ResourceSinkGroup); MinGravityAcceleration = obGenerator.MinGravityAcceleration; MaxGravityAcceleration = obGenerator.MaxGravityAcceleration; }
public virtual bool CanStack(MyObjectBuilderType typeId, MyStringHash subtypeId, MyItemFlags flags) { if (flags == Flags && typeId == TypeId && subtypeId == SubtypeId) { return true; } return false; }
public MyEnvironmentItemDefinition GetItemDefinition(MyStringHash subtypeId) { MyEnvironmentItemDefinition retval = null; MyDefinitionId defId = new MyDefinitionId(m_itemDefinitionType, subtypeId); MyDefinitionManager.Static.TryGetDefinition(defId, out retval); Debug.Assert(retval != null, "Could not find environment item with definition id " + defId); return retval; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_ButtonPanelDefinition; ResourceSinkGroup = MyStringHash.GetOrCompute(ob.ResourceSinkGroup); ButtonCount = ob.ButtonCount; ButtonSymbols = ob.ButtonSymbols; ButtonColors = ob.ButtonColors; UnassignedButtonColor = ob.UnassignedButtonColor; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var obMass = builder as MyObjectBuilder_VirtualMassDefinition; MyDebug.AssertDebug(obMass != null, "Initializing virtual mass definition using wrong object builder."); ResourceSinkGroup = MyStringHash.GetOrCompute(obMass.ResourceSinkGroup); RequiredPowerInput = obMass.RequiredPowerInput; VirtualMass = obMass.VirtualMass; }
public static void DoDamageSynced(MyEntity entity, float damage, MyStringHash type, long attackerId) { Debug.Assert(Sync.IsServer); IMyDestroyableObject destroyable = entity as IMyDestroyableObject; if (destroyable == null) return; destroyable.DoDamage(damage, type, false, attackerId: attackerId); MyMultiplayer.RaiseStaticEvent(s => MySyncDamage.OnDoDamage, entity.EntityId, damage, type, attackerId); }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var cbuilder = builder as MyObjectBuilder_ShipDrillDefinition; Debug.Assert(cbuilder != null); ResourceSinkGroup = MyStringHash.GetOrCompute(cbuilder.ResourceSinkGroup); SensorRadius = cbuilder.SensorRadius; SensorOffset = cbuilder.SensorOffset; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var obGenerator = builder as MyObjectBuilder_SensorBlockDefinition; MyDebug.AssertDebug(obGenerator != null, "Initializing sensor block definition using wrong object builder."); MyDebug.AssertDebug(obGenerator.MaxRange >= 1, "Invalid max range of sensor definition, using max range 1"); ResourceSinkGroup = MyStringHash.GetOrCompute(obGenerator.ResourceSinkGroup); RequiredPowerInput = obGenerator.RequiredPowerInput; MaxRange = Math.Max(obGenerator.MaxRange, 1); }
public MyEffectInstance CreateEffect(IMySourceVoice input, MyStringHash effect, MySourceVoice[] cues = null, float? duration = null) { if(!m_effects.ContainsKey(effect)) { Debug.Fail(string.Format("Effect not found: {0}", effect.ToString())); return null; } var instance = new MyEffectInstance(m_effects[effect], input, cues, duration, m_engine); m_activeEffects.Add(instance); return instance; }
public string GetCollisionEffect(MyStringId type, MyStringHash materialType1, MyStringHash materialType2) { string foundEffect = null; Dictionary <MyStringHash, Dictionary <MyStringHash, MaterialProperties> > typeDic; if (MaterialDictionary.TryGetValue(type, out typeDic)) { Dictionary <MyStringHash, MaterialProperties> materialDic; if (typeDic.TryGetValue(materialType1, out materialDic)) { MaterialProperties result; if (materialDic.TryGetValue(materialType2, out result)) { foundEffect = result.ParticleEffectName; } } } return(foundEffect); }
void IMyDestroyableObject.DoDamage(float damage, MyStringHash damageType, bool sync, MyHitInfo?hitInfo, long attackerId) { DoDamage(damage, damageType, sync, attackerId); }
void OwnerSkinSelected(PlayerInfo pi, MyStringHash prevSkin, MyStringHash newSkin) { UpdatePaintCanMaterial(); }
internal void ReallyStupidKeenShit() //aka block group removal of individual blocks { var categories = MyDefinitionManager.Static.GetCategories(); var removeDefs = new HashSet <MyDefinitionId>(MyDefinitionId.Comparer); var keepDefs = new HashSet <string>(); foreach (var weaponDef in WeaponDefinitions) { foreach (var mount in weaponDef.Assignments.MountPoints) { var subTypeId = mount.SubtypeId; MyDefinitionId defId = new MyDefinitionId(); if ((ReplaceVanilla && VanillaCoreIds.TryGetValue(MyStringHash.GetOrCompute(subTypeId), out defId))) { removeDefs.Add(defId); } else { foreach (var def in AllDefinitions) { if (def.Id.SubtypeName == subTypeId) { removeDefs.Add(def.Id); break; } } } } } foreach (var def in AllDefinitions) { if (!removeDefs.Contains(def.Id)) { keepDefs.Add(def.Id.SubtypeName); } } foreach (var category in categories) { if (category.Value.IsShipCategory) { var removeList = new List <string>(); foreach (var item in category.Value.ItemIds) { foreach (var def in removeDefs) { var type = def.TypeId.ToString().Replace("MyObjectBuilder_", ""); var subType = string.IsNullOrEmpty(def.SubtypeName) ? "(null)" : def.SubtypeName; if ((item.Contains(type) || item.Contains(subType))) { removeList.Add(item); } } } foreach (var keep in keepDefs) { for (int i = 0; i < removeList.Count; i++) { var toRemove = removeList[i]; if (!string.IsNullOrEmpty(keep) && toRemove.EndsWith(keep)) { removeList.RemoveAtFast(i); } } } for (int i = 0; i < removeList.Count; i++) { category.Value.ItemIds.Remove(removeList[i]); } } } }
public MyInstanceBucket(int modelId, MyStringHash skinSubtypeId) { this.ModelId = modelId; this.SkinSubtypeId = skinSubtypeId; }
private void AddInstancePart(Dictionary <MyInstanceBucket, Tuple <List <MyCubeInstanceMergedData>, Sandbox.Game.Entities.Cube.MyInstanceInfo> > instanceParts, int modelId, MyStringHash skinSubtypeId, ref MyCubeInstanceData instance, ConcurrentDictionary <uint, bool> decals, MyInstanceFlagsEnum flags, float maxViewDistance = 3.402823E+38f) { Tuple <List <MyCubeInstanceMergedData>, Sandbox.Game.Entities.Cube.MyInstanceInfo> tuple; MyInstanceBucket key = new MyInstanceBucket(modelId, skinSubtypeId); if (!instanceParts.TryGetValue(key, out tuple)) { tuple = Tuple.Create <List <MyCubeInstanceMergedData>, Sandbox.Game.Entities.Cube.MyInstanceInfo>(new List <MyCubeInstanceMergedData>(), new Sandbox.Game.Entities.Cube.MyInstanceInfo(flags, maxViewDistance)); instanceParts.Add(key, tuple); } Vector3 translation = instance.LocalMatrix.Translation; this.m_tmpBoundingBox.Min = translation - new Vector3(this.m_gridRenderComponent.GridSize); this.m_tmpBoundingBox.Max = translation + new Vector3(this.m_gridRenderComponent.GridSize); this.m_boundingBox.Include(this.m_tmpBoundingBox); MyCubeInstanceMergedData item = new MyCubeInstanceMergedData { CubeInstanceData = instance, Decals = decals }; tuple.Item1.Add(item); }
private MyStringHash RayCastGround() { MyStringHash walkSurfaceMaterial = new MyStringHash(); float maxDistValue = MyConstants.DEFAULT_GROUND_SEARCH_DISTANCE; var from = m_character.PositionComp.GetPosition() + m_character.PositionComp.WorldMatrix.Up * 0.5; //(needs some small distance from the bottom or the following call to HavokWorld.CastRay will find no hits) var to = from + m_character.PositionComp.WorldMatrix.Down * maxDistValue; MyPhysics.CastRay(from, to, m_hits, MyPhysics.CollisionLayers.CharacterCollisionLayer); // Skips invalid hits (null body, self character) int index = 0; while ((index < m_hits.Count) && ((m_hits[index].HkHitInfo.Body == null) || (m_hits[index].HkHitInfo.GetHitEntity() == Entity.Components))) { index++; } if (m_hits.Count == 0) { if ((m_standingOnGrid != null || m_standingOnVoxel != null) && ShouldUpdateSoundEmitters) { m_standingOnGrid = null; m_standingOnVoxel = null; MyEntity3DSoundEmitter.UpdateEntityEmitters(true, true, false); } else { m_standingOnGrid = null; m_standingOnVoxel = null; } } if (index < m_hits.Count) { // We must take only closest hit (others are hidden behind) var h = m_hits[index]; var entity = h.HkHitInfo.GetHitEntity(); var sqDist = Vector3D.DistanceSquared((Vector3D)h.Position, from); if (sqDist < maxDistValue * maxDistValue) { var cubeGrid = entity as MyCubeGrid; var voxelBase = entity as MyVoxelBase; if (((cubeGrid != null && m_standingOnGrid != cubeGrid) || (voxelBase != null && m_standingOnVoxel != voxelBase)) && ShouldUpdateSoundEmitters) { m_standingOnGrid = cubeGrid; m_standingOnVoxel = voxelBase; MyEntity3DSoundEmitter.UpdateEntityEmitters(true, true, true); } else { m_standingOnGrid = cubeGrid; m_standingOnVoxel = voxelBase; } if (cubeGrid != null || voxelBase != null) { m_jumpReady = true; } if (cubeGrid != null) { walkSurfaceMaterial = cubeGrid.Physics.GetMaterialAt(h.Position + m_character.PositionComp.WorldMatrix.Down * 0.1f); } else if (voxelBase != null && voxelBase.Storage != null && voxelBase.Storage.DataProvider != null) { var materialDefinition = voxelBase.GetMaterialAt(ref h.Position); if (materialDefinition != null) { walkSurfaceMaterial = MyStringHash.GetOrCompute(materialDefinition.MaterialTypeName); } } if (walkSurfaceMaterial.ToString().Length == 0) { walkSurfaceMaterial = MyMaterialType.ROCK; } } } m_hits.Clear(); return(walkSurfaceMaterial); }
public static void PlayContactSound(long entityId, Vector3D position, MyStringHash materialA, MyStringHash materialB, float volume = 1, Func <bool> canHear = null, Func <bool> shouldPlay2D = null) { ProfilerShort.Begin("GetCue"); MySoundPair cue = MyMaterialPropertiesHelper.Static.GetCollisionCue(m_startCue, materialA, materialB); if (!cue.SoundId.IsNull && MyAudio.Static.SourceIsCloseEnoughToPlaySound(position, cue.SoundId)) { MyEntity3DSoundEmitter emitter = MyAudioComponent.TryGetSoundEmitter(); if (emitter == null) { ProfilerShort.End(); return; } ProfilerShort.BeginNextBlock("Emitter lambdas"); MyAudioComponent.ContactSoundsPool.TryAdd(entityId, 0); emitter.StoppedPlaying += (e) => { byte val; MyAudioComponent.ContactSoundsPool.TryRemove(entityId, out val); }; if (MySession.Static.Settings.RealisticSound && MyFakes.ENABLE_NEW_SOUNDS) { Action <MyEntity3DSoundEmitter> remove = null; remove = (e) => { emitter.EmitterMethods[MyEntity3DSoundEmitter.MethodsEnum.CanHear].Remove(canHear); emitter.EmitterMethods[MyEntity3DSoundEmitter.MethodsEnum.ShouldPlay2D].Remove(shouldPlay2D); emitter.StoppedPlaying -= remove; }; emitter.EmitterMethods[MyEntity3DSoundEmitter.MethodsEnum.CanHear].Add(canHear); emitter.EmitterMethods[MyEntity3DSoundEmitter.MethodsEnum.ShouldPlay2D].Add(shouldPlay2D); emitter.StoppedPlaying += remove; } ProfilerShort.BeginNextBlock("PlaySound"); emitter.SetPosition(position); emitter.PlaySound(cue, true); if (emitter.Sound != null) { if (volume != 0) { emitter.Sound.SetVolume(volume); } } } ProfilerShort.End(); }
public MyStringHash TryTransition(MyStringHash source, IReadOnlyCollection <IPowerProvider> providers) { if (providers.Count == 0) { return(MyStringHash.NullOrEmpty); } var specific = _triggersBySource.GetValueOrDefault(source); var global = _triggersBySource.GetValueOrDefault(source); if (specific == null && global == null) { return(MyStringHash.NullOrEmpty); } var providersOn = 0; foreach (var p in providers) { if (p.TryConsumePower(TimeSpan.FromMilliseconds(1))) { providersOn++; } } var allOn = providersOn == providers.Count; var enumerable = Enumerable.Empty <Trigger>(); if (specific != null) { enumerable = enumerable.Concat(specific); } if (global != null) { enumerable = enumerable.Concat(global); } foreach (var type in enumerable) { switch (type.NeedsPower) { case MyObjectBuilder_EquiPowerStateTransitionDefinition.PowerNeeded.None: { if (providersOn == 0) { return(type.To); } if (!type.AutoStart) { continue; } var success = true; foreach (var k in providers) { success &= !k.TryConsumePower(TimeSpan.FromMilliseconds(1)); if (!success) { break; } } if (success) { return(type.To); } break; } case MyObjectBuilder_EquiPowerStateTransitionDefinition.PowerNeeded.Any: { if (providersOn > 0) { return(type.To); } if (!type.AutoStart) { continue; } var success = false; foreach (var k in providers) { success |= k.TryConsumePower(TimeSpan.FromMilliseconds(1)); if (!success) { break; } } if (success) { return(type.To); } break; } default: case MyObjectBuilder_EquiPowerStateTransitionDefinition.PowerNeeded.All: { if (providersOn > 0 && allOn) { return(type.To); } if (!type.AutoStart) { continue; } var success = true; foreach (var k in providers) { success &= k.TryConsumePower(TimeSpan.FromMilliseconds(1)); if (!success) { break; } } if (success) { return(type.To); } break; } } } return(MyStringHash.NullOrEmpty); }
//[TerminalValues(MySpaceTexts.SwitchText_On, MySpaceTexts.SwitchText_Off)] //[Terminal(2, MyPropertyDisplayEnum.Switch, MySpaceTexts.Terminal_UseConveyorSystem, MySpaceTexts.Blank)] //[Obfuscation(Feature = Obfuscator.NoRename, Exclude = true)] //public MyStringId UseConveyorSystemGui //{ // get { return m_useConveyorSystem ? MySpaceTexts.SwitchText_On : MySpaceTexts.SwitchText_Off; } // set // { // if (m_useConveyorSystem != (value == MySpaceTexts.SwitchText_On)) // { // m_useConveyorSystem = (value == MySpaceTexts.SwitchText_On); // OnPropertiesChanged(); // } // } //} //[TerminalValueSetter(2)] //public void RequestUseConveyorSystemChange(MyStringId newVal) //{ // MySyncConveyors.SendChangeUseConveyorSystemRequest(EntityId, newVal == MySpaceTexts.SwitchText_On); //} public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid) { SyncFlag = true; var ob = builder as MyObjectBuilder_SmallMissileLauncher; MyStringHash resourceSinkGroup; var weaponBlockDefinition = BlockDefinition as MyWeaponBlockDefinition; if (weaponBlockDefinition != null && this.GetInventory() == null) { MyInventory inventory = new MyInventory(weaponBlockDefinition.InventoryMaxVolume, new Vector3(1.2f, 0.98f, 0.98f), MyInventoryFlags.CanReceive); Components.Add <MyInventoryBase>(inventory); resourceSinkGroup = weaponBlockDefinition.ResourceSinkGroup; } else { if (this.GetInventory() == null) // this could be already inicialized object builder { MyInventory inventory = null; if (cubeGrid.GridSizeEnum == MyCubeSize.Small) { inventory = new MyInventory(240.0f / 1000, new Vector3(1.2f, 0.45f, 0.45f), MyInventoryFlags.CanReceive); // 4 missiles } else { inventory = new MyInventory(1140.0f / 1000, new Vector3(1.2f, 0.98f, 0.98f), MyInventoryFlags.CanReceive); // 19 missiles } Components.Add(inventory); } resourceSinkGroup = MyStringHash.GetOrCompute("Defense"); } Debug.Assert(this.GetInventory().Owner == this, "Ownership was not set!"); var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( resourceSinkGroup, MyEnergyConstants.MAX_REQUIRED_POWER_SHIP_GUN, () => (Enabled && IsFunctional) ? ResourceSink.MaxRequiredInput : 0.0f); ResourceSink = sinkComp; ResourceSink.IsPoweredChanged += Receiver_IsPoweredChanged; base.Init(builder, cubeGrid); if (MyFakes.ENABLE_INVENTORY_FIX) { FixSingleInventory(); } ResourceSink.Update(); this.GetInventory().Init(ob.Inventory); m_gunBase.Init(ob.GunBase, BlockDefinition, this); m_shotsLeftInBurst = m_gunBase.ShotsInBurst; AddDebugRenderComponent(new Components.MyDebugRenderComponentDrawPowerReciever(ResourceSink, this)); m_useConveyorSystem.Value = ob.UseConveyorSystem; SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; LoadDummies(); NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME; }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_WeaponDefinition; MyDebug.AssertDebug(ob != null); this.WeaponAmmoDatas = new MyWeaponAmmoData[Enum.GetValues(typeof(MyAmmoType)).Length]; this.WeaponEffects = new MyWeaponEffect[ob.Effects == null ? 0 : ob.Effects.Length]; if (ob.Effects != null) { for (int i = 0; i < ob.Effects.Length; i++) { this.WeaponEffects[i] = new MyWeaponEffect(ob.Effects[i].Action, ob.Effects[i].Dummy, ob.Effects[i].Particle, ob.Effects[i].Loop); } } this.PhysicalMaterial = MyStringHash.GetOrCompute(ob.PhysicalMaterial); this.UseDefaultMuzzleFlash = ob.UseDefaultMuzzleFlash; this.NoAmmoSound = new MySoundPair(ob.NoAmmoSoundName); this.ReloadSound = new MySoundPair(ob.ReloadSoundName); this.SecondarySound = new MySoundPair(ob.SecondarySoundName); this.DeviateShotAngle = MathHelper.ToRadians(ob.DeviateShotAngle); this.ReleaseTimeAfterFire = ob.ReleaseTimeAfterFire; this.MuzzleFlashLifeSpan = ob.MuzzleFlashLifeSpan; this.ReloadTime = ob.ReloadTime; this.AmmoMagazinesId = new MyDefinitionId[ob.AmmoMagazines.Length]; for (int i = 0; i < this.AmmoMagazinesId.Length; i++) { var ammoMagazine = ob.AmmoMagazines[i]; this.AmmoMagazinesId[i] = new MyDefinitionId(ammoMagazine.Type, ammoMagazine.Subtype); var ammoMagazineDefinition = MyDefinitionManager.Static.GetAmmoMagazineDefinition(this.AmmoMagazinesId[i]); MyAmmoType ammoType = MyDefinitionManager.Static.GetAmmoDefinition(ammoMagazineDefinition.AmmoDefinitionId).AmmoType; string errorMessage = null; switch (ammoType) { case MyAmmoType.HighSpeed: MyDebug.AssertDebug(ob.ProjectileAmmoData != null, "No weapon ammo data specified for projectile ammo"); if (ob.ProjectileAmmoData != null) { this.WeaponAmmoDatas[(int)MyAmmoType.HighSpeed] = new MyWeaponAmmoData(ob.ProjectileAmmoData); } else { errorMessage = string.Format(ErrorMessageTemplate, "projectile", "Projectile"); } break; case MyAmmoType.Missile: MyDebug.AssertDebug(ob.MissileAmmoData != null, "No weapon ammo data specified for missile ammo"); if (ob.MissileAmmoData != null) { this.WeaponAmmoDatas[(int)MyAmmoType.Missile] = new MyWeaponAmmoData(ob.MissileAmmoData); } else { errorMessage = string.Format(ErrorMessageTemplate, "missile", "Missile"); } break; default: throw new NotImplementedException(); } if (!string.IsNullOrEmpty(errorMessage)) { MyDefinitionErrors.Add(Context, errorMessage, TErrorSeverity.Critical); } } }
public override void Init(MyObjectBuilder_EntityBase objectBuilder) { if (objectBuilder.SubtypeName != null && objectBuilder.SubtypeName.Length > 0) { PhysicalObject = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_PhysicalGunObject>(objectBuilder.SubtypeName + "Item"); m_physItemDef = MyDefinitionManager.Static.GetPhysicalItemDefinition(new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), objectBuilder.SubtypeName + "Item")); } else { PhysicalObject = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_PhysicalGunObject>("HandDrillItem"); m_physItemDef = MyDefinitionManager.Static.GetPhysicalItemDefinition(new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), "HandDrillItem")); } (PositionComp as MyPositionComponent).WorldPositionChanged = WorldPositionChanged; m_handItemDefId = objectBuilder.GetId(); var definition = MyDefinitionManager.Static.TryGetHandItemDefinition(ref m_handItemDefId); m_speedMultiplier = 1f / (definition as MyHandDrillDefinition).SpeedMultiplier; m_drillBase = new MyDrillBase(this, MyDrillConstants.DRILL_HAND_DUST_EFFECT, MyDrillConstants.DRILL_HAND_DUST_STONES_EFFECT, MyDrillConstants.DRILL_HAND_SPARKS_EFFECT, new MyDrillSensorRayCast(-0.5f, 1.8f), new MyDrillCutOut(0.5f, 0.35f * (definition as MyHandDrillDefinition).DistanceMultiplier), SPIKE_SLOWDOWN_TIME_IN_SECONDS, floatingObjectSpawnOffset: -0.25f, floatingObjectSpawnRadius: 1.4f * 0.25f ); m_drillBase.VoxelHarvestRatio = MyDrillConstants.VOXEL_HARVEST_RATIO * (definition as MyHandDrillDefinition).HarvestRatioMultiplier; AddDebugRenderComponent(new Components.MyDebugRenderCompomentDrawDrillBase(m_drillBase)); base.Init(objectBuilder); var physDefinition = MyDefinitionManager.Static.GetPhysicalItemDefinition(definition.PhysicalItemId); Init(null, physDefinition.Model, null, null, null); Render.CastShadows = true; Render.NeedsResolveCastShadow = false; m_spike = Subparts["Spike"]; m_spikeBasePos = m_spike.PositionComp.LocalMatrix.Translation; m_drillBase.IgnoredEntities.Add(this); m_drillBase.OnWorldPositionChanged(PositionComp.WorldMatrix); PhysicalObject.GunEntity = (MyObjectBuilder_EntityBase)objectBuilder.Clone(); PhysicalObject.GunEntity.EntityId = this.EntityId; NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME; m_oreDetectorBase.DetectionRadius = 20; m_oreDetectorBase.OnCheckControl = OnCheckControl; var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( MyStringHash.GetOrCompute("Utility"), MyEnergyConstants.REQUIRED_INPUT_HAND_DRILL, () => m_tryingToDrill ? SinkComp.MaxRequiredInput : 0f); SinkComp = sinkComp; foreach (ToolSound toolSound in definition.ToolSounds) { if (toolSound.type == null || toolSound.subtype == null || toolSound.sound == null) { continue; } if (toolSound.type.Equals("Main")) { if (toolSound.subtype.Equals("Idle")) { m_drillBase.m_idleSoundLoop = new MySoundPair(toolSound.sound); } if (toolSound.subtype.Equals("Soundset")) { m_drillBase.m_drillMaterial = MyStringHash.GetOrCompute(toolSound.sound); } } } }
public MySoundPair GetCollisionCueWithMass(MyStringId type, MyStringHash materialType1, MyStringHash materialType2, ref float volume, float?mass = null, float velocity = 0f) { Dictionary <MyStringHash, Dictionary <MyStringHash, MaterialProperties> > typeDic; if (MaterialDictionary.TryGetValue(type, out typeDic)) { Dictionary <MyStringHash, MaterialProperties> materialDic; if (typeDic.TryGetValue(materialType1, out materialDic)) { MaterialProperties result; if (materialDic.TryGetValue(materialType2, out result)) { if (mass == null || result.ImpactSoundCues == null || result.ImpactSoundCues.Count == 0) { return(result.Sound); } else { int bestSoundIndex = -1; float bestSoundMass = -1; for (int i = 0; i < result.ImpactSoundCues.Count; i++) { if (mass >= result.ImpactSoundCues[i].Mass && result.ImpactSoundCues[i].Mass > bestSoundMass && velocity >= result.ImpactSoundCues[i].minVelocity) { bestSoundIndex = i; bestSoundMass = result.ImpactSoundCues[i].Mass; } } if (bestSoundIndex >= 0) { volume = 0.25f + 0.75f * MyMath.Clamp((velocity - result.ImpactSoundCues[bestSoundIndex].minVelocity) / (result.ImpactSoundCues[bestSoundIndex].maxVolumeVelocity - result.ImpactSoundCues[bestSoundIndex].minVelocity), 0f, 1f); return(result.ImpactSoundCues[bestSoundIndex].SoundCue); } else { return(result.Sound); } } } } } return(MySoundPair.Empty); }
void DrawSkinSelector(MatrixD camMatrix, Vector3D worldPos, float scaleFOV, float bgAlpha) { PlayerInfo localInfo = Main.Palette.LocalInfo; List <SkinInfo> shownSkins = Main.Palette.SkinsForHUD; if (localInfo == null || shownSkins == null || !localInfo.ApplySkin || !Main.Palette.HasAnySkin) { return; } float iconSize = 0.0024f * scaleFOV; float selectedIconSize = 0.003f * scaleFOV; MyStringHash selectedSkinId = localInfo.SelectedSkin; double iconSpacingAdd = (selectedIconSize - iconSize); // 0.0012 * scaleFOV; double iconSpacingWidth = (iconSize * 2) + iconSpacingAdd; float iconBgSpacingAddWidth = 0.0004f * scaleFOV; float iconBgSpacingAddHeight = 0.0006f * scaleFOV; //float iconBgSpacingAddWidth = 0.0006f * scaleFOV; //float iconBgSpacingAddHeight = 0.0008f * scaleFOV; Vector3D pos = worldPos; if (localInfo.ApplyColor) { pos += camMatrix.Up * (0.0075f * scaleFOV); } DrawSkinNameText(localInfo.SelectedSkinInfo); const int MAX_VIEW_SKINS = 7; // must be an odd number. const int MAX_VIEW_SKINS_HALF = ((MAX_VIEW_SKINS - 1) / 2); const double MAX_VIEW_SKINS_HALF_D = (MAX_VIEW_SKINS / 2d); //const double MAX_VIEW_SKINS_HALF_D_BG = ((MAX_VIEW_SKINS - 4) / 2d); int showSkinsCount = shownSkins.Count; if (showSkinsCount >= MAX_VIEW_SKINS) // scrolling skin bar { //var bgPos = pos + camMatrix.Right * ((iconSpacingWidth * 0.5) - (iconSpacingWidth * 0.5)); //MyTransparentGeometry.AddBillboardOriented(MATERIAL_PALETTE_BACKGROUND, PALETTE_COLOR_BG * bgAlpha, bgPos, camMatrix.Left, camMatrix.Up, (float)(iconSpacingWidth * MAX_VIEW_SKINS_HALF_D_BG) + iconBgSpacingAddWidth, iconSize + iconBgSpacingAddHeight, Vector2.Zero, UI_BG_BLENDTYPE); pos += camMatrix.Left * ((iconSpacingWidth * MAX_VIEW_SKINS_HALF_D) - (iconSpacingWidth * 0.5)); int skinIndex = 0; for (int i = 0; i < showSkinsCount; ++i) { SkinInfo skin = shownSkins[i]; if (skin.SubtypeId == selectedSkinId) { skinIndex = i; break; } } const float MIN_ALPHA = 0.5f; // alpha of the skin icon on the edge of the scrollable bar float alphaSubtractStep = ((1f - MIN_ALPHA) / MAX_VIEW_SKINS_HALF); int index = skinIndex - MAX_VIEW_SKINS_HALF; for (int a = -MAX_VIEW_SKINS_HALF; a <= MAX_VIEW_SKINS_HALF; ++a) { if (index < 0) { index = showSkinsCount + index; } if (index >= showSkinsCount) { index %= showSkinsCount; } SkinInfo skin = shownSkins[index]; float alpha = 1f - (Math.Abs(a) * alphaSubtractStep); if (selectedSkinId == skin.SubtypeId) { MyTransparentGeometry.AddBillboardOriented(MATERIAL_PALETTE_COLOR, Color.White, pos, camMatrix.Left, camMatrix.Up, selectedIconSize, selectedIconSize, Vector2.Zero, GUI_FG_BLENDTYPE); } MyTransparentGeometry.AddBillboardOriented(skin.Icon, Color.White * alpha, pos, camMatrix.Left, camMatrix.Up, iconSize, iconSize, Vector2.Zero, GUI_FG_BLENDTYPE); pos += camMatrix.Right * iconSpacingWidth; index++; } } else // static skin bar with moving selection { double halfOwnedSkins = showSkinsCount * 0.5; //MyTransparentGeometry.AddBillboardOriented(MATERIAL_PALETTE_BACKGROUND, PALETTE_COLOR_BG * bgAlpha, pos, camMatrix.Left, camMatrix.Up, (float)(iconSpacingWidth * halfOwnedSkins) + iconBgSpacingAddWidth, iconSize + iconBgSpacingAddHeight, Vector2.Zero, UI_BG_BLENDTYPE); pos += camMatrix.Left * ((iconSpacingWidth * halfOwnedSkins) - (iconSpacingWidth * 0.5)); foreach (SkinInfo skin in shownSkins) { if (selectedSkinId == skin.SubtypeId) { MyTransparentGeometry.AddBillboardOriented(MATERIAL_PALETTE_COLOR, Color.White, pos, camMatrix.Left, camMatrix.Up, selectedIconSize, selectedIconSize, Vector2.Zero, GUI_FG_BLENDTYPE); } MyTransparentGeometry.AddBillboardOriented(skin.Icon, Color.White, pos, camMatrix.Left, camMatrix.Up, iconSize, iconSize, Vector2.Zero, GUI_FG_BLENDTYPE); pos += camMatrix.Right * iconSpacingWidth; } } }
private bool IsEdgeVisible(MyFourEdgeInfo edgeInfo, out int modelId) { int[] numArray; modelId = 0; m_edgesToCompare.Clear(); if (edgeInfo.Full) { return(false); } for (int i = 0; i < 4; i++) { Color color; MyStringHash hash2; MyStringHash hash3; Base27Directions.Direction direction; Base27Directions.Direction direction2; if (edgeInfo.GetNormalInfo(i, out color, out hash3, out hash2, out direction, out direction2)) { EdgeInfoNormal item = new EdgeInfoNormal { Normal = Base27Directions.GetVector(direction), Color = color, SkinSubtypeId = hash3, EdgeModel = hash2 }; m_edgesToCompare.Add(item); item = new EdgeInfoNormal { Normal = Base27Directions.GetVector(direction2), Color = color, SkinSubtypeId = hash3, EdgeModel = hash2 }; m_edgesToCompare.Add(item); } } if (m_edgesToCompare.Count == 0) { return(false); } bool flag = m_edgesToCompare.Count == 4; MyStringHash edgeModel = m_edgesToCompare[0].EdgeModel; int index = 0; while (index < m_edgesToCompare.Count) { int num6 = index + 1; while (true) { if (num6 < m_edgesToCompare.Count) { if (!MyUtils.IsZero(m_edgesToCompare[index].Normal + m_edgesToCompare[num6].Normal, 0.1f)) { num6++; continue; } m_edgesToCompare.RemoveAt(num6); m_edgesToCompare.RemoveAt(index); index--; } index++; break; } } if (m_edgesToCompare.Count == 1) { return(false); } bool flag2 = false; bool flag3 = false; bool flag4 = false; if (m_edgesToCompare.Count > 0) { Color color = m_edgesToCompare[0].Color; MyStringHash skinSubtypeId = m_edgesToCompare[0].SkinSubtypeId; edgeModel = m_edgesToCompare[0].EdgeModel; for (int j = 1; j < m_edgesToCompare.Count; j++) { EdgeInfoNormal normal2 = m_edgesToCompare[j]; flag2 |= normal2.Color != color; flag4 |= normal2.SkinSubtypeId != skinSubtypeId; flag3 |= edgeModel != normal2.EdgeModel; if ((flag2 | flag3) | flag4) { break; } } } if (!((m_edgesToCompare.Count != 1) ? (!((flag2 | flag3) | flag4) ? ((m_edgesToCompare.Count <= 2) ? ((m_edgesToCompare.Count != 0) ? (Math.Abs(Vector3.Dot(m_edgesToCompare[0].Normal, m_edgesToCompare[1].Normal)) <= 0.85f) : flag) : true) : true) : false)) { return(false); } int edgeTypeCount = m_edgeTypeCount; if (!m_edgeModelIdCache.TryGetValue(edgeModel, out numArray)) { MyDefinitionId id = new MyDefinitionId(m_edgeDefinitionType, edgeModel); MyEdgesDefinition edgesDefinition = MyDefinitionManager.Static.GetEdgesDefinition(id); MyEdgesModelSet small = edgesDefinition.Small; MyEdgesModelSet large = edgesDefinition.Large; numArray = new int[m_edgeTypeCount * 2]; MyCubeEdgeType[] values = MyEnum <MyCubeEdgeType> .Values; int num8 = 0; while (true) { int num9; int num10; if (num8 >= values.Length) { m_edgeModelIdCache.Add(edgeModel, numArray); break; } MyCubeEdgeType type = values[num8]; switch (type) { case MyCubeEdgeType.Vertical: num9 = MyModel.GetId(small.Vertical); num10 = MyModel.GetId(large.Vertical); break; case MyCubeEdgeType.Vertical_Diagonal: num9 = MyModel.GetId(small.VerticalDiagonal); num10 = MyModel.GetId(large.VerticalDiagonal); break; case MyCubeEdgeType.Horizontal: num9 = MyModel.GetId(small.Horisontal); num10 = MyModel.GetId(large.Horisontal); break; case MyCubeEdgeType.Horizontal_Diagonal: num9 = MyModel.GetId(small.HorisontalDiagonal); num10 = MyModel.GetId(large.HorisontalDiagonal); break; case MyCubeEdgeType.Hidden: num9 = 0; num10 = 0; break; default: throw new Exception("Unhandled edge type"); } int num11 = (int)type; numArray[num11] = num9; numArray[num11 + edgeTypeCount] = num10; num8++; } } int edgeType = (int)edgeInfo.EdgeType; modelId = numArray[((this.m_gridRenderComponent.GridSizeEnum == MyCubeSize.Large) ? edgeTypeCount : 0) + edgeType]; return(true); }
void SkinSelected(PlayerInfo pi, MyStringHash prevSkin, MyStringHash newSkin) { skinLabelUpdate = true; }
public T GetDefinition <T>(MyStringHash subtypeId) where T : MyDefinitionBase { return(m_definitions.GetDefinition <T>(subtypeId)); }
/// <summary> /// Evaluates what kind of material should be used for this floating object. If material is not defined than returns empty one and throws an assert. /// </summary> /// <param name="originalMaterial">Original material set in this object.</param> /// <returns>Final material.</returns> private MyStringHash EvaluatePhysicsMaterial(MyStringHash originalMaterial) { //Debug.Assert(originalMaterial.String != string.Empty, "No physical material set for this object, please define it in coresponding cbs file"); return(VoxelMaterial != null ? MyMaterialType.ROCK : originalMaterial); }
public void Init(long seed, string generator, double radius) { radius = Math.Max(radius, 1.0); var def = MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(generator)); if (def == null) { throw new Exception($"Cannot load planet generator definition for subtype '{generator}'."); } Generator = def; Radius = radius; Seed = seed; Version = STORAGE_VERSION; Init(); }
private void RunScriptInternal(MyStringHash scriptName) { m_scriptsQueue.Enqueue(scriptName); }
public void DoDamage(float damage, MyStringHash damageType, bool sync, long attackerId) { if (MarkedForClose) { return; } if (sync) { if (!Sync.IsServer) { return; } else { MySyncHelper.DoDamageSynced(this, damage, damageType, attackerId); return; } } MyDamageInformation damageinfo = new MyDamageInformation(false, damage, damageType, attackerId); if (UseDamageSystem) { MyDamageSystem.Static.RaiseBeforeDamageApplied(this, ref damageinfo); } var typeId = Item.Content.TypeId; if (typeId == typeof(MyObjectBuilder_Ore) || typeId == typeof(MyObjectBuilder_Ingot)) { if (Item.Amount < 1) { //TODO: SYNC particle MyParticleEffect effect; if (MyParticlesManager.TryCreateParticleEffect((int)MyParticleEffectsIDEnum.Smoke_Construction, out effect)) { effect.WorldMatrix = WorldMatrix; effect.UserScale = 0.4f; } MyFloatingObjects.RemoveFloatingObject(this); } else { if (Sync.IsServer) { MyFloatingObjects.RemoveFloatingObject(this, (MyFixedPoint)damageinfo.Amount); } } } else { m_health -= (10 + 90 * DamageMultiplier) * damageinfo.Amount; if (UseDamageSystem) { MyDamageSystem.Static.RaiseAfterDamageApplied(this, damageinfo); } if (m_health < 0) { //TODO: SYNC particle MyParticleEffect effect; if (MyParticlesManager.TryCreateParticleEffect((int)MyParticleEffectsIDEnum.Smoke_Construction, out effect)) { effect.WorldMatrix = WorldMatrix; effect.UserScale = 0.4f; } if (Sync.IsServer) { MyFloatingObjects.RemoveFloatingObject(this); } //TODO: dont compare to string? if (Item.Content.SubtypeId == m_explosives && Sync.IsServer) { var expSphere = new BoundingSphere(WorldMatrix.Translation, (float)Item.Amount * 0.01f + 0.5f);// MathHelper.Clamp((float)Item.Amount, 0, 300) * 0.5f); MyExplosionInfo info = new MyExplosionInfo() { PlayerDamage = 0, Damage = 800, ExplosionType = MyExplosionTypeEnum.WARHEAD_EXPLOSION_15, ExplosionSphere = expSphere, LifespanMiliseconds = MyExplosionsConstants.EXPLOSION_LIFESPAN, CascadeLevel = 0, HitEntity = this, ParticleScale = 1, OwnerEntity = this, Direction = WorldMatrix.Forward, VoxelExplosionCenter = expSphere.Center, ExplosionFlags = MyExplosionFlags.AFFECT_VOXELS | MyExplosionFlags.APPLY_FORCE_AND_DAMAGE | MyExplosionFlags.CREATE_DEBRIS | MyExplosionFlags.CREATE_DECALS | MyExplosionFlags.CREATE_PARTICLE_EFFECT | MyExplosionFlags.CREATE_SHRAPNELS | MyExplosionFlags.APPLY_DEFORMATION, VoxelCutoutScale = 0.5f, PlaySound = true, ApplyForceAndDamage = true, ObjectsRemoveDelayInMiliseconds = 40 }; MyExplosions.AddExplosion(ref info); } if (MyFakes.ENABLE_SCRAP && Sync.IsServer) { if (Item.Content.SubtypeId == ScrapBuilder.SubtypeId) { return; } var contentDefinitionId = Item.Content.GetId(); if (contentDefinitionId.TypeId == typeof(MyObjectBuilder_Component)) { var definition = MyDefinitionManager.Static.GetComponentDefinition((Item.Content as MyObjectBuilder_Component).GetId()); if (MyRandom.Instance.NextFloat() < definition.DropProbability) { MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(Item.Amount * 0.8f, ScrapBuilder), PositionComp.GetPosition(), WorldMatrix.Forward, WorldMatrix.Up); } } } if (UseDamageSystem) { MyDamageSystem.Static.RaiseDestroyed(this, damageinfo); } } } return; }
private static void SendScriptRequest(MyStringHash stringId) { MyMultiplayer.RaiseStaticEvent(x => RunScriptRequest, stringId); }
public MySoundPair GetCollisionCue(MyStringId type, MyStringHash materialType1, MyStringHash materialType2) { Dictionary <MyStringHash, Dictionary <MyStringHash, MaterialProperties> > typeDic; if (MaterialDictionary.TryGetValue(type, out typeDic)) { Dictionary <MyStringHash, MaterialProperties> materialDic; if (typeDic.TryGetValue(materialType1, out materialDic)) { MaterialProperties result; if (materialDic.TryGetValue(materialType2, out result)) { return(result.Sound); } } } return(MySoundPair.Empty); }
private MyPlanetGeneratorDefinition GetDefinition(string name) { return(MyDefinitionManager.Static.GetDefinition <MyPlanetGeneratorDefinition>(MyStringHash.GetOrCompute(name))); }
public bool Drill(bool collectOre = true, bool performCutout = true, bool assignDamagedMaterial = false) { ProfilerShort.Begin("MyDrillBase::Drill()"); bool drillingSuccess = false; MySoundPair sound = null; if ((m_drillEntity.Parent != null) && (m_drillEntity.Parent.Physics != null) && !m_drillEntity.Parent.Physics.Enabled) { return(false); } if (performCutout) { StopSparkParticles(); StopDustParticles(); var entitiesInRange = m_sensor.EntitiesInRange; MyStringHash targetMaterial = MyStringHash.NullOrEmpty; bool targetIsBlock = false; foreach (var entry in entitiesInRange) { drillingSuccess = false; var entity = entry.Value.Entity; if (entity.MarkedForClose) { continue; } if (entity is MyCubeGrid) { var grid = entity as MyCubeGrid; if (grid.Physics != null && grid.Physics.Enabled) { drillingSuccess = TryDrillBlocks(grid, entry.Value.DetectionPoint, !Sync.IsServer, out targetMaterial); targetIsBlock = true; } if (drillingSuccess) { m_initialHeatup = false; CreateParticles(entry.Value.DetectionPoint, false, true, false); } } else if (entity is MyVoxelBase) { ProfilerShort.Begin("Drill voxel map"); var voxels = entity as MyVoxelBase; drillingSuccess = TryDrillVoxels(voxels, entry.Value.DetectionPoint, collectOre, !Sync.IsServer, assignDamagedMaterial); ProfilerShort.BeginNextBlock("Create particles"); if (drillingSuccess) { Vector3D drillHitPoint = entry.Value.DetectionPoint; if (targetMaterial == MyStringHash.NullOrEmpty) { var voxelMaterial = voxels.GetMaterialAt(ref drillHitPoint); if (voxelMaterial != null) { targetMaterial = MyStringHash.GetOrCompute(voxelMaterial.MaterialTypeName); } } CreateParticles(entry.Value.DetectionPoint, true, false, true); } ProfilerShort.End(); } else if (entity is MyFloatingObject) { var sphere = (BoundingSphereD)m_cutOut.Sphere; sphere.Radius *= 1.33f; if (entity.GetIntersectionWithSphere(ref sphere)) { MyFloatingObject flObj = entity as MyFloatingObject; if (Sync.IsServer) { if (flObj.Item.Content.TypeId == typeof(MyObjectBuilder_Ore)) { var invOwn = (m_drillEntity != null && m_drillEntity.HasInventory) ? m_drillEntity : null; if (invOwn == null) { invOwn = (m_drillEntity as MyHandDrill).Owner; } System.Diagnostics.Debug.Assert((invOwn.GetInventory(0) as MyInventory) != null, "Null or unexpected inventory type!"); (invOwn.GetInventory(0) as MyInventory).TakeFloatingObject(flObj); } else { (entity as MyFloatingObject).DoDamage(70, MyDamageType.Drill, true, attackerId: m_drillEntity != null ? m_drillEntity.EntityId : 0); } } drillingSuccess = true; } } else if (entity is MyCharacter) { var sphere = (BoundingSphereD)m_cutOut.Sphere; sphere.Radius *= 0.8f; var character = entity as MyCharacter; if (targetMaterial == MyStringHash.NullOrEmpty) { targetMaterial = MyStringHash.GetOrCompute((entity as MyCharacter).Definition.PhysicalMaterial); } if (entity.GetIntersectionWithSphere(ref sphere)) { //MyRenderProxy.DebugDrawSphere(sphere.Center, sphere.Radius, Color.Green.ToVector3(), 1, true); //damage tracking if ((m_drillEntity is MyHandDrill) && (m_drillEntity as MyHandDrill).Owner == MySession.Static.LocalCharacter && character != MySession.Static.LocalCharacter && character.IsDead == false) { MySession.Static.TotalDamageDealt += 20; } if (Sync.IsServer) { character.DoDamage(20, MyDamageType.Drill, true, attackerId: m_drillEntity != null ? m_drillEntity.EntityId : 0); } drillingSuccess = true; } else { BoundingSphereD headSphere = new BoundingSphereD(character.PositionComp.WorldMatrix.Translation + character.WorldMatrix.Up * 1.25f, 0.6f); //MyRenderProxy.DebugDrawSphere(headSphere.Center, headSphere.Radius, Color.Red.ToVector3(), 1, false); if (headSphere.Intersects(sphere)) { //MyRenderProxy.DebugDrawSphere(sphere.Center, sphere.Radius, Color.Green.ToVector3(), 1, true); //damage tracking if ((m_drillEntity is MyHandDrill) && (m_drillEntity as MyHandDrill).Owner == MySession.Static.LocalCharacter && character != MySession.Static.LocalCharacter && character.IsDead == false) { MySession.Static.TotalDamageDealt += 20; } if (Sync.IsServer) { character.DoDamage(20, MyDamageType.Drill, true, attackerId: m_drillEntity != null ? m_drillEntity.EntityId : 0); } drillingSuccess = true; } } } if (drillingSuccess) { m_lastContactTime = MySandboxGame.TotalGamePlayTimeInMilliseconds; } } if (targetMaterial != null && targetMaterial != MyStringHash.NullOrEmpty) { sound = MyMaterialPropertiesHelper.Static.GetCollisionCue(MyMaterialPropertiesHelper.CollisionType.Start, m_drillMaterial, targetMaterial); if (sound == null || sound == MySoundPair.Empty)//target material was not set in definition - using metal/rock sound { if (targetIsBlock) { targetMaterial = m_metalMaterial; } else { targetMaterial = m_rockMaterial; } } sound = MyMaterialPropertiesHelper.Static.GetCollisionCue(MyMaterialPropertiesHelper.CollisionType.Start, m_drillMaterial, targetMaterial); } } if (sound != null && sound != MySoundPair.Empty) { StartLoopSound(sound); } else { StartIdleSound(m_idleSoundLoop); } if (!IsDrilling) { IsDrilling = true; m_animationLastUpdateTime = MySandboxGame.TotalGamePlayTimeInMilliseconds; } ProfilerShort.End(); return(drillingSuccess); }
protected virtual bool TryDrillBlocks(MyCubeGrid grid, Vector3 worldPoint, bool onlyCheck, out MyStringHash blockMaterial) { var invWorld = grid.PositionComp.WorldMatrixNormalizedInv; var gridLocalPosCenter = Vector3.Transform(m_sensor.Center, invWorld); var gridLocalPos = Vector3.Transform(m_sensor.FrontPoint, invWorld); var gridLocalTarget = Vector3.Transform(worldPoint, invWorld); var gridSpacePos = Vector3I.Round(gridLocalPos / grid.GridSize); var block = grid.GetCubeBlock(gridSpacePos); if (block != null) { if (block.BlockDefinition.PhysicalMaterial.Id.SubtypeId == MyStringHash.NullOrEmpty) { blockMaterial = m_metalMaterial; } else { blockMaterial = block.BlockDefinition.PhysicalMaterial.Id.SubtypeId; } } else { blockMaterial = MyStringHash.NullOrEmpty; } int createDebris = 0; if (!onlyCheck) { if (block != null && block is IMyDestroyableObject && block.CubeGrid.BlocksDestructionEnabled) { var destroyable = (block as IMyDestroyableObject); destroyable.DoDamage(60, MyDamageType.Drill, Sync.IsServer, attackerId: m_drillEntity != null ? m_drillEntity.EntityId : 0); createDebris = grid.Physics.ApplyDeformation(0.25f, 1.5f, 2f, gridLocalTarget, Vector3.Normalize(gridLocalPos - gridLocalPosCenter), MyDamageType.Drill, attackerId: m_drillEntity != null ? m_drillEntity.EntityId : 0); } } m_target = createDebris != 0 ? null : block; bool success = false; if (block != null) { if (createDebris != 0) { BoundingSphereD bsphere = m_cutOut.Sphere; BoundingBoxD aabb = BoundingBoxD.CreateFromSphere(bsphere); MyDebris.Static.CreateExplosionDebris(ref bsphere, block.CubeGrid, ref aabb, 0.3f); } success = true; } return(success); }
private static MyEntity SpawnBagAround(MyEntity itemOwner, MyContainerDefinition bagDefinition, int sideCheckCount = 3, int frontCheckCount = 2, int upCheckCount = 5, float stepSize = 1f) { MatrixD xd; Vector3D?nullable = null; MyModel modelOnlyData = null; foreach (MyContainerDefinition.DefaultComponent component in bagDefinition.DefaultComponents) { if (typeof(MyObjectBuilder_ModelComponent).IsAssignableFrom((System.Type)component.BuilderType)) { MyComponentDefinitionBase componentDefinition = null; MyStringHash subtypeId = bagDefinition.Id.SubtypeId; if (component.SubtypeId != null) { subtypeId = component.SubtypeId.Value; } if (MyComponentContainerExtension.TryGetComponentDefinition(component.BuilderType, subtypeId, out componentDefinition)) { MyModelComponentDefinition definition = componentDefinition as MyModelComponentDefinition; if (definition != null) { modelOnlyData = MyModels.GetModelOnlyData(definition.Model); } } break; } } if (modelOnlyData == null) { return(null); } float radius = modelOnlyData.BoundingBox.HalfExtents.Max(); HkShape shape = (HkShape) new HkSphereShape(radius); try { Vector3 vector3; Vector3 vector5; Vector3 vector6; int num4; Vector3D vectord3; int num5; Vector3D translation = itemOwner.PositionComp.WorldMatrix.Translation; float num2 = radius * stepSize; Vector3 up = -MyGravityProviderSystem.CalculateNaturalGravityInPoint(itemOwner.PositionComp.WorldMatrix.Translation); if (up == Vector3.Zero) { up = Vector3.Up; } else { up.Normalize(); } up.CalculatePerpendicularVector(out vector3); Vector3 vector4 = Vector3.Cross(vector3, up); vector4.Normalize(); Quaternion identity = Quaternion.Identity; Vector3[] vectorArray = new Vector3[] { vector3, vector4, -vector3, -vector4 }; Vector3[] vectorArray2 = new Vector3[] { vector4, -vector3, -vector4, vector3 }; int index = 0; goto TR_0026; TR_000D: if (nullable == null) { MyOrientedBoundingBoxD xd3 = new MyOrientedBoundingBoxD(itemOwner.PositionComp.LocalAABB, itemOwner.PositionComp.WorldMatrix); Vector3D[] corners = new Vector3D[8]; xd3.GetCorners(corners, 0); float minValue = float.MinValue; Vector3D[] vectordArray2 = corners; int num8 = 0; while (true) { if (num8 >= vectordArray2.Length) { nullable = new Vector3D?(itemOwner.PositionComp.WorldMatrix.Translation); if (minValue > 0f) { nullable = new Vector3D?(xd3.Center + (minValue * up)); } break; } float num9 = Vector3.Dot((Vector3)(vectordArray2[num8] - xd3.Center), up); minValue = Math.Max(minValue, num9); num8++; } } goto TR_0003; TR_000E: index++; goto TR_0026; TR_000F: num4++; goto TR_0022; TR_0010: num5++; TR_001E: while (true) { if (num5 >= sideCheckCount) { goto TR_000F; } else if (nullable == null) { for (int i = 0; (i < upCheckCount) && (nullable == null); i++) { Vector3D pos = (vectord3 + ((num5 * num2) * vector6)) + ((i * num2) * up); if (MyEntities.IsInsideWorld(pos) && !MyEntities.IsShapePenetrating(shape, ref pos, ref identity, 15)) { BoundingSphereD sphere = new BoundingSphereD(pos, (double)radius); if (MySession.Static.VoxelMaps.GetOverlappingWithSphere(ref sphere) == null) { nullable = new Vector3D?(pos); break; } } } } else { goto TR_000F; } break; } goto TR_0010; TR_0022: while (true) { if (num4 >= frontCheckCount) { goto TR_000E; } else if (nullable == null) { vectord3 = (((translation + (0.25f * vector5)) + (radius * vector5)) + ((num4 * num2) * vector5)) - (((0.5f * (sideCheckCount - 1)) * num2) * vector6); num5 = 0; } else { goto TR_000E; } break; } goto TR_001E; TR_0026: while (true) { if (index >= vectorArray.Length) { goto TR_000D; } else if (nullable == null) { vector5 = vectorArray[index]; vector6 = vectorArray2[index]; num4 = 0; } else { goto TR_000D; } break; } goto TR_0022; } finally { shape.RemoveReference(); } TR_0003: xd = itemOwner.PositionComp.WorldMatrix; xd.Translation = nullable.Value; MyEntity entity = MyEntities.CreateFromComponentContainerDefinitionAndAdd(bagDefinition.Id, false, true); if (entity == null) { return(null); } entity.PositionComp.SetWorldMatrix(xd, null, false, true, true, false, false, false); entity.Physics.LinearVelocity = Vector3.Zero; entity.Physics.AngularVelocity = Vector3.Zero; return(entity); }
private void StateChanged(MyStringHash oldState, MyStringHash newState) { MarkForUpdate(); }
public void DoDamage(float damage, MyStringHash damageType, bool sync, MyHitInfo?hitInfo, long attackerId) { GameLogic.DoDamage(damage, damageType, sync, hitInfo, attackerId); }
private MySoundPair SelectSound() { MySoundPair soundPair = EmptySoundPair; MyCharacterDefinition myCharDefinition = m_character.Definition; MyStringHash physMaterial = MyStringHash.GetOrCompute(myCharDefinition.PhysicalMaterial); m_isWalking = false; bool updateEmitterSounds = false; MyCharacterMovementEnum movementState = m_character.GetCurrentMovementState(); switch (movementState) { case MyCharacterMovementEnum.Walking: case MyCharacterMovementEnum.BackWalking: case MyCharacterMovementEnum.WalkingLeftFront: case MyCharacterMovementEnum.WalkingRightFront: case MyCharacterMovementEnum.WalkingLeftBack: case MyCharacterMovementEnum.WalkingRightBack: case MyCharacterMovementEnum.WalkStrafingLeft: case MyCharacterMovementEnum.WalkStrafingRight: { if (m_character.Breath != null) { m_character.Breath.CurrentState = MyCharacterBreath.State.Calm; } soundPair = MyMaterialPropertiesHelper.Static.GetCollisionCue(MovementSoundType.Walk, physMaterial, RayCastGround()); m_isWalking = true; } break; case MyCharacterMovementEnum.Running: case MyCharacterMovementEnum.Backrunning: case MyCharacterMovementEnum.RunStrafingLeft: case MyCharacterMovementEnum.RunStrafingRight: case MyCharacterMovementEnum.RunningRightFront: case MyCharacterMovementEnum.RunningRightBack: case MyCharacterMovementEnum.RunningLeftFront: case MyCharacterMovementEnum.RunningLeftBack: { if (m_character.Breath != null) { m_character.Breath.CurrentState = MyCharacterBreath.State.Heated; } soundPair = MyMaterialPropertiesHelper.Static.GetCollisionCue(MovementSoundType.Run, physMaterial, RayCastGround()); m_isWalking = true; } break; case MyCharacterMovementEnum.CrouchWalking: case MyCharacterMovementEnum.CrouchBackWalking: case MyCharacterMovementEnum.CrouchWalkingLeftFront: case MyCharacterMovementEnum.CrouchWalkingRightFront: case MyCharacterMovementEnum.CrouchWalkingLeftBack: case MyCharacterMovementEnum.CrouchWalkingRightBack: case MyCharacterMovementEnum.CrouchStrafingLeft: case MyCharacterMovementEnum.CrouchStrafingRight: { if (m_character.Breath != null) { m_character.Breath.CurrentState = MyCharacterBreath.State.Calm; } soundPair = MyMaterialPropertiesHelper.Static.GetCollisionCue(MovementSoundType.CrouchWalk, physMaterial, RayCastGround()); m_isWalking = true; } break; case MyCharacterMovementEnum.Crouching: case MyCharacterMovementEnum.Standing: { if (m_character.Breath != null) { m_character.Breath.CurrentState = MyCharacterBreath.State.Calm; } var previousMovementState = m_character.GetPreviousMovementState(); var currentMovementState = m_character.GetCurrentMovementState(); if (previousMovementState != currentMovementState && (previousMovementState == MyCharacterMovementEnum.Standing || previousMovementState == MyCharacterMovementEnum.Crouching)) { soundPair = (currentMovementState == MyCharacterMovementEnum.Standing) ? CharacterSounds[(int)CharacterSoundsEnum.CROUCH_UP_SOUND] : CharacterSounds[(int)CharacterSoundsEnum.CROUCH_DOWN_SOUND]; } } break; case MyCharacterMovementEnum.Sprinting: { if (m_character.Breath != null) { m_character.Breath.CurrentState = MyCharacterBreath.State.VeryHeated; } soundPair = MyMaterialPropertiesHelper.Static.GetCollisionCue(MovementSoundType.Sprint, physMaterial, RayCastGround()); m_isWalking = true; } break; case MyCharacterMovementEnum.Jump: { if (!m_jumpReady) { break; } m_jumpReady = false; m_character.SetPreviousMovementState(m_character.GetCurrentMovementState()); var emitter = MyAudioComponent.TryGetSoundEmitter(); // We need to use another emitter otherwise the sound would be cut by silence next frame if (emitter != null) { emitter.Entity = m_character; emitter.PlaySingleSound(CharacterSounds[(int)CharacterSoundsEnum.JUMP_SOUND]); } if ((m_standingOnGrid != null || m_standingOnVoxel != null) && ShouldUpdateSoundEmitters) { updateEmitterSounds = true; } m_standingOnGrid = null; m_standingOnVoxel = null; } break; case MyCharacterMovementEnum.Flying: { if (m_character.Breath != null) { m_character.Breath.CurrentState = MyCharacterBreath.State.Calm; } if (m_character.JetpackComp != null && m_jetpackMinIdleTime <= 0f && m_character.JetpackComp.FinalThrust.LengthSquared() >= 50000f) { soundPair = CharacterSounds[(int)CharacterSoundsEnum.JETPACK_RUN_SOUND]; m_jetpackSustainTimer = Math.Min(JETPACK_TIME_BETWEEN_SOUNDS, m_jetpackSustainTimer + MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS); } else { soundPair = CharacterSounds[(int)CharacterSoundsEnum.JETPACK_IDLE_SOUND]; m_jetpackSustainTimer = Math.Max(0f, m_jetpackSustainTimer - MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS); } m_jetpackMinIdleTime -= MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS; if ((m_standingOnGrid != null || m_standingOnVoxel != null) && ShouldUpdateSoundEmitters) { updateEmitterSounds = true; } m_standingOnGrid = null; m_standingOnVoxel = null; } break; case MyCharacterMovementEnum.Falling: { if (m_character.Breath != null) { m_character.Breath.CurrentState = MyCharacterBreath.State.Calm; } if ((m_standingOnGrid != null || m_standingOnVoxel != null) && ShouldUpdateSoundEmitters) { updateEmitterSounds = true; } m_standingOnGrid = null; m_standingOnVoxel = null; } break; default: { } break; } //MyRenderProxy.DebugDrawText2D(Vector2.Zero, movementState.ToString(), Color.Red, 1.0f); if (movementState != MyCharacterMovementEnum.Flying) { m_jetpackSustainTimer = 0f; m_jetpackMinIdleTime = 0.5f; } if (updateEmitterSounds) { MyEntity3DSoundEmitter.UpdateEntityEmitters(true, true, false); } return(soundPair); }