protected override void InitializeCore() { base.InitializeCore(); backgroundEffect = new EffectInstance(new Effect(RenderSystem.GraphicsDevice, BackgroundEffect.Bytecode) { Name = "BackgroundEffect" }); spriteBatch = new SpriteBatch(RenderSystem.GraphicsDevice) { VirtualResolution = new Vector3(1) }; }
protected override void Process(float deltaTime, EffectInstance instance, Particle[] particles, int begin, int end) { for (int i = begin; i < end; ++i) { Vector3 d = particles[i].m_position - Center; particles[i].m_velocity = (Accelerate ? d : Vector3.Normalize(d)) * Strength; } }
protected override void Process(float deltaTime, EffectInstance instance, Particle[] particles, int begin, int end) { var v = Acceleration * deltaTime; for (int i = begin; i < end; ++i) { particles[i].m_velocity += v; } }
protected override void Process(float deltaTime, EffectInstance instance, Particle[] particles, int begin, int end) { for (int i = begin; i < end; ++i) { m_phase = (m_phase + AngularInterval) % 360.0f; float sin = (float)Math.Sin(MathHelper.ToRadians(m_phase)); float cos = (float)Math.Cos(MathHelper.ToRadians(m_phase)); particles[i].m_position = Center + XAxis * sin + YAxis * cos; particles[i].m_rotation = m_phase + AngularOffset; } }
protected override void Process(float deltaTime, EffectInstance instance, Particle[] particles, int begin, int end) { var effectInstance = instance.SystemInstance.EffectInstances.FirstOrDefault(fx => fx.Effect.Name == EffectName); if (effectInstance == null || effectInstance == instance) { return; } if (end > begin) { effectInstance.IsEmitting = particles[begin].m_age <= Duration; } }
protected override void Process(float deltaTime, EffectInstance instance, Particle[] particles, int begin, int end) { Vector3 halfDim = Dimensions * 0.5f; for (int i = begin; i < end; ++i) { particles[i].m_position = new Vector3 { X = RandomNumber.Generate(-halfDim.X, halfDim.X), Y = RandomNumber.Generate(-halfDim.Y, halfDim.Y), Z = RandomNumber.Generate(-halfDim.Z, halfDim.Z), } + Center; } }
protected override void Process(float deltaTime, EffectInstance instance, Particle[] particles, int begin, int end) { var effectInstance = instance.SystemInstance.EffectInstances.FirstOrDefault(fx => fx.Effect.Name == EffectName); if (effectInstance == null || effectInstance == instance) { return; } for (int i = 0; i < Amount * Math.Max(end - begin, 0); ++i) { effectInstance.Emit(effectInstance.Template); } effectInstance.EndEmit(); }
public override MeshContainer CreateMeshContainer(string name, MeshData meshData, ExtendedMaterial[] materials, EffectInstance[] effectInstances, int[] adjacency, SkinInfo skinInfo) { CustomMeshContainer meshContainer = new CustomMeshContainer(); meshContainer.Name = name; meshContainer.MeshData = meshData; meshContainer.SetAdjacency(adjacency); meshContainer.SetEffects(effectInstances); meshContainer.SkinInfo = skinInfo; meshContainer.OriginalMesh = meshData.Mesh.Clone(meshData.Mesh.Device, meshData.Mesh.CreationOptions, meshData.Mesh.VertexFormat); if (skinInfo != null) { meshContainer.BoneOffsets = new Matrix[skinInfo.BoneCount]; for (int i = 0; i < skinInfo.BoneCount; i++) meshContainer.BoneOffsets[i] = skinInfo.GetBoneOffsetMatrix(i); meshContainer.PaletteEntries = Math.Min(MaxMatrices, meshContainer.SkinInfo.BoneCount); int influences; BoneCombination[] boneCombinations; meshContainer.MeshData.Mesh.Dispose(); meshContainer.MeshData = new MeshData(meshContainer.SkinInfo.ConvertToIndexedBlendedMesh(meshContainer.OriginalMesh, meshContainer.PaletteEntries, adjacency, out influences, out boneCombinations)); meshContainer.Influences = influences; meshContainer.BoneCombinations = boneCombinations; VertexElement[] elements = meshContainer.MeshData.Mesh.GetDeclaration(); for (int i = 0; i < elements.Length; i++) { if (elements[i].Stream == 0xff) break; if (elements[i].Usage == DeclarationUsage.BlendIndices && elements[i].UsageIndex == 0) elements[i].Type = DeclarationType.Color; } meshContainer.MeshData.Mesh.UpdateSemantics(elements); } return meshContainer; }
protected override void Process(float deltaTime, EffectInstance instance, Particle[] particles, int begin, int end) { var effectInstance = instance.SystemInstance.EffectInstances.FirstOrDefault(fx => fx.Effect.Name == EffectName); if (effectInstance == null || effectInstance == instance) { return; } for (int i = begin; i < end; ++i) { if (particles[i].m_position.Z < 0) { particles[i].m_life = 0; // kill the particle var p = effectInstance.Template; p.m_position = particles[i].m_position; p.m_position.Z = 0; effectInstance.Emit(p); } } effectInstance.EndEmit(); }
protected override void Process(float deltaTime, EffectInstance instance, Particle[] particles, int begin, int end) { for (int i = begin; i < end; ++i) { float r3 = RandomNumber.Generate(0, Radius * Radius * Radius); float r = (float)Math.Pow(r3, 1.0 / 3.0); float theta = RandomNumber.Generate(0, MathHelper.TwoPi); float sinTheta = (float)Math.Sin(theta); float cosTheta = (float)Math.Cos(theta); float phi = RandomNumber.Generate(-MathHelper.PiOver2, MathHelper.PiOver2); float sinPhi = (float)Math.Sin(phi); float cosPhi = (float)Math.Cos(phi); particles[i].m_velocity = new Vector3 { X = r * cosTheta * cosPhi, Y = r * sinPhi, Z = r * sinTheta * cosPhi }; } }
public ReplacePerInvocation(Fighter source, SpellLevelRecord spellLevel, EffectInstance effect, Fighter[] targets, MapPoint castPoint, bool critical) : base(source, spellLevel, effect, targets, castPoint, critical) { }
public void GetLists( ArrayList models, out Mesh[] meshes, out Matrix[] localToWorlds, out int[][] adjacencies, out ExtendedMaterial[] materials, out EffectInstance[] effectInstances) { ArrayList meshList = new ArrayList(); ArrayList localToWorldList = new ArrayList(); ArrayList adjacenciesList = new ArrayList(); ArrayList materialList = new ArrayList(); ArrayList effectInstanceList = new ArrayList(); foreach( OpsModel model in models) { OpsFrame.ComputeLocalToWorld( model.HierarchyRoot as OpsFrame , Matrix.Identity ); foreach( OpsMeshContainer mc in model.GetMeshEnumerator()) { meshList.Add( mc.MeshData.Mesh ); adjacenciesList.Add( mc.GetAdjacency() ); localToWorldList.Add( mc.LocalToWorld ); ExtendedMaterial[] oldMtlList = mc.GetMaterials(); EffectInstance[] oldFxList = mc.GetEffectInstances(); System.Diagnostics.Debug.Assert( oldMtlList.Length == oldFxList.Length ); materialList.AddRange( oldMtlList ); effectInstanceList.AddRange( oldFxList ); } } meshes = meshList.ToArray( typeof(Mesh) ) as Mesh[]; localToWorlds = localToWorldList.ToArray( typeof(Matrix) ) as Matrix[]; adjacencies = adjacenciesList.ToArray( typeof(int[]) ) as int[][]; materials = materialList.ToArray( typeof(ExtendedMaterial) ) as ExtendedMaterial[]; effectInstances = effectInstanceList.ToArray( typeof(EffectInstance) ) as EffectInstance[]; }
private EffectInstance GetOrCreateSelectedSpriteEffect() { return(selectedSpriteEffect ?? (selectedSpriteEffect = new EffectInstance(RenderSystem.EffectSystem.LoadEffect("SelectedSprite").WaitForResult()))); }
private EffectInstance GetOrCreatePickingSpriteEffect() { return(pickingSpriteEffect ?? (pickingSpriteEffect = new EffectInstance(RenderSystem.EffectSystem.LoadEffect("SpritePicking").WaitForResult()))); }
protected override void Process(float deltaTime, EffectInstance instance, Particle[] particles, int begin, int end) { if (AnimationType == Modifiers.AnimationType.Constant || AnimationType == Modifiers.AnimationType.Curve && CurveObject == null) { ProcessConstant(m_startValue, deltaTime, particles, begin, end); } else if (AnimationType == Modifiers.AnimationType.Linear) { ProcessLinear(m_startValue, m_finishValue - m_startValue, deltaTime, particles, begin, end); } else { if (CurveObject.Keys.Count == 0) { return; } float duration = CurveObject.Keys.Last().Position; ProcessCurve(CurveObject, duration, deltaTime, particles, begin, end); } }
public StatsBuff(Fighter source, SpellLevelRecord spellLevel, EffectInstance effect, Fighter[] targets, MapPoint castPoint, bool critical) : base(source, spellLevel, effect, targets, castPoint, critical) { }
public LookBuff(Fighter source, Fighter target, short delta, EffectInstance effect, ushort spellId) : base(source, target, delta, effect, spellId) { }
/// <summary> /// Begins a sprite batch rendering using the specified sorting mode and blend state, sampler, depth stencil, rasterizer state objects, plus a custom effect and a 2D transformation matrix. Passing null for any of the state objects selects the default default state objects (BlendState.AlphaBlend, DepthStencilState.Default, RasterizerState.CullCounterClockwise, SamplerState.LinearClamp). Passing a null effect selects the default SpriteBatch Class shader. /// </summary> /// <param name="graphicsContext">The graphics context to use.</param> /// <param name="viewMatrix">The view matrix to use for the batch session</param> /// <param name="projectionMatrix">The projection matrix to use for the batch session</param> /// <param name="sortMode">The sprite drawing order to use for the batch session</param> /// <param name="blendState">The blending state to use for the batch session</param> /// <param name="samplerState">The sampling state to use for the batch session</param> /// <param name="depthStencilState">The depth stencil state to use for the batch session</param> /// <param name="rasterizerState">The rasterizer state to use for the batch session</param> /// <param name="effect">The effect to use for the batch session</param> /// <param name="stencilValue">The value of the stencil buffer to take as reference for the batch session</param> public void Begin(GraphicsContext graphicsContext, Matrix viewMatrix, Matrix projectionMatrix, SpriteSortMode sortMode = SpriteSortMode.Deferred, BlendStateDescription?blendState = null, SamplerState samplerState = null, DepthStencilStateDescription?depthStencilState = null, RasterizerStateDescription?rasterizerState = null, EffectInstance effect = null, int stencilValue = 0) { CheckEndHasBeenCalled("begin"); userViewMatrix = viewMatrix; userProjectionMatrix = projectionMatrix; base.Begin(graphicsContext, effect, sortMode, blendState, samplerState, depthStencilState, rasterizerState, stencilValue); }
/// <summary> /// Begins a sprite batch rendering using the specified sorting mode and blend state, sampler, depth stencil, rasterizer state objects, plus a custom effect and a 2D transformation matrix. Passing null for any of the state objects selects the default default state objects (BlendState.AlphaBlend, DepthStencilState.Default, RasterizerState.CullCounterClockwise, SamplerState.LinearClamp). Passing a null effect selects the default SpriteBatch Class shader. /// </summary> /// <param name="graphicsContext">The graphics context to use.</param> /// <param name="viewMatrix">The view matrix to use for the batch session</param> /// <param name="sortMode">The sprite drawing order to use for the batch session</param> /// <param name="blendState">The blending state to use for the batch session</param> /// <param name="samplerState">The sampling state to use for the batch session</param> /// <param name="depthStencilState">The depth stencil state to use for the batch session</param> /// <param name="rasterizerState">The rasterizer state to use for the batch session</param> /// <param name="effect">The effect to use for the batch session</param> /// <param name="stencilValue">The value of the stencil buffer to take as reference for the batch session</param> public void Begin(GraphicsContext graphicsContext, Matrix viewMatrix, SpriteSortMode sortMode = SpriteSortMode.Deferred, BlendStateDescription?blendState = null, SamplerState samplerState = null, DepthStencilStateDescription?depthStencilState = null, RasterizerStateDescription?rasterizerState = null, EffectInstance effect = null, int stencilValue = 0) { UpdateDefaultProjectionMatrix(graphicsContext.CommandList); Begin(graphicsContext, viewMatrix, defaultProjectionMatrix, sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, stencilValue); }
/// <summary> /// Begins a sprite batch operation using deferred sort and default state objects (BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.Default, RasterizerState.CullCounterClockwise). /// </summary> /// <param name="graphicsContext">The graphics context to use.</param> /// <param name="sortMode">The sprite drawing order to use for the batch session</param> /// <param name="effect">The effect to use for the batch session</param> public void Begin(GraphicsContext graphicsContext, SpriteSortMode sortMode, EffectInstance effect) { UpdateDefaultProjectionMatrix(graphicsContext.CommandList); Begin(graphicsContext, defaultViewMatrix, defaultProjectionMatrix, sortMode, null, null, null, null, effect); }
public override void Draw(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) { base.Draw(context, renderView, renderViewStage, startIndex, endIndex); var isMultisample = RenderSystem.RenderStages[renderViewStage.Index].Output.MultisampleCount != MultisampleCount.None; var batchContext = threadContext.Value; Matrix viewInverse; Matrix.Invert(ref renderView.View, out viewInverse); uint previousBatchState = uint.MaxValue; //TODO string comparison ...? var isPicking = RenderSystem.RenderStages[renderViewStage.Index].Name == "Picking"; bool hasBegin = false; for (var index = startIndex; index < endIndex; index++) { var renderNodeReference = renderViewStage.SortedRenderNodes[index].RenderNode; var renderNode = GetRenderNode(renderNodeReference); var renderSprite = (RenderSprite)renderNode.RenderObject; var sprite = renderSprite.Sprite; if (sprite == null) { continue; } // TODO: this should probably be moved to Prepare() // Project the position // TODO: This could be done in a SIMD batch, but we need to figure-out how to plugin in with RenderMesh object var worldPosition = new Vector4(renderSprite.WorldMatrix.TranslationVector, 1.0f); Vector4 projectedPosition; Vector4.Transform(ref worldPosition, ref renderView.ViewProjection, out projectedPosition); var projectedZ = projectedPosition.Z / projectedPosition.W; BlendModes blendMode; EffectInstance currentEffect = null; if (isPicking) { blendMode = BlendModes.Default; currentEffect = batchContext.GetOrCreatePickingSpriteEffect(RenderSystem.EffectSystem); } else { var spriteBlend = renderSprite.BlendMode; if (spriteBlend == SpriteBlend.Auto) { spriteBlend = sprite.IsTransparent ? SpriteBlend.AlphaBlend : SpriteBlend.None; } if (spriteBlend == SpriteBlend.AlphaBlend) { blendMode = renderSprite.PremultipliedAlpha ? BlendModes.Alpha : BlendModes.NonPremultiplied; } else { blendMode = spriteBlendToBlendMode[spriteBlend]; } } // Check if the current blend state has changed in any way, if not // Note! It doesn't really matter in what order we build the bitmask, the result is not preserved anywhere except in this method var currentBatchState = (uint)blendMode; currentBatchState = (currentBatchState << 1) + (renderSprite.IgnoreDepth ? 1U : 0U); currentBatchState = (currentBatchState << 1) + (renderSprite.IsAlphaCutoff ? 1U : 0U); currentBatchState = (currentBatchState << 2) + ((uint)renderSprite.Sampler); if (previousBatchState != currentBatchState) { var blendState = blendModeToDescription[blendMode]; if (renderSprite.IsAlphaCutoff) { currentEffect = batchContext.GetOrCreateAlphaCutoffSpriteEffect(RenderSystem.EffectSystem); } var depthStencilState = renderSprite.IgnoreDepth ? DepthStencilStates.None : DepthStencilStates.Default; var samplerState = context.GraphicsDevice.SamplerStates.LinearClamp; if (renderSprite.Sampler != SpriteSampler.LinearClamp) { switch (renderSprite.Sampler) { case SpriteSampler.PointClamp: samplerState = context.GraphicsDevice.SamplerStates.PointClamp; break; case SpriteSampler.AnisotropicClamp: samplerState = context.GraphicsDevice.SamplerStates.AnisotropicClamp; break; } } if (hasBegin) { batchContext.SpriteBatch.End(); } var rasterizerState = RasterizerStates.CullNone; if (isMultisample) { rasterizerState.MultisampleCount = RenderSystem.RenderStages[renderViewStage.Index].Output.MultisampleCount; rasterizerState.MultisampleAntiAliasLine = true; } batchContext.SpriteBatch.Begin(context.GraphicsContext, renderView.ViewProjection, SpriteSortMode.Deferred, blendState, samplerState, depthStencilState, rasterizerState, currentEffect); hasBegin = true; } previousBatchState = currentBatchState; var sourceRegion = sprite.Region; var texture = sprite.Texture; var color = renderSprite.Color; if (isPicking) // TODO move this code corresponding to picking out of the runtime code. { var compId = RuntimeIdHelper.ToRuntimeId(renderSprite.Source); color = new Color4(compId, 0.0f, 0.0f, 0.0f); } // skip the sprite if no texture is set. if (texture == null) { continue; } // determine the element world matrix depending on the type of sprite var worldMatrix = renderSprite.WorldMatrix; if (renderSprite.SpriteType == SpriteType.Billboard) { worldMatrix = viewInverse; var worldMatrixRow1 = worldMatrix.Row1; var worldMatrixRow2 = worldMatrix.Row2; // remove scale of the camera worldMatrixRow1 /= ((Vector3)viewInverse.Row1).Length(); worldMatrixRow2 /= ((Vector3)viewInverse.Row2).Length(); // set the scale of the object worldMatrixRow1 *= ((Vector3)renderSprite.WorldMatrix.Row1).Length(); worldMatrixRow2 *= ((Vector3)renderSprite.WorldMatrix.Row2).Length(); worldMatrix.Row1 = worldMatrixRow1; worldMatrix.Row2 = worldMatrixRow2; // set the position worldMatrix.TranslationVector = renderSprite.WorldMatrix.TranslationVector; // set the rotation var localRotationZ = renderSprite.RotationEulerZ; if (localRotationZ != 0) { worldMatrix = Matrix.RotationZ(localRotationZ) * worldMatrix; } } // calculate normalized position of the center of the sprite (takes into account the possible rotation of the image) var normalizedCenter = new Vector2(sprite.Center.X / sourceRegion.Width - 0.5f, 0.5f - sprite.Center.Y / sourceRegion.Height); if (sprite.Orientation == ImageOrientation.Rotated90) { var oldCenterX = normalizedCenter.X; normalizedCenter.X = -normalizedCenter.Y; normalizedCenter.Y = oldCenterX; } // apply the offset due to the center of the sprite var centerOffset = Vector2.Modulate(normalizedCenter, sprite.SizeInternal); worldMatrix.M41 -= centerOffset.X * worldMatrix.M11 + centerOffset.Y * worldMatrix.M21; worldMatrix.M42 -= centerOffset.X * worldMatrix.M12 + centerOffset.Y * worldMatrix.M22; worldMatrix.M43 -= centerOffset.X * worldMatrix.M13 + centerOffset.Y * worldMatrix.M23; // adapt the source region to match what is expected at full resolution if (texture.ViewType == ViewType.Full && texture.ViewWidth != texture.FullQualitySize.Width) { var fullQualitySize = texture.FullQualitySize; var horizontalRatio = texture.ViewWidth / (float)fullQualitySize.Width; var verticalRatio = texture.ViewHeight / (float)fullQualitySize.Height; sourceRegion.X *= horizontalRatio; sourceRegion.Width *= horizontalRatio; sourceRegion.Y *= verticalRatio; sourceRegion.Height *= verticalRatio; } // register resource usage. Context.StreamingManager?.StreamResources(texture); // draw the sprite batchContext.SpriteBatch.Draw(texture, ref worldMatrix, ref sourceRegion, ref sprite.SizeInternal, ref color, sprite.Orientation, renderSprite.Swizzle, projectedZ); } if (hasBegin) { batchContext.SpriteBatch.End(); } }
public EffectInstance GetOrCreatePickingSpriteEffect(EffectSystem effectSystem) { return(pickingEffect ?? (pickingEffect = new EffectInstance(effectSystem.LoadEffect("SpritePicking").WaitForResult()))); }
void Update() { if (isPlayer) { if (Time.time - timer > RPGManager.statInfo.updateLevelTime) { timer = Time.time; VampireSave.blood = blood; File.WriteAllText(Path.Combine(Application.streamingAssetsPath, "Mods/Amnesia RPG/Saves/vampiresave.json"), JsonConvert.SerializeObject(new VampireSave(), Formatting.Indented)); } } foreach (Item item in Item.list) { if (Vector3.Distance(item.transform.position, vampire.ragdoll.GetPart(RagdollPart.Type.Head).transform.position + (vampire.ragdoll.GetPart(RagdollPart.Type.Head).transform.up * 0.1f)) < 0.25f) { foreach (Paintable paintable in item.paintables) { if (Vector3.Distance(paintable.transform.position, vampire.ragdoll.GetPart(RagdollPart.Type.Head).transform.position + (vampire.ragdoll.GetPart(RagdollPart.Type.Head).transform.up * 0.1f)) < 0.10f) { paintable.Clear(); } } } } if (isPlayer && blood > 1 && vampire.currentHealth < vampire.maxHealth) { blood -= 0.01f * Time.deltaTime; vampire.currentHealth += 0.05f * Time.deltaTime; } blood -= 0.0025f * Time.deltaTime; foreach (Creature creature in Creature.list) { if (Vector3.Distance(vampire.ragdoll.GetPart(RagdollPart.Type.Head).transform.position, creature.ragdoll.GetPart(RagdollPart.Type.Neck).transform.position) < 0.3f && creature != vampire && !biteVictim) { biteVictim = creature; } } if (biteVictim) { if (biteEffect is null) { biteEffect = Catalog.GetData <EffectData>("Bleeding").Spawn(biteVictim.ragdoll.GetPart(RagdollPart.Type.Neck).transform.position, Quaternion.identity, biteVictim.ragdoll.GetPart(RagdollPart.Type.Neck).transform); } biteEffect.Play(); if (isPlayer) { damage = TraitsManager.vampirismLvl * Time.deltaTime; } else { damage = Random.Range(1 * Time.deltaTime, 3 * Time.deltaTime); } if (biteVictim.currentHealth > damage) { biteVictim.currentHealth -= damage; vampire.currentHealth += damage; } else { biteVictim.Kill(); if (isPlayer) { TraitsManager.vampirismExp += damage; } } if (isPlayer) { int divider; if (biteVictim.isKilled) { divider = 100; } else { divider = 50; } TraitsManager.vampirismExp += damage / divider; if (blood < 100) { blood += damage / divider; } } if (Vector3.Distance(vampire.ragdoll.GetPart(RagdollPart.Type.Head).transform.position, biteVictim.ragdoll.GetPart(RagdollPart.Type.Neck).transform.position) > 0.3f) { biteVictim = null; biteEffect.Despawn(); biteEffect = null; } } }
//AllocateHierarchy public override MeshContainer CreateMeshContainer( string name, MeshData meshData, ExtendedMaterial[] materials, EffectInstance[] effectInstances, GraphicsStream adjacency, SkinInformation skinInfo) { if(meshData.Mesh == null ) throw new OpsException("Expecting Microsoft.DirectX.Direct3D.Mesh not Microsoft.DirectX.Direct3D.ProgressiveMesh or Microsoft.DirectX.Direct3D.PatchMesh."); OpsMeshContainer mc= new OpsMeshContainer(); mc.Name= name; mc.MeshData= meshData; mc.SetMaterials(materials); mc.SetEffectInstances(effectInstances); mc.SetAdjacency(adjacency); mc.SkinInformation = skinInfo; return mc; }
public MakeControlableBuff(int id, Fighter target, Fighter caster, SpellLevelRecord level, EffectInstance effect, ushort spellId, bool critical, FightDispellableEnum dispelable) : base(id, target, caster, level, effect, spellId, critical, dispelable) { }
IEnumerator DespawnEffectDelay(EffectInstance effect, float delay) { yield return(new WaitForSeconds(delay)); effect.Despawn(); }
public override void Enter(DaggerBehaviour dagger, DaggerController controller) { base.Enter(dagger, controller); trapEffect = Catalog.GetData <EffectData>("DaggerFloatFX").Spawn(dagger.transform.position, dagger.transform.rotation); dagger.SetPhysics(0); }
public EffectInstance GetOrCreatePickingSpriteEffect(EffectSystem effectSystem) { return pickingEffect ?? (pickingEffect = new EffectInstance(effectSystem.LoadEffect("SpritePicking").WaitForResult())); }
public ActiveRunes(Fighter source, SpellLevelRecord level, EffectInstance effect, Fighter[] targets, MapPoint castPoint, bool critical) : base(source, level, effect, targets, castPoint, critical) { }
public TriggerBuff(int id, Fighter target, Fighter caster, SpellLevelRecord level, EffectInstance effect, ushort spellId, bool critical, FightDispellableEnum dispelable, TriggerType trigger, TriggerBuffApplyHandler applyTrigger, TriggerBuffRemoveHandler removeTrigger, short delay, short customActionId) : base(id, target, caster, level, effect, spellId, critical, dispelable, customActionId) { this.Trigger = trigger; this.ApplyTrigger = applyTrigger; this.RemoveTrigger = removeTrigger; this.Delay = delay; }
public override void Draw(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) { base.Draw(context, renderView, renderViewStage, startIndex, endIndex); BlendStateDescription? previousBlendState = null; DepthStencilStateDescription?previousDepthStencilState = null; EffectInstance previousEffect = null; //TODO string comparison ...? var isPicking = RenderSystem.RenderStages[renderViewStage.Index].Name == "Picking"; var hasBegin = false; for (var index = startIndex; index < endIndex; index++) { var renderNodeReference = renderViewStage.SortedRenderNodes[index].RenderNode; var renderNode = GetRenderNode(renderNodeReference); var spriteState = (RenderSpriteStudio)renderNode.RenderObject; var depthStencilState = DepthStencilStates.DepthRead; foreach (var node in spriteState.SortedNodes) { if (node.Sprite?.Texture == null || node.Sprite.Region.Width <= 0 || node.Sprite.Region.Height <= 0f || node.Hide != 0) { continue; } // Update the sprite batch BlendStateDescription spriteBlending; switch (node.BaseNode.AlphaBlending) { case SpriteStudioBlending.Mix: spriteBlending = BlendStates.AlphaBlend; break; case SpriteStudioBlending.Multiplication: spriteBlending = MultBlendState; break; case SpriteStudioBlending.Addition: spriteBlending = BlendStates.Additive; break; case SpriteStudioBlending.Subtraction: spriteBlending = SubBlendState; break; default: throw new ArgumentOutOfRangeException(); } // TODO: this should probably be moved to Prepare() // Project the position // TODO: This could be done in a SIMD batch, but we need to figure-out how to plugin in with RenderMesh object var worldPosition = new Vector4(spriteState.WorldMatrix.TranslationVector, 1.0f); Vector4 projectedPosition; Vector4.Transform(ref worldPosition, ref renderView.ViewProjection, out projectedPosition); var projectedZ = projectedPosition.Z / projectedPosition.W; var blendState = isPicking ? BlendStates.Default : spriteBlending; // TODO: the current impementation to determine if the sprite is selected does not work. This should be fixed later at some point //var currentEffect = isPicking ? GetOrCreatePickingSpriteEffect() : ShadowObject.IsObjectSelected(spriteState.SpriteStudioComponent) ? GetOrCreateSelectedSpriteEffect() : null; var currentEffect = isPicking ? GetOrCreatePickingSpriteEffect() : null; // TODO remove this code when material are available if (previousEffect != currentEffect || blendState != previousBlendState || depthStencilState != previousDepthStencilState) { if (hasBegin) { sprite3DBatch.End(); } sprite3DBatch.Begin(context.GraphicsContext, renderView.ViewProjection, SpriteSortMode.Deferred, blendState, null, depthStencilState, RasterizerStates.CullNone, currentEffect); hasBegin = true; } previousEffect = currentEffect; previousBlendState = blendState; previousDepthStencilState = depthStencilState; var sourceRegion = node.Sprite.Region; var texture = node.Sprite.Texture; // skip the sprite if no texture is set. if (texture == null) { continue; } var color4 = Color4.White; if (isPicking) { // TODO move this code corresponding to picking out of the runtime code. color4 = new Color4(RuntimeIdHelper.ToRuntimeId(spriteState.Source)); } else { if (node.BlendFactor > 0.0f) { switch (node.BlendType) //todo this should be done in a shader { case SpriteStudioBlending.Mix: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; case SpriteStudioBlending.Multiplication: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; case SpriteStudioBlending.Addition: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; case SpriteStudioBlending.Subtraction: color4 = Color4.Lerp(color4, node.BlendColor, node.BlendFactor) * node.FinalTransparency; break; default: throw new ArgumentOutOfRangeException(); } } else { color4 *= node.FinalTransparency; } } Matrix.Multiply(ref node.ModelTransform, ref spriteState.WorldMatrix, out var worldMatrix); // calculate normalized position of the center of the sprite (takes into account the possible rotation of the image) var normalizedCenter = new Vector2(node.Sprite.Center.X / sourceRegion.Width - 0.5f, 0.5f - node.Sprite.Center.Y / sourceRegion.Height); if (node.Sprite.Orientation == ImageOrientation.Rotated90) { var oldCenterX = normalizedCenter.X; normalizedCenter.X = -normalizedCenter.Y; normalizedCenter.Y = oldCenterX; } // apply the offset due to the center of the sprite var size = node.Sprite.Size; var centerOffset = Vector2.Modulate(normalizedCenter, size); worldMatrix.M41 -= centerOffset.X * worldMatrix.M11 + centerOffset.Y * worldMatrix.M21; worldMatrix.M42 -= centerOffset.X * worldMatrix.M12 + centerOffset.Y * worldMatrix.M22; // draw the sprite sprite3DBatch.Draw(texture, ref worldMatrix, ref sourceRegion, ref size, ref color4, node.Sprite.Orientation, SwizzleMode.None, projectedZ); } } if (hasBegin) { sprite3DBatch.End(); } }
public Jet EvaluateJet(Fighter source, EffectElementType elementType, EffectInstance effect, ushort spellId) { return(this.EvaluateJet(source, elementType, (short)effect.DiceMin, (short)effect.DiceMax, source.GetSpellBoost(spellId), spellId == WeaponManager.PunchSpellId)); }
/// <summary> /// Constructor, called by HierarchyAllocator /// </summary> /// <param name="subfolder">textures are found in ../Cells/subfolder, where subfolder is the cell group name</param> /// <param name="name">mesh name (read from the X file)</param> /// <param name="mesh">the source mesh (as a standard mesh)</param> /// <param name="extmaterials">Materials and texture filenames</param> /// <param name="effectInstances">Effects</param> /// <param name="adjacency">Mesh adjacency data</param> /// <param name="skinInfo">Skin information for the mesh</param> public Cytoplasm( string subfolder, string name, Mesh mesh, ExtendedMaterial[] extmaterials, EffectInstance[] effectInstances, GraphicsStream adjacency, SkinInformation skinInfo) { // Store the name Name = name; // Keep the original mesh because this is needed for MousePick() // (ProgressiveMeshes don't have a .Intersect() method) originalMesh = mesh; // Store the materials int matlength = 0; if (extmaterials != null) matlength = extmaterials.Length; materials = new Material[matlength]; textures = new Texture[matlength]; bumps = new Texture[matlength]; for (int i = 0; i < matlength; i++) { materials[i] = extmaterials[i].Material3D; // TRUESPACE HACK: Truespace doesn't allow me to set any ambient values in materials, // which means that everything comes out black if it isn't lit by the diffuse light. // So add a default ambient value here for any black cells, to simulate reflection from terrain if ((materials[i].Ambient.R + materials[i].Ambient.G + materials[i].Ambient.B) == 0) materials[i].Ambient = Color.FromArgb(68, 68, 68); if ((extmaterials[i].TextureFilename != null) && (extmaterials[i].TextureFilename != string.Empty)) { try { // We have a texture file, rather than an inline texture, so try to load it from ./cells/group/type textures[i] = TextureLoader.FromFile(Engine.Device, FileResource.Fsp(subfolder, extmaterials[i].TextureFilename)); // Also attempt to load a normal map, if any try { string filename = System.IO.Path.GetFileNameWithoutExtension(extmaterials[i].TextureFilename) + " Normal.PNG"; bumps[i] = TextureLoader.FromFile(Engine.Device, FileResource.Fsp(subfolder, filename)); } catch { } } catch { throw new SDKException("Failed to load texture " + FileResource.Fsp(subfolder, extmaterials[i].TextureFilename)); } } } // Get access to the vertices to allow various operations // get the input vertices as an array (in case I want to modify them) VertexBuffer vb = mesh.VertexBuffer; // Retrieve the vertex buffer data System.Array vert = null; // We don't know if array will be PositionNormal or PositionNormalTextured, so use generic type if (mesh.VertexFormat == VertexFormats.PositionNormal) { vert = vb.Lock(0, typeof(CustomVertex.PositionNormal), LockFlags.ReadOnly, mesh.NumberVertices); } else { vert = vb.Lock(0, typeof(CustomVertex.PositionNormalTextured), LockFlags.ReadOnly, mesh.NumberVertices); } // compute the bounding sphere radius & centre from the vertices // NOTE: THIS VALUE IS FOR THE UNSCALED VERTICES and needs to be transformed by the combined transformation matrix boundRadius = Geometry.ComputeBoundingSphere(vert, mesh.VertexFormat, out boundCentre); // Calculate a bounding box for fine collision detection // NOTE: THIS VALUE IS FOR THE UNSCALED VERTICES and needs to be transformed by the combined transformation matrix Geometry.ComputeBoundingBox(vert, mesh.VertexFormat, out minOBB, out maxOBB); // gather useful debug info while we have the vertices // Debug.WriteLine(String.Format(" Loaded mesh [{0}] from disk. {1} vertices, {2} textures, {3} materials", // name,md.Mesh.NumberVertices,textures.Length, materials.Length)); // Debug.WriteLine(String.Format("Mesh is centred on {0} with bound radius {1}; OBB is {2}:{3}", // boundcentre, boundradius, OBBmin, OBBmax)); vb.Unlock(); vb.Dispose(); // vertices no longer needed // create a cleaned progressive mesh from the input using (Mesh clean = Mesh.Clean(CleanType.Optimization, mesh, adjacency, adjacency)) { // From the cleaned mesh, create one that has binormals and tangents as well as normals // (ThreeDee.BinormalVertex). These are needed for normal mapping in the shader using (Mesh clone = clean.Clone(MeshFlags.Managed, BinormalVertex.VertexElements, Engine.Device)) { // Add tangents and binormals clone.ComputeTangent(0, 0, 0, 0); //clone.ComputeTangentFrame(0); // Create a new progressive mesh from the clean version MeshData md = new MeshData(); md.ProgressiveMesh = new ProgressiveMesh(clone, adjacency, null, 12, // min acceptable # faces MeshFlags.SimplifyFace); this.MeshData = md; } } // Add a device reset handler to reload resources (if required) /////Engine.Device.DeviceReset += new System.EventHandler(OnReset); }
public EffectHandle(EffectInstance fxInstance) { this.hasValue = fxInstance != null; this.id = fxInstance == null ? 0 : fxInstance.id; this.effect = fxInstance == null ? null : fxInstance.effect; }
public StateBuff(int id, Fighter target, Fighter caster, SpellLevelRecord level, EffectInstance effect, ushort spellId, bool critical, FightDispellableEnum dispelable, SpellStateRecord stateRecord) : base(id, target, caster, level, effect, spellId, critical, dispelable) { this.StateRecord = stateRecord; }
public EffectObjectOutline() { this.device = Rendering.GraphicsDevice; this.effect = EffectInstance.Create(new EffectResource("Special/ObjectOutline")); }
private EffectInstance GetOrCreatePickingSpriteEffect() { return pickingSpriteEffect ?? (pickingSpriteEffect = new EffectInstance(RenderSystem.EffectSystem.LoadEffect("SpritePicking").WaitForResult())); }
public void Handler(EffectInstance effect, MapPoint castPoint, Fighter[] targets) { SpellEffectsManager.Instance.HandleEffect(Source, Level, castPoint, CriticalHit, effect, targets); }
public AuraGlyph(short id, Fighter source, SpellLevelRecord spellLevel, EffectInstance effect, MapPoint centerPoint, Zone zone, Color color, MarkTriggerTypeEnum triggerType) : base(id, source, spellLevel, effect, centerPoint, zone, color, triggerType) { this.Duration = (short)effect.Duration; }
public TriggerBuff AddTriggerBuff(Fighter target, FightDispellableEnum dispelable, TriggerType trigger, SpellLevelRecord level, EffectInstance effect, ushort spellId, short delay, TriggerBuff.TriggerBuffApplyHandler applyTrigger, short duration) { int id = target.BuffIdProvider.Pop(); TriggerBuff triggerBuff = new TriggerBuff(id, target, this.Source, level, effect, spellId, CriticalHit, dispelable, trigger, applyTrigger, delay); triggerBuff.Duration = duration; target.AddAndApplyBuff(triggerBuff, true); return(triggerBuff); }
public Friction(Fighter source, SpellLevelRecord spellLevel, EffectInstance effect, Fighter[] targets, MapPoint castPoint, bool critical) : base(source, spellLevel, effect, targets, castPoint, critical) { this.CellsStep = (short)Effect.DiceMax; }
protected override async Task LoadContent() { await base.LoadContent(); pipelineState = new MutablePipelineState(GraphicsDevice); var vertices = new Vertex[4]; vertices[0] = new Vertex { Position = new Vector3(-1, -1, 0.5f), TexCoords = new Vector2(0, 0) }; vertices[1] = new Vertex { Position = new Vector3(-1, 1, 0.5f), TexCoords = new Vector2(3, 0) }; vertices[2] = new Vertex { Position = new Vector3(1, 1, 0.5f), TexCoords = new Vector2(3, 3) }; vertices[3] = new Vertex { Position = new Vector3(1, -1, 0.5f), TexCoords = new Vector2(0, 3) }; var indices = new short[] { 0, 1, 2, 0, 2, 3 }; var vertexBuffer = Buffer.Vertex.New(GraphicsDevice, vertices, GraphicsResourceUsage.Default); var indexBuffer = Buffer.Index.New(GraphicsDevice, indices, GraphicsResourceUsage.Default); var meshDraw = new MeshDraw { DrawCount = 4, PrimitiveType = PrimitiveType.TriangleList, VertexBuffers = new[] { new VertexBufferBinding(vertexBuffer, new VertexDeclaration(VertexElement.Position <Vector3>(), VertexElement.TextureCoordinate <Vector2>()), 4) }, IndexBuffer = new IndexBufferBinding(indexBuffer, false, indices.Length), }; mesh = new Mesh { Draw = meshDraw, }; simpleEffect = new EffectInstance(new Effect(GraphicsDevice, SpriteEffect.Bytecode)); simpleEffect.Parameters.Set(TexturingKeys.Texture0, UVTexture); simpleEffect.UpdateEffect(GraphicsDevice); // TODO GRAPHICS REFACTOR //vao = VertexArrayObject.New(GraphicsDevice, mesh.Draw.IndexBuffer, mesh.Draw.VertexBuffers); myDraws = new DrawOptions[3]; myDraws[0] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearClamp, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(-0.5f, 0.5f, 0f)) }; myDraws[1] = new DrawOptions { Sampler = GraphicsDevice.SamplerStates.LinearWrap, Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, 0.5f, 0f)) }; myDraws[2] = new DrawOptions { Sampler = SamplerState.New(GraphicsDevice, new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Mirror)), Transform = Matrix.Multiply(Matrix.Scaling(0.4f), Matrix.Translation(0.5f, -0.5f, 0f)) }; //var borderDescription = new SamplerStateDescription(TextureFilter.Linear, TextureAddressMode.Border) { BorderColor = Color.Purple }; //var border = SamplerState.New(GraphicsDevice, borderDescription); //myDraws[3] = new DrawOptions { Sampler = border, Transform = Matrix.Multiply(Matrix.Scale(0.3f), Matrix.Translation(-0.5f, -0.5f, 0f)) }; }
IEnumerator SlowCoroutine(Creature targetCreature, float energy, float maxSlow, float minSlow, float duration) { EffectData imbueHitRagdollEffectData = Catalog.GetData <EffectData>("ImbueIceRagdoll", true); effectInstance = imbueHitRagdollEffectData.Spawn(targetCreature.ragdoll.rootPart.transform, true, Array.Empty <Type>()); effectInstance.SetRenderer(targetCreature.GetRendererForVFX(), false); effectInstance.Play(0); effectInstance.SetIntensity(1f); float animSpeed = Mathf.Lerp(minSlow, maxSlow, energy / 100); if (animSpeed != 0) { targetCreature.animator.speed *= (animSpeed / 100); targetCreature.locomotion.speed *= (animSpeed / 100); } else { targetCreature.ragdoll.SetState(Ragdoll.State.Frozen); targetCreature.ragdoll.AddNoStandUpModifier(this); targetCreature.brain.Stop(); } /* * targetCreature.animator.speed *= (animSpeed / 100); * targetCreature.locomotion.speed *= (animSpeed / 100); */ yield return(new WaitForSeconds(duration)); /* * targetCreature.animator.speed = 1; * targetCreature.locomotion.speed = targetCreature.data.locomotionSpeed; * * * * if (!targetCreature.brain.instance.isActive) * { * targetCreature.brain.instance.Start(); * }*/ if (animSpeed != 0) { targetCreature.animator.speed = 1; targetCreature.locomotion.speed = targetCreature.data.locomotionSpeed; } else { if (!targetCreature.isKilled) { targetCreature.ragdoll.SetState(Ragdoll.State.Destabilized); targetCreature.ragdoll.RemoveNoStandUpModifier(this); targetCreature.brain.Load(targetCreature.brain.instance.id); } } effectInstance.Despawn(); /* * targetCreature.umaCharacter.umaDCS.SetColor("Skin", defaultSkinColor, default(Color), 0, true); */ }
public TakenDamageMultiply(Fighter source, SpellLevelRecord spellLevel, EffectInstance effect, Fighter[] targets, MapPoint castPoint, bool critical) : base(source, spellLevel, effect, targets, castPoint, critical) { this.Ratio = ((double)Effect.DiceMin / (double)100); }