Esempio n. 1
0
    //光照贴图纹理
    void Lightmap()
    {
        GUILayout.Label("自 定 义 光 照 贴 图", EditorStyles.boldLabel);

        LightMap light = LightMap.unityLightMap;

        if (IsKeywordEnabled("_OHR_LIGHTMAP_UNITY"))
        {
            light = LightMap.unityLightMap;
        }
        else if (IsKeywordEnabled("_OHR_LIGHTMAP_INNER"))
        {
            light = LightMap.innerLightMap;
        }

        editor.EndAnimatedCheck();
        light = (LightMap)EditorGUILayout.EnumPopup(MakeLabel("Light Map"), light);

        if (EditorGUI.EndChangeCheck())
        {
            RecordAction("Light Map");
            SetKeyword("_OHR_LIGHTMAP_UNITY", light == LightMap.unityLightMap);
            SetKeyword("_OHR_LIGHTMAP_INNER", light == LightMap.innerLightMap);
        }

        MaterialProperty lightmap = FindProperty("_LightMap");
        Texture          tex      = lightmap.textureValue;

        EditorGUI.BeginChangeCheck();

        if (light == LightMap.innerLightMap)
        {
            editor.TexturePropertySingleLine(SetLabel(lightmap, "光照贴图,带ARBG,支持shadowmask,A通道为mask通道,如果为空,自动获取系统自带关照贴图信息"), lightmap, null);

            if (EditorGUI.EndChangeCheck())
            {
                if (tex != lightmap.textureValue)
                {
                    SetDefineInfo("_LightMap", lightmap.textureValue);
                }
                if (lightmap.textureValue == null)
                {
                    SetDefineInfo("CF_LIGHTMAP", false);
                }
                else
                {
                    SetDefineInfo("CF_LIGHTMAP", true);
                }
            }
            editor.TextureScaleOffsetProperty(lightmap);
        }
    }
Esempio n. 2
0
    public Material[] mats;     //0: air; 1: dirt; 2: grass; 3: stone;

    void Start()
    {
        levelData         = GameObject.FindGameObjectWithTag("terrain").GetComponent <loadLevel>();
        lightMap          = GameObject.FindGameObjectWithTag("terrain").GetComponent <LightMap>();
        meshRenderer      = gameObject.GetComponent <MeshRenderer>();
        boxCollider       = gameObject.GetComponent <BoxCollider2D>();
        damage            = gameObject.GetComponent <takeDamage>();
        damage.levelData  = levelData;
        damage.block      = this;
        damageOverlay     = transform.GetChild(0).GetComponent <SpriteRenderer>();;
        myShadow          = gameObject.GetComponentInChildren <GetShadow>();
        myShadow.lightMap = lightMap;
        SetupBlock();
    }
Esempio n. 3
0
    public static void RecomputeLightAtPosition(Map map, Vector3i pos)
    {
        LightMap lightmap = map.GetLightmap();
        int      oldLight = lightmap.GetLight(pos);
        int      light    = map.GetBlock(pos).GetLight();

        if (oldLight > light)
        {
            RemoveLight(map, pos);
        }
        if (light > MIN_LIGHT)
        {
            Scatter(map, pos);
        }
    }
Esempio n. 4
0
    // Update is called once per frame
    private void Start()
    {
        //lightMat = lightMesh.GetComponent<MeshRenderer>().sharedMaterial;
        if (isAPixelLight)
        {
            LightMap lightMap = GetComponent <LightMap>();
            if (lightMap != null)
            {
                lightMat = GetComponent <LightMap>().lightMapMesh.GetComponent <MeshRenderer>().sharedMaterial;
            }

            Debug.Log("Light material is: " + lightMat);
        }

        //Each light will add itself to the lights manager once it's activated
        LightsManager.lightsInScene.Add(this);
    }
Esempio n. 5
0
    private static void Scatter(Map map, List <Vector3i> list)      // рассеивание
    {
        LightMap lightmap = map.GetLightmap();

        foreach (Vector3i pos in list)
        {
            byte light = map.GetBlock(pos).GetLight();
            if (light > MIN_LIGHT)
            {
                lightmap.SetMaxLight(light, pos);
            }
        }

        for (int i = 0; i < list.Count; i++)
        {
            Vector3i pos = list[i];
            if (pos.y < 0)
            {
                continue;
            }

            BlockData block = map.GetBlock(pos);
            int       light = lightmap.GetLight(pos) - LightComputerUtils.GetLightStep(block);
            if (light <= MIN_LIGHT)
            {
                continue;
            }

            foreach (Vector3i dir in Vector3i.directions)
            {
                Vector3i nextPos = pos + dir;
                block = map.GetBlock(nextPos);
                if (block.IsAlpha() && lightmap.SetMaxLight((byte)light, nextPos))
                {
                    list.Add(nextPos);
                }
                if (!block.IsEmpty())
                {
                    LightComputerUtils.SetLightDirty(map, nextPos);
                }
            }
        }
    }
Esempio n. 6
0
        private void CreateRenderTargets(GraphicsDevice graphics)
        {
            var pp = graphics.PresentationParameters;

            currLightMapScale = GameMain.Config.LightMapScale;

            LightMap?.Dispose();
            LightMap = new RenderTarget2D(graphics,
                                          (int)(GameMain.GraphicsWidth * GameMain.Config.LightMapScale), (int)(GameMain.GraphicsHeight * GameMain.Config.LightMapScale), false,
                                          pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount,
                                          RenderTargetUsage.DiscardContents);

            SpecularMap?.Dispose();
            SpecularMap = new RenderTarget2D(graphics,
                                             (int)(GameMain.GraphicsWidth * GameMain.Config.LightMapScale), (int)(GameMain.GraphicsHeight * GameMain.Config.LightMapScale), false,
                                             pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount,
                                             RenderTargetUsage.DiscardContents);

            LosTexture?.Dispose();
            LosTexture = new RenderTarget2D(graphics, (int)(GameMain.GraphicsWidth * GameMain.Config.LightMapScale), (int)(GameMain.GraphicsHeight * GameMain.Config.LightMapScale), false, SurfaceFormat.Color, DepthFormat.None);
        }
Esempio n. 7
0
    public static IEnumerable <(Position Location, TreasureType Type)> RandomlyPlaceTreasure(
        ConnectedArea area,
        IEnumerable <Position> edge,
        LightMap floorLighting,
        LightRange lightRange,
        Random random)
    {
        var maxScore = 3 * lightRange.DarkLevels;
        var cutOff   = (int)(0.5 * maxScore);

        var scoredLocations = edge
                              .Select(p => new { Location = p, Score = area.CountAdjacentWalls(p) * -floorLighting[p] })
                              .OrderBy(scoredLocation => scoredLocation.Score)
                              .Where(scoredLocation => scoredLocation.Score >= cutOff)
                              .OrderBy(sl => random.Next())
                              .ToArray();

        var numberToTake = scoredLocations.Length / 2;

        return(scoredLocations.Take(numberToTake).Select(sl => (sl.Location, TreasureType.Medium)));
    }
Esempio n. 8
0
    public InGame(int race)
    {
        SoundManager.Stop();
        Players[0] = new PC(race);
        PlayerList.AddFirst(Players[0]);
        HUDs[0] = new HUD(Players[0], HUD.Corner.TOPLEFT);

        Map = new ObliqueMap(@"maps\testmap.xml", CastleSpire.BaseWidth, CastleSpire.BaseHeight);

        Lightmap   = new LightMap(CastleSpire.BaseWidth, CastleSpire.BaseHeight);
        FloorItems = new LinkedList <Item>();

        TotalLosOverlay  = new RenderTarget2D(Renderer.GraphicsDevice, CastleSpire.BaseWidth, CastleSpire.BaseHeight);
        LosTemp          = new Color[CastleSpire.BaseWidth * CastleSpire.BaseHeight];
        PlayerLosOverlay = new Texture2D[4];

        for (int i = 0; i != 4; i++)
        {
            PlayerLosOverlay[i] = new Texture2D(Renderer.GraphicsDevice, CastleSpire.BaseWidth, CastleSpire.BaseHeight);
        }

        L = new Light(.1f, .1f, .2f, 50, 50, 50);
        Lightmap.AddLight(L);

        Lightmap.AddLight(new Light(.1f, .0f, .0f, 300, 100, 100));
        Lightmap.AddLight(new Light(.0f, .0f, .1f, 400, 200, 100));
        Lightmap.AddLight(new Light(.0f, .1f, .0f, 500, 300, 100));
        Lightmap.AddLight(new Light(.3f, .0f, .3f, 100, 100, 50));
        Lightmap.AddLight(new Light(.3f, .3f, .0f, 200, 150, 50));
        Lightmap.AddLight(new Light(.0f, .3f, .3f, 300, 200, 50));
        Lightmap.AddLight(new Light(.5f, .5f, .5f, 300, 600, 70));
        Clock = new Clock();

        FloorItems.AddFirst(new Item(@"items\melee\axe.xml", 300, 300));

        SoundManager.Play("night.ogg", true);
    }
Esempio n. 9
0
    public InGame(int race)
    {
        SoundManager.Stop();
        Players[0] = new PC(race);
        PlayerList.AddFirst(Players[0]);
        HUDs[0] = new HUD(Players[0], HUD.Corner.TOPLEFT);

        Map = new ObliqueMap(@"maps\testmap.xml", CastleSpire.BaseWidth, CastleSpire.BaseHeight);

        Lightmap = new LightMap(CastleSpire.BaseWidth, CastleSpire.BaseHeight);
        FloorItems = new LinkedList<Item>();

        TotalLosOverlay = new RenderTarget2D(Renderer.GraphicsDevice, CastleSpire.BaseWidth, CastleSpire.BaseHeight);
        LosTemp = new Color[CastleSpire.BaseWidth * CastleSpire.BaseHeight];
        PlayerLosOverlay = new Texture2D[4];

        for (int i = 0; i != 4; i++)
        {
           PlayerLosOverlay[i] = new Texture2D(Renderer.GraphicsDevice, CastleSpire.BaseWidth, CastleSpire.BaseHeight);
        }

        L = new Light(.1f, .1f, .2f, 50, 50, 50);
        Lightmap.AddLight(L);

        Lightmap.AddLight(new Light(.1f, .0f, .0f, 300, 100, 100));
        Lightmap.AddLight(new Light(.0f, .0f, .1f, 400, 200, 100));
        Lightmap.AddLight(new Light(.0f, .1f, .0f, 500, 300, 100));
        Lightmap.AddLight(new Light(.3f, .0f, .3f, 100, 100, 50));
        Lightmap.AddLight(new Light(.3f, .3f, .0f, 200, 150, 50));
        Lightmap.AddLight(new Light(.0f, .3f, .3f, 300, 200, 50));
        Lightmap.AddLight(new Light(.5f, .5f, .5f, 300, 600, 70));
        Clock = new Clock();

        FloorItems.AddFirst(new Item(@"items\melee\axe.xml",300,300));

        SoundManager.Play("night.ogg", true);
    }
Esempio n. 10
0
        public static void Serialize(this SerializingContainer2 sc, ref LightMap lmap)
        {
            if (sc.IsLoading)
            {
                var type = (ELightMapType)sc.ms.ReadInt32();
                switch (type)
                {
                case ELightMapType.LMT_None:
                    lmap = new LightMap();
                    break;

                case ELightMapType.LMT_1D:
                    lmap = new LightMap_1D();
                    break;

                case ELightMapType.LMT_2D:
                    lmap = new LightMap_2D();
                    break;

                case ELightMapType.LMT_3:
                    lmap = new LightMap_3();
                    break;

                case ELightMapType.LMT_4:
                case ELightMapType.LMT_6:
                    lmap = new LightMap_4or6();
                    break;

                case ELightMapType.LMT_5:
                    lmap = new LightMap_5();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                lmap.LightMapType = type;
            }
            else
            {
                sc.ms.WriteInt32((int)lmap.LightMapType);
            }

            switch (lmap.LightMapType)
            {
            case ELightMapType.LMT_None:
                break;

            case ELightMapType.LMT_1D:
                sc.Serialize((LightMap_1D)lmap);
                break;

            case ELightMapType.LMT_2D:
                sc.Serialize((LightMap_2D)lmap);
                break;

            case ELightMapType.LMT_3:
                sc.Serialize((LightMap_3)lmap);
                break;

            case ELightMapType.LMT_4:
            case ELightMapType.LMT_6:
                sc.Serialize((LightMap_4or6)lmap);
                break;

            case ELightMapType.LMT_5:
                sc.Serialize((LightMap_5)lmap);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Esempio n. 11
0
        private static void StartGame()
        {
            //Dungeon dungeon = new Dungeon();
            // dungeon.Enter();

            MessageBus mainBus = new MessageBus();

            Timeline timeline = new Timeline();
            MapInfo  mapInfo  = new MapGenerator(timeline, mainBus).Generate(120, 40, "helloseed");
            Map      map      = mapInfo.Map;
            LightMap lightMap = mapInfo.LightMap;


            Spawner spawner = new Spawner(map);

            mainBus.RegisterSubscriber(spawner);

            JoystickConfig joystickConfig = new JoystickConfig
            {
                DownCode  = Terminal.TK_S,
                LeftCode  = Terminal.TK_A,
                RightCode = Terminal.TK_D,
                UpCode    = Terminal.TK_W,
                MapUp     = Terminal.TK_UP,
                MapDown   = Terminal.TK_DOWN,
                MapRight  = Terminal.TK_RIGHT,
                MapLeft   = Terminal.TK_LEFT,
                Inventory = Terminal.TK_I,
                Equip     = Terminal.TK_E
            };

            //lightMap.AddLight(new Light(Color.AntiqueWhite, new Coord(1, 1), 15, 5));
            lightMap.AddLight(new Light(Color.Wheat, new Coord(8, 8), 20, 10000));

            // Creating Player
            GameObject player = new UpdatingGameObject(new Coord(20, 20), Layers.Main, null, timeline);

            Being playerBeing = new Being(new SelectedAttributes(new AttributeSet(10, 10, 10, 10, 10)), Alignment.PlayerAlignment, new EquipmentSlotSet(), 5, "You");

            playerBeing.Equipment.Equip(new MeleeWeapon(new Damage(10)), EquipmentSlot.RightHandEquip);

            UserControlAgent control = new UserControlAgent(joystickConfig);

            mainBus.RegisterSubscriber <MouseMoveEvent>(control);
            mainBus.RegisterSubscriber <KeyEvent>(control);

            Actor playerActor = new Actor(playerBeing, control, mainBus);

            player.AddComponent(playerActor);
            player.AddComponent(new GlyphComponent(new Glyph(Characters.AT, Color.Aqua)));
            player.AddComponent(new LightSourceComponent(lightMap, new Light(Color.Aqua, Coord.NONE, 4, 8)));
            player.AddComponent(new FOVExplorerComponent());
            player.AddComponent(new NameComponent(new Title("the", "Hero")));

            EffectTargetComponent playerEffectTarget = new EffectTargetComponent();

            playerEffectTarget.EffectTarget.AddEffectReceiver(playerActor);
            player.AddComponent(playerEffectTarget);

            playerEffectTarget.EffectTarget.ApplyEffect(new StaminaEffect(1, EffectKind.Repeating, new EventTimerTiming(25, 25)));

            Logger logger = new Logger();

            mainBus.RegisterSubscriber(logger);

            MapViewPane viewPane = new MapViewPane(mainBus, joystickConfig, new InventoryDisplayPane(playerBeing.Equipment, playerBeing.Inventory, joystickConfig, mainBus));

            viewPane.Map      = map;
            viewPane.LightMap = lightMap;

            map.ObjectRemoved += (sender, eventArgs) => viewPane.SetDirty();
            map.ObjectMoved   += (sender, eventArgs) => viewPane.SetDirty();
            map.ObjectAdded   += (sender, eventArgs) => viewPane.SetDirty();


            TextPane descriptionPane = new TextPane("TEST TEXT");

            Describer describer = new Describer(descriptionPane);

            describer.Map = map;

            mainBus.RegisterSubscriber(describer);

            LogPane logPane = new LogPane(logger);

            StackPane mapAndConsole = new StackPane(StackPane.StackDirection.Vertical);

            mapAndConsole.AddChild(descriptionPane, 1);
            mapAndConsole.AddChild(viewPane, 5);
            mapAndConsole.AddChild(logPane, 1);

            StackPane statusBars = new StackPane(StackPane.StackDirection.Vertical);

            statusBars.AddChild(new FillBarPane(playerBeing.Health, "Health", Color.Red, Color.DarkRed), 1);
            statusBars.AddChild(new FillBarPane(playerBeing.Mana, "Mana", Color.Aqua, Color.DarkBlue), 1);
            statusBars.AddChild(new FillBarPane(playerBeing.Stamina, "Stamina", Color.Yellow, Color.DarkGoldenrod), 1);

            StackPane root = new StackPane(StackPane.StackDirection.Horizontal);

            root.AddChild(mapAndConsole, 4);
            root.AddChild(statusBars, 1);

            Window rootWindow = new Window(root, new Rectangle(0, 0, 160, 50), 0);

            BearTermRenderer renderer = new BearTermRenderer(rootWindow, "window.title='Spell Sword'; window.size=160x50; window.resizeable=true; input.filter=[keyboard+, mouse+, arrows+]");

            mainBus.RegisterSubscriber <ParticleEvent>(renderer);
            mainBus.RegisterSubscriber <WindowEvent>(renderer);

            //WindowRouter windowRouter = new WindowRouter();
            //windowRouter.Handle(WindowEvent.Open(root, new Rectangle(0, 0, 160, 50)));
            //mainBus.RegisterSubscriber(windowRouter);

            GameControlConsumer gameControlConsumer = new GameControlConsumer(joystickConfig, mainBus, viewPane);

            BearTermInputRouter inputRouter = new BearTermInputRouter(gameControlConsumer);

            mainBus.RegisterSubscriber(inputRouter);
            inputRouter.Handle(WindowEvent.Open(root, new Rectangle(0, 0, 160, 50)));


            GoalMapStore goalMapStore = new GoalMapStore(map);

            for (int i = 1; i < 5; i++)
            {
                //GameObject goblin = TestUtil.CreateGoblin((5 + i, 5 + i % 2 + 1), playerActor, timeline, goalMapStore, mainBus);
                //map.AddEntity(goblin);
            }

            map.AddEntity(player);

            Terminal.Refresh();


            int lastFrame = Environment.TickCount;

            while (true)
            {
                inputRouter.HandleInput();
                //control.VisualizeAim(playerActor);

                if (!control.WaitingForInput)
                {
                    timeline.Advance(1);
                    goalMapStore.UpdateMaps();
                }

                if (Environment.TickCount - lastFrame > 20)
                {
                    renderer.Refresh();
                    lastFrame = Environment.TickCount;
                }
            }
        }
Esempio n. 12
0
    void Update()
    {
        if (isAPixelLight)
        {
            if (lightMat == null)
            {
                LightMap lightMap = GetComponent <LightMap>();
                if (lightMap != null)
                {
                    lightMat = GetComponent <LightMap>().lightMapMesh.GetComponent <MeshRenderer>().sharedMaterial;
                }
                Debug.Log("Light material is: " + lightMat);
            }
        }

        if (lightIsActive && isAPixelLight)
        {
            if (gameObject.transform.parent != null)
            {
                MovementScript2D player = transform.GetComponentInParent <MovementScript2D>();
                if (player != null)
                {
                    Vector3 playerAngles = player.transform.rotation.eulerAngles;
                    if (gameObject.transform.parent.localScale.x == -1)
                    {
                        //gameObject.transform.rotation = Quaternion.Euler(0, 0, -180);
                        Rotate(Quaternion.Euler(playerAngles.x, playerAngles.y, playerAngles.z - 180));
                    }
                    else
                    {
                        //gameObject.transform.rotation = Quaternion.Euler(0, 0, 0);
                        Rotate(Quaternion.Euler(playerAngles.x, playerAngles.y, playerAngles.z));
                    }
                }
            }
            //set the right vector according to the angle provided

            //First, get the right guy's direction
            //transform.GetChild(0).RotateAround(transform.position, transform.up, rightAngle);

            perpendicularLeftVector  = Quaternion.AngleAxis(angle - 90, transform.forward) * transform.right;
            perpendicularRightVector = Quaternion.AngleAxis(90 - angle, transform.forward) * transform.right;

            perpendicularLeftFogVector  = Quaternion.AngleAxis(angle + fog - 90, transform.forward) * transform.right;
            perpendicularRightFogVector = Quaternion.AngleAxis(90 - angle + (-fog), transform.forward) * transform.right;


            actualRightVector = Quaternion.AngleAxis(-angle, transform.forward) * transform.right;
            actualLeftVector  = Quaternion.AngleAxis(angle, transform.forward) * transform.right;


            actualLeftFogVector  = Quaternion.AngleAxis(angle + fog, transform.forward) * transform.right;
            actualRightFogVector = Quaternion.AngleAxis(-angle + (-fog), transform.forward) * transform.right;

            //Debug.DrawLine(gameObject.transform.position, perpendicularRightVector);
            //Debug.DrawLine(gameObject.transform.position, perpendicularLeftVector);
            //
            Debug.DrawLine(gameObject.transform.position, actualLeftVector + gameObject.transform.position);
            //Debug.DrawLine(gameObject.transform.position, actualRightVector + gameObject.transform.position);

            Debug.DrawLine(gameObject.transform.position, gameObject.transform.position + actualLeftFogVector);
            //Debug.DrawLine(gameObject.transform.position, gameObject.transform.position + actualRightFogVector);
            //Debug.DrawLine(gameObject.transform.position, perpendicularRightFogVector);


            float rightVectorAngle = Vector3.Angle(transform.forward, perpendicularRightFogVector);
            float leftVectorAngle  = Vector3.Angle(perpendicularLeftFogVector, transform.forward);
            //Debug.Log("right vector angle is: " + rightVectorAngle);

            lightAngle = (angle + fog);

            //setting the properties for the mesh

            lightMat.SetColor("_Color", lightColor);
            lightMat.SetVector("_LightPosition", transform.position);
            lightMat.SetVector("_LightDirection", transform.forward);

            lightMat.SetFloat("_Distance", distance);
            lightMat.SetFloat("_NoFadeDistance", noFadeDistance);

            lightMat.SetFloat("_LightMixtureAdjustmentController", lightMixtureAdjustmentController);


            lightMat.SetVector("_PerpendicularRightVector", perpendicularRightVector);
            lightMat.SetVector("_PerpendicularLeftVector", perpendicularLeftVector);

            lightMat.SetVector("_PerpendiculatRightFogVector", perpendicularRightFogVector);
            lightMat.SetVector("_PerpendiculatLeftFogVector", perpendicularLeftFogVector);

            lightMat.SetVector("_ActualRightVector", actualRightVector);
            lightMat.SetVector("_ActualLeftVector", actualLeftVector);
            lightMat.SetVector("_ActualRightFogVector", actualRightFogVector);
            lightMat.SetVector("_ActualLeftFogVector", actualLeftFogVector);
        }

        //Cast Ray to the light detector. If light hits the light detector, add the light to the list lightsInContact
        if (castRay && Application.isPlaying)
        {
            RaycastHit2D hit;
            hit = Physics2D.Raycast(gameObject.transform.position, gameObject.transform.right, (Mathf.Clamp(distance, 0, Mathf.Infinity)), whatShouldIDetect);
            if (hit.collider != null)
            {
                hit.collider.GetComponent <LightDetector>().lightsInContact.Add(this.gameObject);
            }
        }
    }
Esempio n. 13
0
        public void Draw(
            Camera camera,
            IGameWorld gameWorld,
            IEntitySet entitySet,
            IEntity myPlayer,
            LightMap lightMap)
        {
            if (_renderTarget.Width != Window.WindowWidth)
            {
                _renderTarget = new RenderTarget2D(
                    Window.GraphicsDeviceManager.GraphicsDevice,
                    Window.WindowWidth, Window.WindowHeight);
            }

            if (lightMap.ChangedSinceLastGet)
            {
                _lightMapRenderer.RenderToRenderTarget(
                    camera,
                    myPlayer.GameArea,
                    lightMap);
            }

            Window.GraphicsDeviceManager.GraphicsDevice.SetRenderTarget(_renderTarget);

            GraphicsUtils.Instance.Begin();
            GraphicsUtils.Instance.SpriteBatch.Draw(ContentChest.Background, new Rectangle(0, 0, Window.WindowWidth, Window.WindowHeight), Color.White);
            GraphicsUtils.Instance.End();

            GraphicsUtils.Instance.Begin(camera.GetMatrix());
            _worldRenderer.DrawWorldObjects(gameWorld.GameAreas[0], camera);
            _playerRenderer.DrawPlayers(entitySet.GetAll());

            foreach (var entity in gameWorld.GameAreas[0].GetItems())
            {
                if (!_updateResolver.ShouldUpdate(entity))
                {
                    continue;
                }
                if (!(entity is ItemDrop item))
                {
                    continue;
                }
                GraphicsUtils.Instance.SpriteBatch.Draw(ContentChest.ItemTextures[item.Item.ItemId],
                                                        new Vector2(item.X, item.Y), Color.White);
            }

            _worldRenderer.Draw(gameWorld.GameAreas[0], camera);
            GraphicsUtils.Instance.End();

            GraphicsUtils.Instance.SpriteBatch.Begin(
                SpriteSortMode.Deferred,
                null,                // No blending
                null,                // Point clamp, so we get sexy pixel perfect resizing
                null,                // We don't care about this. Tbh, I don't even understand it.
                null,                // I don't even know what this it.
                null,                // We can choose to flip textures as an example, but we dont, so null it.
                camera.GetMatrix()); // Window viewport, for nice resizing.
            _lightMapRenderer?.Draw(camera, myPlayer, gameWorld);
            GraphicsUtils.Instance.End();

            Window.GraphicsDeviceManager.GraphicsDevice.SetRenderTarget(null);

            GraphicsUtils.Instance.SpriteBatch.Begin();
            GraphicsUtils.Instance.SpriteBatch.Draw(_renderTarget,
                                                    new Rectangle(0, 0, Window.WindowWidth, Window.WindowHeight), Color.White);
            GraphicsUtils.Instance.End();
        }
Esempio n. 14
0
 void Start()
 {
     levelLighting = GameObject.Find("Terrain").GetComponent <LightMap>();
     levelLighting.lights.Add(this);
 }
Esempio n. 15
0
    static (ImmutableArray <MapSquare>, ImmutableArray <Sector>, ImmutableArray <Tile>) CreateGeometry(
        Size size,
        ConnectedArea cave,
        CellBoard alternateFloor,
        CellBoard alternateCeiling,
        LightMap floorLight,
        LightMap ceilingLight,
        TextureQueue textureQueue,
        string texturePrefix)
    {
        var planeMap = new Canvas(size);

        double minLight  = 0.2;
        double darkStep  = (1 - minLight) / ceilingLight.Range.DarkLevels;
        double maxLight  = 1.1;
        double lightStep = (maxLight - 1) / ceilingLight.Range.LightLevels;


        double GetAlpha(int light) =>
        light switch
        {
            0 => 0,
            int pos when pos > 0 => pos * lightStep,
            int neg when neg < 0 => - neg * darkStep,
            _ => throw new InvalidOperationException("Impossible")
        };


        string GetTextureName(Corners corners, int light, bool isEastWest = false)
        {
            string name = $"t{(int)corners:D2}{light:+#;-#;#}{(isEastWest ? "dark" : "")}";

            var patches = ImmutableArray.CreateBuilder <Patch>();

            if (light > 0)
            {
                patches.Add(
                    new Patch(
                        $"{texturePrefix}{(int)corners:D2}",
                        0,
                        0,
                        Blend: new ColorBlend("FFFFFF", GetAlpha(light))));
            }
            else if (light < 0)
            {
                patches.Add(
                    new Patch(
                        $"{texturePrefix}{(int)corners:D2}",
                        0,
                        0,
                        Blend: new ColorBlend("000000", GetAlpha(light))));
            }
            else
            {
                patches.Add(
                    new Patch(
                        $"{texturePrefix}{(int)corners:D2}",
                        0,
                        0));
            }

            if (isEastWest)
            {
                patches.Add(
                    new Patch(
                        $"{texturePrefix}{(int)corners:D2}",
                        0,
                        0,
                        Blend: new ColorBlend("000000"),
                        Style: RenderStyle.Translucent,
                        Alpha: 0.075));
            }

            textureQueue.Add(new CompositeTexture(name, 256, 256, patches.ToImmutable(), XScale: 4, YScale: 4));
            return(name);
        }

        Corners GetCorners(CellBoard board, Position pos) => Corner.CreateFromUpperLeft(
            upperLeft: pos, on: p => board[p] == CellType.Dead);

        Corners GetSideCorners(Position left, Position right) => Corner.Create(
            topLeft: alternateCeiling[left] == CellType.Dead,
            topRight: alternateCeiling[right] == CellType.Dead,
            bottomLeft: alternateFloor[left] == CellType.Dead,
            bottomRight: alternateFloor[right] == CellType.Dead
            );

        int GetSideLight(Position p) => (ceilingLight[p] + floorLight[p]) / 2;

        var sectorSequence = new ModelSequence <SectorDescription, Sector>(description =>
                                                                           new Sector(
                                                                               TextureCeiling: GetTextureName(description.Ceiling, description.CeilingLight),
                                                                               TextureFloor: GetTextureName(description.Floor, description.FloorLight)));
        var tileSequence = new ModelSequence <TileDescription, Tile>(description =>
                                                                     new Tile(
                                                                         TextureEast: GetTextureName(description.EastCorners, description.EastLight, isEastWest: true),
                                                                         TextureNorth: GetTextureName(description.NorthCorners, description.NorthLight),
                                                                         TextureWest: GetTextureName(description.WestCorners, description.WestLight, isEastWest: true),
                                                                         TextureSouth: GetTextureName(description.SouthCorners, description.SouthLight),
                                                                         TextureOverhead: GetTextureName(description.FloorCorners, 0)));

        for (int y = 0; y < size.Height; y++)
        {
            for (int x = 0; x < size.Width; x++)
            {
                var pos = new Position(x, y);

                int tileId = -1;
                if (!cave.Contains(pos))
                {
                    tileId = tileSequence.GetIndex(new TileDescription(
                                                       NorthCorners: GetSideCorners(left: pos + Offset.Right, right: pos),
                                                       EastCorners: GetSideCorners(left: pos + Offset.DownAndRight, right: pos + Offset.Right),
                                                       SouthCorners: GetSideCorners(left: pos + Offset.Down, right: pos + Offset.DownAndRight),
                                                       WestCorners: GetSideCorners(left: pos, right: pos + Offset.Down),
                                                       FloorCorners: GetCorners(alternateFloor, pos),
                                                       NorthLight: GetSideLight(pos + Offset.Up),
                                                       EastLight: GetSideLight(pos + Offset.Right),
                                                       SouthLight: GetSideLight(pos + Offset.Down),
                                                       WestLight: GetSideLight(pos + Offset.Left)));
                }

                int sectorId = sectorSequence.GetIndex(new SectorDescription(
                                                           Floor: GetCorners(alternateFloor, pos),
                                                           Ceiling: GetCorners(alternateCeiling, pos),
                                                           FloorLight: floorLight[pos],
                                                           CeilingLight: ceilingLight[pos]));

                planeMap.Set(x, y,
                             tile: tileId,
                             sector: sectorId,
                             zone: 0);
            }
        }

        return(
            planeMap.ToPlaneMap(),
            sectorSequence.GetDefinitions().ToImmutableArray(),
            tileSequence.GetDefinitions().ToImmutableArray());
    }
Esempio n. 16
0
 public MapInfo(Map map, LightMap lightMap)
 {
     Map      = map;
     LightMap = lightMap;
 }