public override void Flush(GraphicsDevice Device, Shader Effect, Camera Camera, InstanceRenderMode Mode) { if (InstanceCount == 0) { return; } if (NeedsRendered || (AtlasTexture != null && (AtlasTexture.IsDisposed || AtlasTexture.GraphicsDevice.IsDisposed))) { if (AtlasEntries == null) { RebuildAtlas(); } AtlasTexture = new Texture2D(Device, AtlasBounds.Width, AtlasBounds.Height); foreach (var texture in AtlasEntries) { var realTexture = texture.SourceTexture; if (realTexture == null || realTexture.IsDisposed || realTexture.GraphicsDevice.IsDisposed) { texture.SourceTexture = AssetManager.GetContentTexture(texture.SourceDefinition.Texture); realTexture = texture.SourceTexture; } var textureData = new Color[realTexture.Width * realTexture.Height]; realTexture.GetData(textureData); // Paste texture data into atlas. AtlasTexture.SetData(0, texture.AtlasBounds, textureData, 0, realTexture.Width * realTexture.Height); } NeedsRendered = false; } if (InstanceBuffer == null || InstanceBuffer.IsDisposed || InstanceBuffer.IsContentLost) { InstanceBuffer = new DynamicVertexBuffer(Device, TiledInstancedVertex.VertexDeclaration, InstanceQueueSize, BufferUsage.None); } Device.RasterizerState = new RasterizerState { CullMode = CullMode.None }; if (Mode == InstanceRenderMode.Normal) { Effect.SetTiledInstancedTechnique(); } else { Effect.CurrentTechnique = Effect.Techniques[Shader.Technique.SelectionBufferTiledInstanced]; } Effect.EnableWind = RenderData.EnableWind; Effect.EnableLighting = true; Effect.VertexColorTint = Color.White; if (RenderData.Model.VertexBuffer == null || RenderData.Model.IndexBuffer == null || (RenderData.Model.VertexBuffer != null && RenderData.Model.VertexBuffer.IsContentLost) || (RenderData.Model.IndexBuffer != null && RenderData.Model.IndexBuffer.IsContentLost)) { RenderData.Model.ResetBuffer(Device); } Device.Indices = RenderData.Model.IndexBuffer; BlendState blendState = Device.BlendState; Device.BlendState = Mode == InstanceRenderMode.Normal ? BlendState.NonPremultiplied : BlendState.Opaque; Effect.MainTexture = AtlasTexture; Effect.LightRamp = Color.White; InstanceBuffer.SetData(Instances, 0, InstanceCount, SetDataOptions.Discard); Device.SetVertexBuffers(new VertexBufferBinding(RenderData.Model.VertexBuffer), new VertexBufferBinding(InstanceBuffer, 0, 1)); var ghostEnabled = Effect.GhostClippingEnabled; Effect.GhostClippingEnabled = RenderData.EnableGhostClipping && ghostEnabled; foreach (EffectPass pass in Effect.CurrentTechnique.Passes) { pass.Apply(); Device.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0, RenderData.Model.VertexCount, 0, RenderData.Model.Indexes.Length / 3, InstanceCount); } Effect.GhostClippingEnabled = ghostEnabled; Effect.SetTexturedTechnique(); Effect.World = Matrix.Identity; Device.BlendState = blendState; Effect.EnableWind = false; InstanceCount = 0; }
private void GenerateData(GraphicsDevice device, float sizeX, float sizeY, float resolution) { int numCellsX = (int)(sizeX / resolution); int numCellsY = (int)(sizeY / resolution); int numVerts = (numCellsX + 1) * (numCellsY + 1); int numIndices = numCellsX * numCellsY * 6; float aspectRatio = sizeX / sizeY; const int height = 36; int width = (int)(aspectRatio * height); BannerData data = new BannerData() { Mesh = new VertexBuffer(device, ExtendedVertex.VertexDeclaration, numVerts, BufferUsage.None), Indices = new IndexBuffer(device, typeof(short), numIndices, BufferUsage.None), Texture = new RenderTarget2D(device, width, height), Verts = new ExtendedVertex[numVerts], SizeX = sizeX, SizeY = sizeY, Idx = new ushort[numIndices] }; banners[Logo] = data; for (int i = 0, y = 0; y <= numCellsY; y++) { for (int x = 0; x <= numCellsX; x++, i++) { data.Verts[i] = new ExtendedVertex(new Vector3(0, y * resolution - sizeY * 0.5f, 0), Color.White, Color.White, new Vector2((float)x / (float)numCellsX, 1.0f - (float)y / (float)numCellsY), new Vector4(0, 0, 1, 1)); } } for (ushort ti = 0, vi = 0, y = 0; y < numCellsY; y++, vi++) { for (int x = 0; x < numCellsX; x++, ti += 6, vi++) { data.Idx[ti] = vi; data.Idx[ti + 3] = data.Idx[ti + 2] = (ushort)(vi + 1); data.Idx[ti + 4] = data.Idx[ti + 1] = (ushort)(vi + numCellsX + 1); data.Idx[ti + 5] = (ushort)(vi + numCellsX + 2); } } var oldView = device.Viewport; data.Mesh.SetData(data.Verts); data.Indices.SetData(data.Idx); device.SetRenderTarget(data.Texture); //device.Viewport = new Viewport(0, 0, width, height); // Must set viewport after target bound. device.Clear(new Color(Logo.LogoBackgroundColor * 0.5f + Logo.LogoSymbolColor * 0.5f)); Texture2D logoBg = AssetManager.GetContentTexture("newgui/logo-bg"); Texture2D logoFg = AssetManager.GetContentTexture("newgui/logo-fg"); int bgIdx = Logo.LogoBackground.Tile; int bgX = (bgIdx % (logoBg.Width / 32)) * 32; int bgY = (bgIdx / (logoBg.Width / 32)) * 32; int fgIdx = Logo.LogoSymbol.Tile; int fgX = (fgIdx % (logoFg.Width / 32)) * 32; int fgY = (fgIdx / (logoFg.Width / 32)) * 32; DwarfGame.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin, DepthStencilState.None, RasterizerState.CullNone); Drawer2D.DrawRect(DwarfGame.SpriteBatch, new Rectangle(1, 1, width - 1, height - 2), Color.Black, 2); DwarfGame.SpriteBatch.Draw(logoBg, new Rectangle(width / 2 - 16, height / 2 - 16, 32, 32), new Rectangle(bgX, bgY, 32, 32), new Color(Logo.LogoBackgroundColor)); DwarfGame.SpriteBatch.Draw(logoFg, new Rectangle(width / 2 - 16, height / 2 - 16, 32, 32), new Rectangle(fgX, fgY, 32, 32), new Color(Logo.LogoSymbolColor)); DwarfGame.SpriteBatch.End(); device.SetRenderTarget(null); device.Indices = null; device.SetVertexBuffer(null); //device.Viewport = oldView; }
public void Render( GraphicsDevice graphics, Shader effect, Camera cam, string mode) { effect.EnableWind = EnableWind; Camera = cam; if (HardwareInstancingSupported && (instanceBuffer == null || instanceBuffer.IsContentLost || instanceBuffer.IsDisposed)) { instanceBuffer = new DynamicVertexBuffer(graphics, InstancedVertex.VertexDeclaration, numInstances, BufferUsage.None); } if (SortedData.Data.Count > 0 && numActiveInstances > 0) { graphics.RasterizerState = rasterState; effect.CurrentTechnique = effect.Techniques[mode]; effect.EnableLighting = true; effect.VertexColorTint = Color.White; if (Texture == null || Texture.GraphicsDevice.IsDisposed) { Texture = AssetManager.GetContentTexture(TextureAsset); } if (Model.VertexBuffer == null || Model.IndexBuffer == null || Model.VertexBuffer.IsDisposed || Model.VertexBuffer.IsContentLost) { Model.ResetBuffer(graphics); Model.Texture = new NamedImageFrame(TextureAsset); } bool hasIndex = Model.IndexBuffer != null; graphics.Indices = Model.IndexBuffer; BlendState blendState = graphics.BlendState; graphics.BlendState = BlendMode; effect.MainTexture = Texture; effect.LightRamp = Color.White; if (HardwareInstancingSupported) { instanceBuffer.SetData(instanceVertexes, 0, SortedData.Data.Count, SetDataOptions.Discard); graphics.SetVertexBuffers(new VertexBufferBinding(Model.VertexBuffer), new VertexBufferBinding(instanceBuffer, 0, 1)); try { DrawInstanced(graphics, effect, cam); } catch (NoSuitableGraphicsDeviceException exception) { global::System.Console.WriteLine(exception.ToString()); HardwareInstancingSupported = false; } } else { // Fallback case when hardware instancing is not supported effect.SetTexturedTechnique(); DrawNonInstanced(graphics, effect, cam); } effect.SetTexturedTechnique(); effect.World = Matrix.Identity; graphics.BlendState = blendState; } effect.EnableWind = false; }
public static Texture2D RenderIcons(GraphicsDevice device, Microsoft.Xna.Framework.Content.ContentManager Content, Gui.JsonTileSheet Sheet) { InitializeDefaultLibrary(device); var shader = new Shader(Content.Load <Effect>(ContentPaths.Shaders.TexturedShaders), true); var sqrt = (int)(Math.Ceiling(Math.Sqrt(PrimitiveMap.Count))); var width = MathFunctions.NearestPowerOf2(sqrt * Sheet.TileWidth); var height = MathFunctions.NearestPowerOf2(sqrt * Sheet.TileWidth); RenderTarget2D toReturn = new RenderTarget2D(device, width, height, false, SurfaceFormat.Color, DepthFormat.Depth16, 0, RenderTargetUsage.PreserveContents); device.SetRenderTarget(toReturn); device.Clear(Color.Transparent); shader.SetIconTechnique(); shader.MainTexture = AssetManager.GetContentTexture(ContentPaths.Terrain.terrain_tiles); shader.SelfIlluminationEnabled = true; shader.SelfIlluminationTexture = AssetManager.GetContentTexture(ContentPaths.Terrain.terrain_illumination); shader.EnableShadows = false; shader.EnableLighting = false; shader.ClippingEnabled = false; shader.CameraPosition = new Vector3(-0.5f, 0.5f, 0.5f); shader.VertexColorTint = Color.White; shader.LightRamp = Color.White; shader.SunlightGradient = AssetManager.GetContentTexture(ContentPaths.Gradients.sungradient); shader.AmbientOcclusionGradient = AssetManager.GetContentTexture(ContentPaths.Gradients.ambientgradient); shader.TorchlightGradient = AssetManager.GetContentTexture(ContentPaths.Gradients.torchgradient); Viewport oldview = device.Viewport; int rows = height / Sheet.TileWidth; int cols = width / Sheet.TileWidth; device.ScissorRectangle = new Rectangle(0, 0, Sheet.TileWidth, Sheet.TileWidth); device.RasterizerState = RasterizerState.CullNone; device.DepthStencilState = DepthStencilState.Default; Vector3 half = Vector3.One * 0.5f; half = new Vector3(half.X, half.Y, half.Z); List <VoxelType> voxelsByType = Types.Select(type => type.Value).ToList(); voxelsByType.Sort((a, b) => a.ID < b.ID ? -1 : 1); foreach (EffectPass pass in shader.CurrentTechnique.Passes) { foreach (var type in voxelsByType) { int row = type.ID / cols; int col = type.ID % cols; BoxPrimitive primitive = GetPrimitive(type); if (primitive == null) { continue; } if (type.HasTransitionTextures) { primitive = new BoxPrimitive(device, 1, 1, 1, type.TransitionTextures[new BoxTransition()]); } device.Viewport = new Viewport(col * Sheet.TileWidth, row * Sheet.TileWidth, Sheet.TileWidth, Sheet.TileWidth); Matrix viewMatrix = Matrix.CreateLookAt(new Vector3(-1.2f, 1.0f, -1.5f), Vector3.Zero, Vector3.Up); Matrix projectionMatrix = Matrix.CreateOrthographic(1.5f, 1.5f, 0, 5); shader.View = viewMatrix; shader.Projection = projectionMatrix; shader.World = Matrix.CreateTranslation(-half); shader.VertexColorTint = type.Tint; pass.Apply(); primitive.Render(device); } } device.Viewport = oldview; device.SetRenderTarget(null); return((Texture2D)toReturn); }
private void LoadThreaded() { // Ensure we're using the invariant culture. Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; LoadStatus = LoadingStatus.Loading; SetLoadingMessage("Initializing ..."); while (GraphicsDevice == null) { Thread.Sleep(100); } Thread.Sleep(1000); #if !DEBUG try { #endif bool fileExists = !string.IsNullOrEmpty(ExistingFile); SetLoadingMessage("Creating Sky..."); Sky = new SkyRenderer(); #region Reading game file if (fileExists) { SetLoadingMessage("Loading " + ExistingFile); gameFile = SaveGame.CreateFromDirectory(ExistingFile); if (gameFile == null) { throw new InvalidOperationException("Game File does not exist."); } // Todo: REMOVE THIS WHEN THE NEW SAVE SYSTEM IS COMPLETE. if (gameFile.Metadata.Version != Program.Version && !Program.CompatibleVersions.Contains(gameFile.Metadata.Version)) { throw new InvalidOperationException(String.Format("Game file is from version {0}. Compatible versions are {1}.", gameFile.Metadata.Version, TextGenerator.GetListString(Program.CompatibleVersions))); } Sky.TimeOfDay = gameFile.Metadata.TimeOfDay; Time = gameFile.Metadata.Time; WorldOrigin = gameFile.Metadata.WorldOrigin; WorldScale = gameFile.Metadata.WorldScale; WorldSize = gameFile.Metadata.NumChunks; GameID = gameFile.Metadata.GameID; if (gameFile.Metadata.OverworldFile != null && gameFile.Metadata.OverworldFile != "flat") { SetLoadingMessage("Loading world " + gameFile.Metadata.OverworldFile); Overworld.Name = gameFile.Metadata.OverworldFile; DirectoryInfo worldDirectory = Directory.CreateDirectory(DwarfGame.GetWorldDirectory() + Path.DirectorySeparatorChar + Overworld.Name); var overWorldFile = new NewOverworldFile(worldDirectory.FullName); Overworld.Map = overWorldFile.Data.Data; Overworld.Name = overWorldFile.Data.Name; } else { SetLoadingMessage("Generating flat world.."); Overworld.CreateUniformLand(GraphicsDevice); } } #endregion #region Initialize static data { Vector3 origin = new Vector3(0, 0, 0); Vector3 extents = new Vector3(1500, 1500, 1500); OctTree = new OctTreeNode(origin - extents, origin + extents); PrimitiveLibrary.Initialize(GraphicsDevice, Content); InstanceRenderer = new InstanceRenderer(GraphicsDevice, Content); Color[] white = new Color[1]; white[0] = Color.White; pixel = new Texture2D(GraphicsDevice, 1, 1); pixel.SetData(white); Tilesheet = AssetManager.GetContentTexture(ContentPaths.Terrain.terrain_tiles); AspectRatio = GraphicsDevice.Viewport.AspectRatio; DefaultShader = new Shader(Content.Load <Effect>(ContentPaths.Shaders.TexturedShaders), true); DefaultShader.ScreenWidth = GraphicsDevice.Viewport.Width; DefaultShader.ScreenHeight = GraphicsDevice.Viewport.Height; CraftLibrary.InitializeDefaultLibrary(); PotionLibrary.Initialize(); VoxelLibrary.InitializeDefaultLibrary(GraphicsDevice); GrassLibrary.InitializeDefaultLibrary(); DecalLibrary.InitializeDefaultLibrary(); bloom = new BloomComponent(Game) { Settings = BloomSettings.PresetSettings[5] }; bloom.Initialize(); SoundManager.Content = Content; if (PlanService != null) { PlanService.Restart(); } JobLibrary.Initialize(); MonsterSpawner = new MonsterSpawner(this); EntityFactory.Initialize(this); } #endregion SetLoadingMessage("Creating Planner ..."); PlanService = new PlanService(); SetLoadingMessage("Creating Shadows..."); Shadows = new ShadowRenderer(GraphicsDevice, 1024, 1024); SetLoadingMessage("Creating Liquids ..."); #region liquids WaterRenderer = new WaterRenderer(GraphicsDevice); #endregion SetLoadingMessage("Generating Initial Terrain Chunks ..."); if (!fileExists) { GameID = MathFunctions.Random.Next(0, 1024); } ChunkGenerator = new ChunkGenerator(VoxelLibrary, Seed, 0.02f) { SeaLevel = SeaLevel }; #region Load Components if (fileExists) { ChunkManager = new ChunkManager(Content, this, ChunkGenerator, WorldSize.X, WorldSize.Y, WorldSize.Z); Splasher = new Splasher(ChunkManager); ChunkRenderer = new ChunkRenderer(ChunkManager.ChunkData); SetLoadingMessage("Loading Terrain..."); gameFile.ReadChunks(ExistingFile); ChunkManager.ChunkData.LoadFromFile(ChunkManager, gameFile, SetLoadingMessage); SetLoadingMessage("Loading Entities..."); gameFile.LoadPlayData(ExistingFile, this); Camera = gameFile.PlayData.Camera; DesignationDrawer = gameFile.PlayData.Designations; Vector3 origin = new Vector3(WorldOrigin.X, 0, WorldOrigin.Y); Vector3 extents = new Vector3(1500, 1500, 1500); if (gameFile.PlayData.Resources != null) { foreach (var resource in gameFile.PlayData.Resources) { if (!ResourceLibrary.Resources.ContainsKey(resource.Key)) { ResourceLibrary.Add(resource.Value); } } } ComponentManager = new ComponentManager(gameFile.PlayData.Components, this); foreach (var component in gameFile.PlayData.Components.SaveableComponents) { if (!ComponentManager.HasComponent(component.GlobalID) && ComponentManager.HasComponent(component.Parent.GlobalID)) { // Logically impossible. throw new InvalidOperationException("Component exists in save data but not in manager."); } } ConversationMemory = gameFile.PlayData.ConversationMemory; Factions = gameFile.PlayData.Factions; ComponentManager.World = this; Sky.TimeOfDay = gameFile.Metadata.TimeOfDay; Time = gameFile.Metadata.Time; WorldOrigin = gameFile.Metadata.WorldOrigin; WorldScale = gameFile.Metadata.WorldScale; // Restore native factions from deserialized data. Natives = new List <Faction>(); foreach (Faction faction in Factions.Factions.Values) { if (faction.Race.IsNative && faction.Race.IsIntelligent && !faction.IsRaceFaction) { Natives.Add(faction); } } Diplomacy = gameFile.PlayData.Diplomacy; GoalManager = new Goals.GoalManager(); GoalManager.Initialize(new List <Goals.Goal>());// gameFile.PlayData.Goals); TutorialManager = new Tutorial.TutorialManager(); TutorialManager.SetFromSaveData(gameFile.PlayData.TutorialSaveData); } else { Time = new WorldTime(); Camera = new OrbitCamera(this, new Vector3(VoxelConstants.ChunkSizeX, VoxelConstants.ChunkSizeY - 1.0f, VoxelConstants.ChunkSizeZ), new Vector3(VoxelConstants.ChunkSizeY, VoxelConstants.ChunkSizeY - 1.0f, VoxelConstants.ChunkSizeZ) + Vector3.Up * 10.0f + Vector3.Backward * 10, MathHelper.PiOver4, AspectRatio, 0.1f, GameSettings.Default.VertexCullDistance); ChunkManager = new ChunkManager(Content, this, ChunkGenerator, WorldSize.X, WorldSize.Y, WorldSize.Z); Splasher = new Splasher(ChunkManager); ChunkRenderer = new ChunkRenderer(ChunkManager.ChunkData); Camera.Position = new Vector3(0, 10, 0) + new Vector3(WorldSize.X * VoxelConstants.ChunkSizeX, 0, WorldSize.Z * VoxelConstants.ChunkSizeZ) * 0.5f; Camera.Target = new Vector3(0, 10, 1) + new Vector3(WorldSize.X * VoxelConstants.ChunkSizeX, 0, WorldSize.Z * VoxelConstants.ChunkSizeZ) * 0.5f; // If there's no file, we have to initialize the first chunk coordinate if (gameFile == null) { ChunkManager.GenerateInitialChunks(SpawnRect, new GlobalChunkCoordinate(0, 0, 0), SetLoadingMessage); } ComponentManager = new ComponentManager(this); ComponentManager.SetRootComponent(new Body(ComponentManager, "root", Matrix.Identity, Vector3.Zero, Vector3.Zero)); if (Natives == null) // Todo: Always true?? { FactionLibrary library = new FactionLibrary(); library.Initialize(this, CompanyMakerState.CompanyInformation); Natives = new List <Faction>(); for (int i = 0; i < 10; i++) { Natives.Add(library.GenerateFaction(this, i, 10)); } } #region Prepare Factions foreach (Faction faction in Natives) { faction.World = this; if (faction.RoomBuilder == null) { faction.RoomBuilder = new RoomBuilder(faction, this); } } Factions = new FactionLibrary(); if (Natives != null && Natives.Count > 0) { Factions.AddFactions(this, Natives); } Factions.Initialize(this, CompanyMakerState.CompanyInformation); Point playerOrigin = new Point((int)(WorldOrigin.X), (int)(WorldOrigin.Y)); Factions.Factions["Player"].Center = playerOrigin; Factions.Factions["The Motherland"].Center = new Point(playerOrigin.X + 50, playerOrigin.Y + 50); #endregion Diplomacy = new Diplomacy(this); Diplomacy.Initialize(Time.CurrentDate); // Initialize goal manager here. GoalManager = new Goals.GoalManager(); GoalManager.Initialize(new List <Goals.Goal>()); TutorialManager = new Tutorial.TutorialManager(); TutorialManager.TutorialEnabled = !GameSettings.Default.TutorialDisabledGlobally; Tutorial("new game start"); foreach (var item in CraftLibrary.EnumerateCraftables()) { if (!String.IsNullOrEmpty(item.Tutorial)) { TutorialManager.AddTutorial(item.Name, item.Tutorial, item.Icon); } } } Camera.World = this; //Drawer3D.Camera = Camera; #endregion SetLoadingMessage("Creating Particles ..."); ParticleManager = new ParticleManager(ComponentManager); SetLoadingMessage("Creating GameMaster ..."); Master = new GameMaster(Factions.Factions["Player"], Game, ComponentManager, ChunkManager, Camera, GraphicsDevice); if (gameFile != null) { if (gameFile.PlayData.Tasks != null) { Master.NewArrivals = gameFile.PlayData.NewArrivals ?? new List <GameMaster.ApplicantArrival>(); Master.TaskManager = gameFile.PlayData.Tasks; Master.TaskManager.Faction = Master.Faction; } if (gameFile.PlayData.InitialEmbark != null) { InitialEmbark = gameFile.PlayData.InitialEmbark; } ChunkManager.World.Master.SetMaxViewingLevel(gameFile.Metadata.Slice > 0 ? gameFile.Metadata.Slice : ChunkManager.World.Master.MaxViewingLevel); } if (Master.Faction.Economy.Company.Information == null) { Master.Faction.Economy.Company.Information = new CompanyInformation(); } CreateInitialEmbarkment(); foreach (var chunk in ChunkManager.ChunkData.ChunkMap) { chunk.CalculateInitialSunlight(); } if (RevealSurface) { VoxelHelpers.InitialReveal(ChunkManager, ChunkManager.ChunkData, new VoxelHandle( ChunkManager.ChunkData.GetChunkEnumerator().FirstOrDefault(), new LocalVoxelCoordinate(0, VoxelConstants.ChunkSizeY - 1, 0))); } foreach (var chunk in ChunkManager.ChunkData.ChunkMap) { ChunkManager.InvalidateChunk(chunk); } ChunkManager.StartThreads(); SetLoadingMessage("Presimulating ..."); ShowingWorld = false; OnLoadedEvent(); Thread.Sleep(1000); ShowingWorld = true; SetLoadingMessage("Complete."); // GameFile is no longer needed. gameFile = null; LoadStatus = LoadingStatus.Success; #if !DEBUG } catch (Exception exception) { Game.CaptureException(exception); LoadingException = exception; LoadStatus = LoadingStatus.Failure; ProgramData.WriteExceptionLog(exception); } #endif }
public static RoomData InitializeData() { Dictionary <Resource.ResourceTags, Quantitiy <Resource.ResourceTags> > roomResources = new Dictionary <Resource.ResourceTags, Quantitiy <Resource.ResourceTags> >() { { Resource.ResourceTags.Magical, new Quantitiy <Resource.ResourceTags>(Resource.ResourceTags.Magical, 2) }, { Resource.ResourceTags.Precious, new Quantitiy <Resource.ResourceTags>(Resource.ResourceTags.Precious, 1) }, }; List <RoomTemplate> libraryTemplates = new List <RoomTemplate>(); RoomTile[,] lampTemplate = { { RoomTile.None, RoomTile.Wall | RoomTile.Edge }, { RoomTile.Wall | RoomTile.Edge, RoomTile.Lamp } }; RoomTile[,] lampAccessories = { { RoomTile.None, RoomTile.None }, { RoomTile.None, RoomTile.None } }; RoomTile[,] bookshlf = { { RoomTile.Edge | RoomTile.Wall, RoomTile.Edge | RoomTile.Wall, RoomTile.Edge | RoomTile.Wall, }, { RoomTile.Open, RoomTile.BookShelf, RoomTile.Open }, }; RoomTile[,] bookshlfAcc = { { RoomTile.None, RoomTile.None, RoomTile.None }, { RoomTile.None, RoomTile.None, RoomTile.None }, { RoomTile.None, RoomTile.None, RoomTile.None } }; RoomTemplate lamp = new RoomTemplate(PlacementType.All, lampTemplate, lampAccessories); RoomTile[,] bookTemp = { { RoomTile.None, RoomTile.Open | RoomTile.Edge | RoomTile.BookShelf, RoomTile.None }, { RoomTile.Open | RoomTile.Edge | RoomTile.BookShelf, RoomTile.Books, RoomTile.Open | RoomTile.Edge | RoomTile.BookShelf, }, { RoomTile.None, RoomTile.Open | RoomTile.Edge | RoomTile.BookShelf, RoomTile.None } }; RoomTile[,] bookAcc = { { RoomTile.None, RoomTile.None, RoomTile.None }, { RoomTile.None, RoomTile.None, RoomTile.None }, { RoomTile.None, RoomTile.None, RoomTile.None } }; RoomTemplate book = new RoomTemplate(PlacementType.Random, bookTemp, bookAcc) { Probability = 0.5f }; libraryTemplates.Add(lamp); libraryTemplates.Add(new RoomTemplate(PlacementType.Random, bookshlf, bookshlfAcc) { Probability = 0.15f }); libraryTemplates.Add(book); Texture2D roomIcons = AssetManager.GetContentTexture(ContentPaths.GUI.room_icons); return(new RoomData(LibraryRoomName, 4, "Blue Tile", roomResources, libraryTemplates, new Gui.TileReference("rooms", 4)) { Description = "Wizards do magical research here. Also holds mana crystals to charge magic spells.", CanBuildAboveGround = false }); }
public override void CreateCosmeticChildren(ComponentManager manager) { base.CreateCosmeticChildren(manager); if (Resource.Gui_NewStyle) { var sheetName = String.Format("{0}&{1}-{2}&{3}", Resource.Gui_Graphic.AssetPath, Resource.Gui_Graphic.Frame.X, Resource.Gui_Graphic.Frame.Y, Resource.Gui_Palette); var tiledInstanceGroup = Manager.World.Renderer.InstanceRenderer.GetCombinedTiledInstance(); Texture2D fixedTex = null; if (!tiledInstanceGroup.DoesInstanceSheetExist(sheetName)) { if (DwarfSprites.LayerLibrary.FindPalette(Resource.Gui_Palette).HasValue(out var palette)) { fixedTex = TextureTool.CropAndColorSprite(manager.World.Renderer.GraphicsDevice, AssetManager.GetContentTexture(Resource.Gui_Graphic.AssetPath), Resource.Gui_Graphic.FrameSize, Resource.Gui_Graphic.Frame, DwarfSprites.LayerLibrary.BasePalette.CachedPalette, palette.CachedPalette); } } var sheet = new SpriteSheet(fixedTex) { FrameWidth = Resource.Gui_Graphic.FrameSize.X, FrameHeight = Resource.Gui_Graphic.FrameSize.Y, AssetName = sheetName }; var sprite = AddChild(new SimpleBobber(Manager, "Sprite", Matrix.CreateTranslation(Vector3.UnitY * 0.25f), sheet, Point.Zero, 0.15f, MathFunctions.Rand() + 2.0f, MathFunctions.Rand() * 3.0f)) as Tinter; sprite.LocalTransform = Matrix.CreateTranslation(Vector3.UnitY * 0.25f + MathFunctions.RandVector3Cube() * 0.1f); sprite.LightRamp = Resource.Tint; sprite.SetFlag(Flag.ShouldSerialize, false); } else { var compositeLayers = Resource.CompositeLayers; var tint = Resource.Tint; Tinter sprite = null; // Minor optimization for single layer resources. if (compositeLayers.Count == 1) { var layer = compositeLayers[0]; sprite = AddChild(new SimpleBobber(Manager, "Sprite", Matrix.CreateTranslation(Vector3.UnitY * 0.25f), new SpriteSheet(layer.Asset, layer.FrameSize.X, layer.FrameSize.Y), layer.Frame, 0.15f, MathFunctions.Rand() + 2.0f, MathFunctions.Rand() * 3.0f) { OrientationType = SimpleSprite.OrientMode.Spherical, WorldHeight = 0.75f, WorldWidth = 0.75f, }) as Tinter; sprite.LocalTransform = Matrix.CreateTranslation(Vector3.UnitY * 0.25f + MathFunctions.RandVector3Cube() * 0.1f); } else { var layers = new List <LayeredSimpleSprite.Layer>(); foreach (var layer in compositeLayers) { layers.Add(new LayeredSimpleSprite.Layer { Sheet = new SpriteSheet(layer.Asset, layer.FrameSize.X, layer.FrameSize.Y), Frame = layer.Frame }); } sprite = AddChild(new LayeredBobber(Manager, "Sprite", Matrix.CreateTranslation(Vector3.UnitY * 0.25f + MathFunctions.RandVector3Cube() * 0.1f), layers, 0.15f, MathFunctions.Rand() + 2.0f, MathFunctions.Rand() * 3.0f) { OrientationType = LayeredSimpleSprite.OrientMode.Spherical, WorldHeight = 0.75f, WorldWidth = 0.75f, }) as Tinter; } sprite.LightRamp = tint; sprite.SetFlag(Flag.ShouldSerialize, false); } }
public static Texture2D RenderPatternIcons(GraphicsDevice device, Microsoft.Xna.Framework.Content.ContentManager Content, Gui.TileSheetDefinition Sheet) { InitializeRailLibrary(); var shader = new Shader(Content.Load <Effect>(ContentPaths.Shaders.TexturedShaders), true); var sqrt = (int)(Math.Ceiling(Math.Sqrt(RailPatterns.Count))); var width = MathFunctions.NearestPowerOf2(sqrt * Sheet.TileWidth); var fitHorizontal = width / Sheet.TileWidth; var rowCount = (int)Math.Ceiling((float)RailPatterns.Count / (float)fitHorizontal); var height = MathFunctions.NearestPowerOf2(rowCount * Sheet.TileHeight); RenderTarget2D toReturn = new RenderTarget2D(device, width, height, false, SurfaceFormat.Color, DepthFormat.Depth16, 0, RenderTargetUsage.PreserveContents); var tileSheet = new SpriteSheet(ContentPaths.rail_tiles, 32); device.SetRenderTarget(toReturn); device.Clear(Color.Transparent); shader.SetTexturedTechnique(); shader.MainTexture = AssetManager.GetContentTexture(ContentPaths.rail_tiles); shader.SelfIlluminationEnabled = true; shader.SelfIlluminationTexture = AssetManager.GetContentTexture(ContentPaths.Terrain.terrain_illumination); shader.EnableShadows = false; shader.EnableLighting = false; shader.ClippingEnabled = false; shader.CameraPosition = new Vector3(-0.5f, 0.5f, 0.5f); shader.VertexColorTint = Color.White; shader.LightRamp = Color.White; shader.SunlightGradient = AssetManager.GetContentTexture(ContentPaths.Gradients.sungradient); shader.AmbientOcclusionGradient = AssetManager.GetContentTexture(ContentPaths.Gradients.ambientgradient); shader.TorchlightGradient = AssetManager.GetContentTexture(ContentPaths.Gradients.torchgradient); Viewport oldview = device.Viewport; int rows = height / Sheet.TileWidth; int cols = width / Sheet.TileWidth; device.ScissorRectangle = new Rectangle(0, 0, Sheet.TileWidth, Sheet.TileHeight); device.RasterizerState = RasterizerState.CullNone; device.DepthStencilState = DepthStencilState.Default; Vector3 half = Vector3.One * 0.5f; half = new Vector3(half.X, half.Y, half.Z); foreach (EffectPass pass in shader.CurrentTechnique.Passes) { int ID = 0; foreach (var type in RailPatterns) { int row = ID / cols; int col = ID % cols; var xboundsMin = 0; var xboundsMax = 0; var yboundsMin = 0; var yboundsMax = 0; var primitive = new RawPrimitive(); foreach (var piece in type.Pieces) { var rawPiece = Library.GetRailPiece(piece.RailPiece); var bounds = Vector4.Zero; var uvs = tileSheet.GenerateTileUVs(rawPiece.HasValue(out var raw) ? raw.Tile : Point.Zero, out bounds); primitive.AddQuad( Matrix.CreateRotationY((float)Math.PI * 0.5f * (float)piece.Orientation) * Matrix.CreateTranslation(new Vector3(piece.Offset.X, 0.0f, piece.Offset.Y)), Color.White, Color.White, uvs, bounds); xboundsMin = Math.Min(xboundsMin, piece.Offset.X); xboundsMax = Math.Max(xboundsMax, piece.Offset.X); yboundsMin = Math.Min(yboundsMin, piece.Offset.Y); yboundsMax = Math.Max(yboundsMax, piece.Offset.Y); } float xSize = xboundsMax - xboundsMin + 1; float ySize = yboundsMax - yboundsMin + 1; var cameraPos = new Vector3(xboundsMin + (xSize / 2), 2.0f, yboundsMax + 1.0f); device.Viewport = new Viewport(col * Sheet.TileWidth, row * Sheet.TileHeight, Sheet.TileWidth, Sheet.TileHeight); shader.View = Matrix.CreateLookAt(cameraPos, new Vector3((xboundsMin + (xSize / 2)), 0.0f, yboundsMin), Vector3.UnitY); shader.Projection = Matrix.CreatePerspectiveFieldOfView(1.0f, 1.0f, 0.1f, 10); shader.World = Matrix.Identity; shader.CameraPosition = cameraPos; pass.Apply(); primitive.Render(device); ++ID; } } device.Viewport = oldview; device.SetRenderTarget(null); return((Texture2D)toReturn); }
public static SpellTree CreateSpellTree(WorldManager world) { Texture2D icons = AssetManager.GetContentTexture(ContentPaths.GUI.icons); SpellTree toReturn = new SpellTree() { RootSpells = new List <SpellTree.Node>() { new SpellTree.Node() { Spell = new InspectSpell(world, InspectSpell.InspectType.InspectEntity), ResearchProgress = 10.0f, ResearchTime = 10.0f, Children = new List <SpellTree.Node>() { new SpellTree.Node() { Spell = new BuffSpell(world, new StatBuff(30.0f, new CreatureStats.StatNums() { Dexterity = 2.0f, Strength = 2.0f, Wisdom = 2.0f, Intelligence = 2.0f, Charisma = 0.0f, Constitution = 0.0f, Size = 0.0f }) { Particles = "star_particle", SoundOnStart = ContentPaths.Audio.powerup, SoundOnEnd = ContentPaths.Audio.wurp } ) { Name = "Minor Inspire", Description = "Makes the selected creatures work harder for 30 seconds (+2 to DEX, STR, INT and WIS)", Hint = "Click and drag to select creatures" }, ResearchProgress = 0.0f, ResearchTime = 30.0f, Children = new List <SpellTree.Node>() { new SpellTree.Node() { Spell = new BuffSpell(world, new StatBuff(60.0f, new CreatureStats.StatNums() { Dexterity = 5.0f, Strength = 5.0f, Wisdom = 5.0f, Intelligence = 5.0f, Charisma = 0.0f, Constitution = 0.0f, Size = 0.0f }) { Particles = "star_particle", SoundOnStart = ContentPaths.Audio.powerup, SoundOnEnd = ContentPaths.Audio.wurp } ) { Name = "Major Inspire", Description = "Makes the selected creatures work harder for 60 seconds (+5 to DEX, STR, INT and WIS)", Hint = "Click and drag to select creatures" }, Children = new List <SpellTree.Node>() { new SpellTree.Node() { Spell = new CreateEntitySpell(world, "Fairy", false) { Name = "Magic Helper", Description = "Creates a magical helper employee who persists for 30 seconds", Hint = "Click to spawn a helper" }, ResearchProgress = 0.0f, ResearchTime = 150.0f } }, ResearchProgress = 0.0f, ResearchTime = 60.0f, }, new SpellTree.Node() { Spell = new BuffSpell(world, new ThoughtBuff(30.0f, Thought.ThoughtType.Magic) { SoundOnStart = ContentPaths.Audio.powerup }) { Name = "Minor Happiness", Description = "Makes the selected creatures happy for 30 seconds.", Hint = "Click and drag to select creatures", Image = new ImageFrame(AssetManager.GetContentTexture(ContentPaths.GUI.icons), 32, 5, 2), TileRef = 21 }, ResearchTime = 60.0f, ResearchProgress = 0.0f, Children = new List <SpellTree.Node>() { new SpellTree.Node() { Spell = new BuffSpell(world, new ThoughtBuff(60.0f, Thought.ThoughtType.Magic) { SoundOnStart = ContentPaths.Audio.powerup }) { Name = "Major Happiness", Description = "Makes the selected creatures happy for 60 seconds.", Hint = "Click and drag to select creatures", Image = new ImageFrame(AssetManager.GetContentTexture(ContentPaths.GUI.icons), 32, 5, 2), TileRef = 21 }, ResearchTime = 120.0f, ResearchProgress = 0.0f } } } } } } }, new SpellTree.Node() { Spell = new InspectSpell(world, InspectSpell.InspectType.InspectBlock), ResearchProgress = 25.0f, ResearchTime = 25.0f, Children = new List <SpellTree.Node>() { new SpellTree.Node() { Spell = new PlaceBlockSpell(world, "Dirt", false), ResearchProgress = 0.0f, ResearchTime = 50.0f, Children = new List <SpellTree.Node>() { new SpellTree.Node() { ResearchProgress = 0.0f, ResearchTime = 100.0f, Spell = new PlaceBlockSpell(world, "Stone", false), Children = new List <SpellTree.Node>() { new SpellTree.Node() { ResearchProgress = 0.0f, ResearchTime = 150.0f, Spell = new DestroyBlockSpell(world) } } } } }, new SpellTree.Node() { Spell = new PlaceBlockSpell(world, "Magic", false) { Image = new ImageFrame(AssetManager.GetContentTexture(ContentPaths.GUI.icons), 32, 2, 3), Description = "Creates a temporary magic wall.", TileRef = 26 }, ResearchProgress = 0.0f, ResearchTime = 50.0f, Children = new List <SpellTree.Node>() { new SpellTree.Node() { ResearchProgress = 0.0f, ResearchTime = 100.0f, Spell = new PlaceBlockSpell(world, "Iron", true), Children = new List <SpellTree.Node>() { new SpellTree.Node() { ResearchProgress = 0.0f, ResearchTime = 150.0f, Spell = new PlaceBlockSpell(world, "Gold", true) } } } } } } }, new SpellTree.Node() { Spell = new BuffSpell(world, new OngoingHealBuff(2, 10) { Particles = "heart", SoundOnStart = ContentPaths.Audio.powerup, SoundOnEnd = ContentPaths.Audio.wurp }) { Name = "Minor Heal", Description = "Heals 2 damage per second for 10 seconds", Hint = "Click and drag to select creatures", Image = new ImageFrame(AssetManager.GetContentTexture(ContentPaths.GUI.icons), 32, 3, 2), TileRef = 19 }, ResearchProgress = 0.0f, ResearchTime = 30.0f, Children = new List <SpellTree.Node>() { new SpellTree.Node() { Spell = new BuffSpell(world, new OngoingHealBuff(5, 10) { Particles = "heart", SoundOnStart = ContentPaths.Audio.powerup, SoundOnEnd = ContentPaths.Audio.wurp }) { Name = "Major Heal", Description = "Heals 5 damage per second for 10 seconds", Hint = "Click and drag to select creatures", Image = new ImageFrame(AssetManager.GetContentTexture(ContentPaths.GUI.icons), 32, 3, 2), TileRef = 19 }, ResearchProgress = 0.0f, ResearchTime = 150.0f } } } } }; foreach (SpellTree.Node spell in toReturn.RootSpells) { spell.SetupParentsRecursive(); } return(toReturn); }
public static void InitializeDefaultLibrary(GraphicsDevice graphics) { if (TypeList != null) { return; } var cubeTexture = AssetManager.GetContentTexture(ContentPaths.Terrain.terrain_tiles); TypeList = FileUtils.LoadJsonListFromDirectory <VoxelType>(ContentPaths.voxel_types, null, v => v.Name); emptyType = TypeList.FirstOrDefault(v => v.Name == "_empty"); DesignationType = TypeList.FirstOrDefault(v => v.Name == "_designation"); // Todo: Stabalize ids across save games. short id = 2; foreach (VoxelType type in TypeList) { Types[type.Name] = type; if (type.Name == "_empty") { emptyType = type; type.ID = 0; } else { PrimitiveMap[type.Name] = CreatePrimitive(graphics, cubeTexture, 32, 32, type.Top, type.Bottom, type.Sides); if (type.Name == "_designation") { DesignationType = type; type.ID = 1; } else { type.ID = id; id += 1; } } if (type.HasTransitionTextures) { type.TransitionTextures = CreateTransitionUVs(graphics, cubeTexture, 32, 32, type.TransitionTiles, type.Transitions); } type.ExplosionSound = SoundSource.Create(type.ExplosionSoundResource); type.HitSound = SoundSource.Create(type.HitSoundResources); if (type.ReleasesResource) { if (ResourceLibrary.GetResourceByName(type.Name) == null) { var resource = new Resource(ResourceLibrary.GetResourceByName(type.ResourceToRelease)) { Name = type.Name, ShortName = type.Name, Tint = type.Tint, Generated = false }; ResourceLibrary.Add(resource); type.ResourceToRelease = resource.Name; } } } TypeList = TypeList.OrderBy(v => v.ID).ToList(); if (TypeList.Count > VoxelConstants.MaximumVoxelTypes) { throw new InvalidProgramException(String.Format("There can be only {0} voxel types.", VoxelConstants.MaximumVoxelTypes)); } }