public Core(int width = 1280, int height = 720, bool isFullScreen = false, bool enableEntitySystems = true, string windowTitle = "Nez") { #if DEBUG _windowTitle = windowTitle; #endif _instance = this; emitter = new Emitter <CoreEvents>(new CoreEventsComparer()); var graphicsManager = new GraphicsDeviceManager(this); graphicsManager.PreferredBackBufferWidth = width; graphicsManager.PreferredBackBufferHeight = height; graphicsManager.IsFullScreen = isFullScreen; graphicsManager.SynchronizeWithVerticalRetrace = true; graphicsManager.DeviceReset += onGraphicsDeviceReset; graphicsManager.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8; Screen.initialize(graphicsManager); Content.RootDirectory = "Content"; contentManager = new NezContentManager(Services, Content.RootDirectory); IsMouseVisible = true; IsFixedTimeStep = false; entitySystemsEnabled = enableEntitySystems; }
public GiaScene() { ClearColor = Color.CornflowerBlue; Gia.BeingConstructed = this; View = new Camera(); AutoResizeToNativeResolution = true; AspectRatio = AspectRatioResolution.Stretch; AspectOrigin = new Vector2(0.5f, 0.5f); SamplerState = SamplerState.PointClamp; SetSceneSize(Screen.Width, Screen.Height); DestroyOnExit = false; Nubs = new FastList <WindowTitleNub>(); Runner = new DefaultParallelRunner(Environment.ProcessorCount); World = new World(); Content = new NezContentManager(); UpdateSystems = new FastList <ISystem <GiaScene> >(); RenderSystems = new FastList <ISystem <GiaScene> >(); Batcher = Graphics.Instance.Batcher; ConstructSystemGraph(UpdateSystems, RenderSystems); ConstructEntityGraph(); InitializeScene(); Gia.BeingConstructed = null; Core.Instance.Window.ClientSizeChanged += (s, e) => AdaptSize(); }
public Core(int width = 1280, int height = 720, bool isFullScreen = false, bool enableEntitySystems = true, string windowTitle = "Nez", string contentDirectory = "Content") { #if DEBUG _windowTitle = windowTitle; #endif _instance = this; emitter = new Emitter <CoreEvents>(new CoreEventsComparer()); var graphicsManager = new GraphicsDeviceManager(this); graphicsManager.PreferredBackBufferWidth = width; graphicsManager.PreferredBackBufferHeight = height; graphicsManager.IsFullScreen = isFullScreen; graphicsManager.SynchronizeWithVerticalRetrace = true; graphicsManager.DeviceReset += onGraphicsDeviceReset; graphicsManager.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8; Screen.initialize(graphicsManager); Window.ClientSizeChanged += onGraphicsDeviceReset; Window.OrientationChanged += onOrientationChanged; Content.RootDirectory = contentDirectory; content = new NezGlobalContentManager(Services, Content.RootDirectory); IsMouseVisible = true; IsFixedTimeStep = false; entitySystemsEnabled = enableEntitySystems; // setup systems _globalManagers.add(_coroutineManager); _globalManagers.add(new TweenManager()); _globalManagers.add(_timerManager); _globalManagers.add(new RenderTarget()); }
public HelloScene() { // setup a pixel perfect screen that fits our map SetDesignResolution(512, 256, SceneResolutionPolicy.ExactFit); Screen.SetSize(512 * 3, 256 * 3); var playerEntity = CreateEntity("player", new Microsoft.Xna.Framework.Vector2(Screen.Width / 4, Screen.Height / 4)); playerEntity.AddComponent(new Player()); Camera.Entity.AddComponent(new FollowCamera(playerEntity)); Console.Write("HELLO SCENE"); var enemyEntity = CreateEntity("enemy", new Microsoft.Xna.Framework.Vector2(Screen.Width / 4 - 20, Screen.Height / 4 - 20)); enemyEntity.AddComponent(new Robot()); Console.Write("HELLO SCENE"); var manager = new NezContentManager(); var map = manager.LoadTiledMap("Content/Tiles/tilemap.tmx"); //Core.Content.LoadTiledMap() var tiledEntity = CreateEntity("tiled-map-entity"); //var map = Content.LoadTiledMap("Content/Tiles/tilemap.tmx"); var tiledMapRenderer = tiledEntity.AddComponent(new TiledMapRenderer(map, "collision")); tiledMapRenderer.SetLayersToRender(new[] { "tiles", "terrain", "details", "collision" }); tiledMapRenderer.RenderLayer = 10; // render our above-details layer after the player so the player is occluded by it when walking behind things // render things like tops of trees var tiledMapDetailsComp = tiledEntity.AddComponent(new TiledMapRenderer(map)); tiledMapDetailsComp.SetLayerToRender("above-details"); tiledMapDetailsComp.RenderLayer = -1; // have the camera follow the player }
public static IsometricMap Load(this NezContentManager content, string path) { var map = ParseXml($"{content.RootDirectory}{path}"); map.SortTilesets(); map.LoadTextures(content); return(map); }
/// <summary> /// attempts to get a texture for the image /// - first it will check the href for a png file name. If it finds one it will load it with the ContentManager passed in /// - next it will see if the href is a url and if so it will load it /// - next it checks for an embedded, base64 image. It will load that if it finds one /// </summary> /// <returns>The texture.</returns> /// <param name="content">Content.</param> public Texture2D GetTexture(NezContentManager content) { if (_didAttemptTextureLoad || _texture != null) { return(_texture); } // check for a url if (Href.StartsWith("http")) { #if USE_HTTPCLIENT using (var client = new System.Net.Http.HttpClient()) { var stream = client.GetStreamAsync(Href).Result; _texture = Texture2D.FromStream(Core.GraphicsDevice, stream); } #else throw new Exception("Found a texture in an SVG file but the USE_HTTPCLIENT build define is not set and/or HTTP Client is not referenced"); #endif } // see if we have a path to a png files in the href else if (Href.EndsWith("png")) { // check for existance before attempting to load! We are a PCL so we cant so we'll catch the Exception instead try { if (content != null) { _texture = content.Load <Texture2D>(Href); } } catch (ContentLoadException) { Debug.Error("Could not load SvgImage from href: {0}", Href); } } // attempt to parse the base64 string if it is embedded in the href else if (Href.StartsWith("data:")) { var startIndex = Href.IndexOf("base64,", StringComparison.OrdinalIgnoreCase) + 7; var imageContents = Href.Substring(startIndex); var bytes = Convert.FromBase64String(imageContents); using (var m = new MemoryStream()) { m.Write(bytes, 0, bytes.Length); m.Seek(0, SeekOrigin.Begin); _texture = Texture2D.FromStream(Core.GraphicsDevice, m); } } _didAttemptTextureLoad = true; return(_texture); }
public static List <Vector2[]> LoadPolygons(this NezContentManager content, string name) { List <Vector2[]> polys = new List <Vector2[]>(); using (var stream = TitleContainer.OpenStream(name)) using (StreamReader sr = new StreamReader(stream)) { polys.AddRange(Json.FromJson <Vector2[][]>(sr.ReadToEnd())); } return(polys); }
/// <summary> /// creates a UISkin from a UISkinConfig /// </summary> /// <param name="configName">the path of the UISkinConfig xnb</param> /// <param name="contentManager">Content manager.</param> public Skin(string configName, NezContentManager contentManager) { var config = contentManager.Load <UISkinConfig>(configName); if (config.Colors != null) { foreach (var entry in config.Colors) { Add(entry.Key, config.Colors[entry.Key]); } } if (config.TextureAtlases != null) { foreach (var atlas in config.TextureAtlases) { AddSprites(contentManager.LoadSpriteAtlas(atlas)); } } if (config.Styles != null) { var styleClasses = config.Styles.GetStyleClasses(); for (var i = 0; i < styleClasses.Count; i++) { var styleType = styleClasses[i]; try { var type = Type.GetType("Nez.UI." + styleType, true); var styleNames = config.Styles.GetStyleNames(styleType); for (var j = 0; j < styleNames.Count; j++) { var style = Activator.CreateInstance(type); var styleDict = config.Styles.GetStyleDict(styleType, styleNames[j]); // Get the method by simple name check since we know it's the only one var setStylesForStyleClassMethod = ReflectionUtils.GetMethodInfo(this, "SetStylesForStyleClass"); setStylesForStyleClassMethod = setStylesForStyleClassMethod.MakeGenericMethod(type); // Return not nec., but it shows that the style is being modified style = setStylesForStyleClassMethod.Invoke(this, new object[] { style, styleDict, contentManager, styleNames[j] }); Add(styleNames[j], style, type); } } catch (Exception e) { Debug.Error("Error creating style from UISkin: {0}", e); } } } }
public void Load(NezContentManager content, Vector2 ScreenVector) { myMap = new TiledMap(0, (int)ScreenVector.X, (int)ScreenVector.Y, TileData.TileSize, TileData.TileSize, TiledMapOrientation.Orthogonal); //TODO: multilayer support TiledTileLayer Floors = (TiledTileLayer)myMap.createTileLayer("Floors", (int)ScreenVector.X, (int)ScreenVector.Y); Collidables = (TiledTileLayer)myMap.createTileLayer("Walls", (int)ScreenVector.X, (int)ScreenVector.Y); int XOffset = (int)Mathf.ceil(0.5f * (ScreenVector.X / TileData.TileSize)); int YOffset = (int)Mathf.ceil(0.5f * (ScreenVector.Y / TileData.TileSize)); TiledTileset BaseMapTileset = myMap.createTileset(content.Load <Texture2D>(this.MapTextureAtlas), 0, 64, 64, true, 0, 0, this.TextureAtlasTileWidth, this.TextureAtlasTileHeight); for (int x = 0; x < Mathf.ceil(ScreenVector.X / TileData.TileSize); x++) { for (int y = 0; y < Mathf.ceil(ScreenVector.X / TileData.TileSize); x++) { TileData myTileData; TiledTile myTile; Tuple <float, float, float> tuple = new Tuple <float, float, float>(x, y, (float)Math.Ceiling(TileData.MaxHeight * myNoise.GetNoise(x, y))); if (myModifiedTiles.TryGetValue(tuple, out myTileData)) { myTile = new TiledTile(myTileData.TileSetID); myTile.tileset = myMap.createTileset(content.Load <Texture2D>(myTileData.TilesetName), 0, TileData.TileSize, TileData.TileSize, true, 0, 0, myTileData.TextureAtlasTileWidth, myTileData.TextureAtlasTileHeight); if (myTileData.isWall) { Collidables.setTile(myTile); } else { Floors.setTile(myTile); } } else { if (tuple.Item3 > 0) { myTile = new TiledTile(1); myTile.tileset = BaseMapTileset; Collidables.setTile(myTile); } else if (tuple.Item3 == 0) { myTile = new TiledTile(0); myTile.tileset = BaseMapTileset; Floors.setTile(myTile); } else { continue; } } } } }
/// <summary> /// attempts to get a texture for the image /// - first it will check the href for a png file name. If it finds one it will load it with the ContentManager passed in /// - next it will see if the href is a url and if so it will load it /// - next it checks for an embedded, base64 image. It will load that if it finds one /// </summary> /// <returns>The texture.</returns> /// <param name="content">Content.</param> public Texture2D getTexture( NezContentManager content ) { if( _didAttemptTextureLoad || _texture != null ) return _texture; // check for a url if( href.StartsWith( "http" ) ) { using( var client = new System.Net.Http.HttpClient() ) { var stream = client.GetStreamAsync( href ).Result; _texture = Texture2D.FromStream( Core.graphicsDevice, stream ); } } // see if we have a path to a png files in the href else if( href.EndsWith( "png" ) ) { // check for existance before attempting to load! We are a PCL so we cant so we'll catch the Exception instead try { if( content != null ) _texture = content.Load<Texture2D>( href ); } catch( ContentLoadException ) { Debug.error( "Could not load SvgImage from href: {0}", href ); } } // attempt to parse the base64 string if it is embedded in the href else if( href.StartsWith( "data:" ) ) { var startIndex = href.IndexOf( "base64,", StringComparison.OrdinalIgnoreCase ) + 7; var imageContents = href.Substring( startIndex ); var bytes = Convert.FromBase64String( imageContents ); using( var m = new MemoryStream() ) { m.Write( bytes, 0, bytes.Length ); m.Seek( 0, SeekOrigin.Begin ); _texture = Texture2D.FromStream( Core.graphicsDevice, m ); } } _didAttemptTextureLoad = true; return _texture; }
public Scene() { entities = new EntityList( this ); renderableComponents = new RenderableComponentList(); content = new NezContentManager(); var cameraEntity = createEntity( "camera" ); camera = cameraEntity.addComponent( new Camera() ); if( Core.entitySystemsEnabled ) entityProcessors = new EntityProcessorList(); // setup our resolution policy. we'll commit it in begin _resolutionPolicy = defaultSceneResolutionPolicy; _designResolutionSize = defaultDesignResolutionSize; initialize(); }
/// <summary> /// Creates skin styles /// </summary> /// <param name="contentManager">Content manager</param> public GameSkin(NezContentManager contentManager) { Skin = new Skin(); Skin.Add("title-label", new LabelStyle() { Font = contentManager.LoadBitmapFont(Content.OswaldTitleFont) }); Skin.Add("label", new LabelStyle() { Font = contentManager.LoadBitmapFont(Content.DefaultTitleFont) }); var inputCursor = new PrimitiveDrawable(Color.Black); inputCursor.MinHeight = 10; inputCursor.MinWidth = 5; var font = contentManager.LoadBitmapFont(Content.DefaultTitleFont); font.FontSize = 24; var style = Skin.Add("inputfield", new TextFieldStyle() { Font = font, FontColor = Color.Black, Cursor = inputCursor, FocusedBackground = new PrimitiveDrawable(Color.Gray), Background = new PrimitiveDrawable(Color.White), Selection = new PrimitiveDrawable(Color.Blue) }); Skin.Add("regular-button", TextButtonStyle.Create(Color.Gray, new Color(61, 9, 85), new Color(61, 9, 107))); var sliderStyle = SliderStyle.Create(Color.Yellow, new Color(61, 9, 107)); sliderStyle.Knob.MinWidth *= 1.5f; sliderStyle.Knob.MinHeight *= 1.5f; sliderStyle.Background.MinWidth *= 0.5f; Skin.Add("slider", sliderStyle); }
/// <summary> /// creates a UISkin from a UISkinConfig /// </summary> /// <param name="configName">the path of the UISkinConfig xnb</param> /// <param name="contentManager">Content manager.</param> public Skin(string configName, NezContentManager contentManager) { var config = contentManager.Load <UISkinConfig>(configName); if (config.colors != null) { foreach (var entry in config.colors) { add <Color>(entry.Key, config.colors[entry.Key]); } } if (config.textureAtlases != null) { foreach (var atlas in config.textureAtlases) { addSubtextures(contentManager.Load <TextureAtlas>(atlas)); } } if (config.libGdxAtlases != null) { foreach (var atlas in config.libGdxAtlases) { addSubtextures(contentManager.Load <LibGdxAtlas>(atlas)); } } if (config.styles != null) { var styleClasses = config.styles.getStyleClasses(); for (var i = 0; i < styleClasses.Count; i++) { var styleType = styleClasses[i]; try { var type = Type.GetType("Nez.UI." + styleType, true); var styleNames = config.styles.getStyleNames(styleType); for (var j = 0; j < styleNames.Count; j++) { var style = Activator.CreateInstance(type); var styleDict = config.styles.getStyleDict(styleType, styleNames[j]); foreach (var styleConfig in styleDict) { var name = styleConfig.Key; var identifier = styleConfig.Value; // if name has 'color' in it, we are looking for a color. we check color first because some styles have things like // fontColor so we'll check for font after color. if (name.ToLower().Contains("color")) { ReflectionUtils.getFieldInfo(style, name).SetValue(style, getColor(identifier)); } else if (name.ToLower().Contains("font")) { ReflectionUtils.getFieldInfo(style, name).SetValue(style, contentManager.Load <BitmapFont>(identifier)); } else if (name.ToLower().EndsWith("style")) { // we have a style reference. first we need to find out what type of style name refers to from the field. // then we need to fetch the "get" method and properly type it. var styleField = ReflectionUtils.getFieldInfo(style, name); var getStyleMethod = ReflectionUtils.getMethodInfo(this, "get", new Type[] { typeof(string) }); getStyleMethod = getStyleMethod.MakeGenericMethod(styleField.FieldType); // now we look up the style and finally set it var theStyle = getStyleMethod.Invoke(this, new object[] { identifier }); styleField.SetValue(style, theStyle); } else { // we have an IDrawable. first we'll try to find a Subtexture and if we cant find one we will see if // identifier is a color var drawable = getDrawable(identifier); if (drawable != null) { ReflectionUtils.getFieldInfo(style, name).SetValue(style, drawable); } else { Debug.error("could not find a drawable or color named {0} when setting {1} on {2}", identifier, name, styleNames[j]); } } } add(styleNames[j], style, type); } } catch (Exception e) { Debug.error("Error creating style from UISkin: {0}", e); } } } }
public LevelBuilder(NezContentManager contentManager, LevelDescriptor levelDescriptor) { this.contentManager = contentManager ?? throw new ArgumentNullException(nameof(contentManager)); this.levelDescriptor = levelDescriptor ?? throw new ArgumentNullException(nameof(levelDescriptor)); }
/// <summary> /// Recursively finds and sets all styles for a specific style config class that are within /// the dictionary passed in. This allows skins to contain nested, dynamic style declarations. /// For example, it allows a SelectBoxStyle to contain a listStyle that is declared inline /// (and not a reference). /// </summary> /// <param name="styleClass">The style config class instance that needs to be "filled out"</param> /// <param name="styleDict">A dictionary that represents one style name within the style config class (i.e. 'default').</param> /// <param name="styleName">The style name that the dictionary represents (i.e. 'default').</param> /// <typeparam name="T">The style config class type (i.e. SelectBoxStyle)</typeparam> public T SetStylesForStyleClass <T>(T styleClass, Dictionary <string, object> styleDict, NezContentManager contentManager, string styleName) { foreach (var styleConfig in styleDict) { var name = styleConfig.Key; var valueObject = styleConfig.Value; var identifier = valueObject.ToString(); // if name has 'color' in it, we are looking for a color. we check color first because some styles have things like // fontColor so we'll check for font after color. We assume these are strings and do no error checking on 'identifier' if (name.ToLower().Contains("color")) { ReflectionUtils.GetFieldInfo(styleClass, name).SetValue(styleClass, GetColor(identifier)); } else if (name.ToLower().Contains("font")) { ReflectionUtils.GetFieldInfo(styleClass, name) .SetValue(styleClass, contentManager.Load <BitmapFont>(identifier)); } else if (name.ToLower().EndsWith("style")) { var styleField = ReflectionUtils.GetFieldInfo(styleClass, name); // Check to see if valueObject is a Dictionary object instead of a string. If so, it is an 'inline' style // and needs to be recursively parsed like any other style. Otherwise, it is assumed to be a string and // represents an existing style that has been previously parsed. if (valueObject is Dictionary <string, object> ) { // Since there is no existing field to reference, we create it and fill it out by hand var inlineStyle = Activator.CreateInstance(styleField.FieldType); // Recursively call this method with the new field type and dictionary var setStylesForStyleClassMethod = ReflectionUtils.GetMethodInfo(this, "SetStylesForStyleClass"); setStylesForStyleClassMethod = setStylesForStyleClassMethod.MakeGenericMethod(styleField.FieldType); inlineStyle = setStylesForStyleClassMethod.Invoke(this, new object[] { inlineStyle, valueObject as Dictionary <string, object>, contentManager, styleName }); styleField.SetValue(styleClass, inlineStyle); } else { // We have a style reference. First we need to find out what type of style name refers to from the field. // Then we need to fetch the "get" method and properly type it. var getStyleMethod = ReflectionUtils.GetMethodInfo(this, "Get", new Type[] { typeof(string) }); getStyleMethod = getStyleMethod.MakeGenericMethod(styleField.FieldType); // now we look up the style and finally set it var theStyle = getStyleMethod.Invoke(this, new object[] { identifier }); styleField.SetValue(styleClass, theStyle); if (theStyle == null) { Debug.Error("could not find a style reference named {0} when setting {1} on {2}", identifier, name, styleName); } } } else { // we have an IDrawable. first we'll try to find a Sprite and if we cant find one we will see if // identifier is a color var drawable = GetDrawable(identifier); if (drawable != null) { ReflectionUtils.GetFieldInfo(styleClass, name).SetValue(styleClass, drawable); } else { Debug.Error("could not find a drawable or color named {0} when setting {1} on {2}", identifier, name, styleName); } } } return(styleClass); }
public Core( int width = 1280, int height = 720, bool isFullScreen = false, bool enableEntitySystems = true, string windowTitle = "Nez" ) { #if DEBUG _windowTitle = windowTitle; #endif _instance = this; emitter = new Emitter<CoreEvents>( new CoreEventsComparer() ); var graphicsManager = new GraphicsDeviceManager( this ); graphicsManager.PreferredBackBufferWidth = width; graphicsManager.PreferredBackBufferHeight = height; graphicsManager.IsFullScreen = isFullScreen; graphicsManager.SynchronizeWithVerticalRetrace = true; graphicsManager.DeviceReset += onGraphicsDeviceReset; graphicsManager.PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8; Screen.initialize( graphicsManager ); Window.ClientSizeChanged += onGraphicsDeviceReset; Window.OrientationChanged += onOrientationChanged; Content.RootDirectory = "Content"; contentManager = new NezGlobalContentManager( Services, Content.RootDirectory ); IsMouseVisible = true; IsFixedTimeStep = false; entitySystemsEnabled = enableEntitySystems; // setup systems _globalManagers.add( _coroutineManager ); _globalManagers.add( new TweenManager() ); _globalManagers.add( _timerManager ); _globalManagers.add( new RenderTarget() ); }
public static void Create(NezContentManager myManager) { Content = myManager; }
/// <summary> /// creates a UISkin from a UISkinConfig /// </summary> /// <param name="config">Config.</param> /// <param name="contentManager">Content manager.</param> public Skin(string configName, NezContentManager contentManager) { var config = contentManager.Load <UISkinConfig>(configName); if (config.colors != null) { foreach (var entry in config.colors) { add <Color>(entry.Key, config.colors[entry.Key]); } } if (config.textureAtlases != null) { foreach (var atlas in config.textureAtlases) { addSubtextures(contentManager.Load <TextureAtlas>(atlas)); } } if (config.libGdxAtlases != null) { foreach (var atlas in config.libGdxAtlases) { addSubtextures(contentManager.Load <LibGdxAtlas>(atlas)); } } if (config.styles != null) { var styleClasses = config.styles.getStyleClasses(); for (var i = 0; i < styleClasses.Count; i++) { var styleType = styleClasses[i]; try { var type = Type.GetType("Nez.UI." + styleType, true); var styleNames = config.styles.getStyleNames(styleType); for (var j = 0; j < styleNames.Count; j++) { var style = Activator.CreateInstance(type); var styleDict = config.styles.getStyleDict(styleType, styleNames[j]); foreach (var styleConfig in styleDict) { var name = styleConfig.Key; var identifier = styleConfig.Value; // if name has 'color' in it, we are looking for a color. we check color first because some styles have things like // fontColor so we'll check for font after color. if (name.ToLower().Contains("color")) { type.GetField(name).SetValue(style, getColor(identifier)); } else if (name.ToLower().Contains("font")) { type.GetField(name).SetValue(style, contentManager.Load <BitmapFont>(identifier)); } else { // we have an IDrawable. first we'll try to find a Subtexture and if we cant find one we will see if // identifier is a color var drawable = getDrawable(identifier); if (drawable != null) { type.GetField(name).SetValue(style, drawable); } else { Debug.error("could not find a drawable or color named {0} when setting {1} on {2}", identifier, name, styleNames[j]); } } } add(styleNames[j], style, type); } } catch (Exception e) { Debug.error("Error creating style from UISkin: {0}", e); } } } }
public CharacterLoadingUtilitiy() { this.myCache = Nez.Core.content; }
/// <summary> /// Init skin for ui /// </summary> /// <param name="content">Content manager that able to load resources (Scene.Content)</param> public GameUIHelper(NezContentManager content) { _skin = new GameSkin(content); }