Пример #1
0
        private static RgbaImage TextureDefinitionToImage(TextureDefinition definition)
        {
            RgbaImage newImage = new RgbaImage(definition.Dimension)
            {
                Namespace = definition.Namespace,
                Offset    = definition.Offset
            };

            foreach (TextureDefinitionPatch patch in definition.Patches)
            {
                if (TryGetOrReadImage(patch.Name, patch.Namespace, out RgbaImage image))
                {
                    Vec2I position = patch.Origin;
                    if (patch.UseOffsets)
                    {
                        position += image.Offset;
                    }

                    // TODO: Handle the other fields on the patch (ex: flipping, rotation).

                    newImage.DrawOntoThis(image, position);
                }
                else
                {
                    throw new Exception($"Cannot find image patch {patch.Name} in texture definition {definition.Name}");
                }
            }

            return(newImage);
        }
 public PathStep(Vec2I Position, int TravelCost, int Heuristic)
 {
     position   = Position;
     travelCost = TravelCost;
     heuristic  = Heuristic;
     fullCost   = travelCost + heuristic;
 }
Пример #3
0
 public Breath(Vec2I Position, int Direction, int Distance, int Steps)
 {
     position  = Position;
     direction = Direction;
     distance  = Distance;
     steps     = Steps;
 }
Пример #4
0
    private void Init()
    {
        gridPos = TheGrid.GridPosition(transform.position);
        size    = TheGrid.size; //each room spans the entire level at the moment
        //later on we can optimize this so level designer can restrict the area

        if (!TheGrid.Valid(gridPos))
        {
            Debug.Log("Room \"" + gameObject.name + "\" out of grid! (" + gridPos + ")");
            enabled = false;
            return;
        }

        HeatmapNode h = Heatmap.GetNode(gridPos);

        if (h == null)
        {
            Debug.Log("Room \"" + gameObject.name + "\" does not reside in heatmap! (" + gridPos + ")");
            enabled = false;
            return;
        }

        parent     = new Vec2I[size.x, size.y];
        travelCost = new int[size.x, size.y];
        steps      = new int[size.x, size.y];
        exist      = new bool[size.x, size.y];
    }
Пример #5
0
        private void OnConsoleVideoMode(string arguments)
        {
            if (!string.IsNullOrEmpty(arguments))
            {
                try
                {
                    Vec2I mode = Vec2I.Parse(arguments);

                    if (EngineApp.Instance.FullScreen && !DisplaySettings.VideoModeExists(mode))
                    {
                        string text = string.Format("Cannot change screen resolution to \"{0}x{1}\". " +
                                                    "This resolution is not supported by the system.", mode.X, mode.Y);
                        Log.Warning(text);
                        return;
                    }

                    EngineApp.Instance.VideoMode = mode;
                }
                catch (Exception ex)
                {
                    Log.Warning(ex.Message);
                }
            }
            else
            {
                Print(string.Format("Value: \"{0}\"", EngineApp.Instance.VideoMode));
            }
        }
        void FormClosed(object sender, FormClosedEventArgs e)
        {
            CollectionEditor.CollectionForm form = (CollectionEditor.CollectionForm)sender;

            //save window settings
            lastWindowPosition = new Vec2I(form.Location.X, form.Location.Y);
            lastWindowSize     = new Vec2I(form.Size.Width, form.Size.Height);

            if (form.DialogResult == DialogResult.Cancel)
            {
                //restore properties
                foreach (KeyValuePair <object, List <Pair <PropertyInfo, object> > > keyValuePair in propertyCopies)
                {
                    object listItem = keyValuePair.Key;
                    List <Pair <PropertyInfo, object> > pairList = keyValuePair.Value;

                    foreach (Pair <PropertyInfo, object> pair in pairList)
                    {
                        PropertyInfo property = pair.First;
                        object       value    = pair.Second;
                        property.SetValue(listItem, value, null);
                    }
                }
            }
        }
Пример #7
0
 /// <summary>
 /// Creates a TextureX patch from the data provided.
 /// </summary>
 /// <param name="offset">The offset from the top left.</param>
 /// <param name="patchIndex">The PNames index.</param>
 /// <param name="stepDirection">An unused value.</param>
 /// <param name="colormap">Another unused value.</param>
 public TextureXPatch(Vec2I offset, short patchIndex, short stepDirection, short colormap)
 {
     Offset        = offset;
     PatchIndex    = patchIndex;
     StepDirection = stepDirection;
     Colormap      = colormap;
 }
Пример #8
0
        public static CelestialInfo FromStream(IStarboundStream stream)
        {
            CelestialInfo cInfo = new CelestialInfo();

            cInfo.planetOrbitalLevels    = stream.ReadInt32();
            cInfo.satelliteOrbitalLevels = stream.ReadInt32();
            cInfo.ChunkSize    = stream.ReadInt32();
            cInfo.xyCoordRange = Vec2I.FromStream(stream);
            cInfo.zCoordRange  = stream.ReadToEnd();
            //  cInfo.zCoordRange = Vec2I.FromStream(stream); //doc lies???
            // cInfo.zCoordRange = stream.ReadInt32();

            /*
             * cInfo.OrbitalLevels = stream.ReadInt32();
             * cInfo.ChunkSize = stream.ReadInt32();
             * cInfo.XyCoordinateMin = stream.ReadInt32();
             * cInfo.XyCoordinateMax = stream.ReadInt32();
             * cInfo.ZCoordinateMin = stream.ReadInt32();
             * cInfo.ZCoordinateMax = stream.ReadInt32();
             *
             * ulong length = stream.ReadVLQ();
             *
             * for (ulong i = 0; i < length; i++)
             * {
             *  cInfo.Sectors.Add(Sector.FromStream(stream));
             * }
             */
            return(cInfo);
        }
Пример #9
0
    private void Awake()
    {
        Messaging.DevTools.VisualizeHeatmap.AddListener(() =>
        {
            Vec2I campos = TheGrid.GridPosition(Camera.main.transform.position);

            for (int x = campos.x - (int)Options.ScreenDistance.x; x <= campos.x + (int)Options.ScreenDistance.x; x++)
            {
                for (int y = campos.y - (int)Options.ScreenDistance.y; y <= campos.y + (int)Options.ScreenDistance.y; y++)
                {
                    HeatmapNode node = Heatmap.GetNode(new Vec2I(x, y));
                    if (node != null)
                    {
                        VisualizeNode(Heatmap.Nodes[x, y]);
                        VisualizeConnections(Heatmap.Nodes[x, y]);
                    }
                }
            }
        });

        Messaging.DevTools.ClearVisualizations.AddListener(() =>
        {
            foreach (GameObject visualized in Visualized)
            {
                Destroy(visualized);
            }

            Visualized.Clear();
        });
    }
Пример #10
0
        //
        protected override void OnCreateTexture( string definitionName, ref Vec2I size, ref PixelFormat format )
        {
            base.OnCreateTexture( definitionName, ref size, ref format );

            if( definitionName == "scene" || definitionName == "temp" )
                size = Owner.DimensionsInPixels.Size / 2;
        }
Пример #11
0
 public Breath(Vec2I GridPos, Vec2I Parent, int TravelCost, int Steps)
 {
     gridPos    = GridPos;
     parent     = Parent;
     travelCost = TravelCost;
     steps      = Steps;
 }
Пример #12
0
        protected override void OnCreateTexture(string definitionName, ref Vec2I size, ref PixelFormat format)
        {
            base.OnCreateTexture(definitionName, ref size, ref format);

            if (definitionName == "rt_downscale" || definitionName == "rt_blurHorizontal" ||
                definitionName == "rt_blurVertical")
            {
                float divisor = 8.0f - blurTextureResolution;
                if (divisor <= 1)
                {
                    divisor = 1;
                }
                Vec2 sizeFloat = Owner.DimensionsInPixels.Size.ToVec2() / divisor;
                size = new Vec2I((int)sizeFloat.X, (int)sizeFloat.Y);
                if (size.X < 1)
                {
                    size.X = 1;
                }
                if (size.Y < 1)
                {
                    size.Y = 1;
                }

                downscaleTextureSize = size;
            }
        }
Пример #13
0
    public BooleanBox(Vec2I Origo, Vec2I Size)
    {
        origo = Origo;
        size  = Size;

        data = new bool[size.x, size.y];
    }
Пример #14
0
    public List <Breath> GetNearbyBreaths(Vec2I pos, int extend)
    {
        List <Breath> list = new List <Breath>();

        if (extend == 0)
        {
            Breath b = GetBreath(pos);
            if (b != null)
            {
                list.Add(b);
            }

            return(list);
        }

        foreach (Vec2I n in Vec2I.Neighbors(pos + new Vec2I(maxDistance, maxDistance)))
        {
            if (Valid(n))
            {
                if (exist[n.x, n.y])
                {
                    list.Add(new Breath(n, parent[n.x, n.y], travelCost[n.x, n.y], steps[n.x, n.y]));
                }
            }
        }

        return(list);
    }
Пример #15
0
    public static Vec2I[] CartesianLine(int x0, int y0, int x1, int y1)
    {
        bool steep = Mathf.Abs(y1 - y0) > Mathf.Abs(x1 - x0);

        if (steep)
        {
            Swap(ref x0, ref y0);
            Swap(ref x1, ref y1);
        }

        bool flip = false;

        if (x0 > x1)
        {
            Swap(ref x0, ref x1);
            Swap(ref y0, ref y1);
            flip = true;
        }

        int dx    = x1 - x0;
        int dy    = Mathf.Abs(y1 - y0);
        int error = dx / 2;
        int ystep = (y0 < y1) ? 1 : -1;
        int y     = y0;

        Vec2I[] array = new Vec2I[x1 - x0 + 1];

        if (flip)
        {
            int i = array.Length - 1;
            for (int x = x0; x <= x1; x++)
            {
                array[i--] = steep ? new Vec2I(y, x) : new Vec2I(x, y);

                error = error - dy;
                if (error < 0)
                {
                    y     += ystep;
                    error += dx;
                }
            }
        }
        else
        {
            int i = 0;
            for (int x = x0; x <= x1; x++)
            {
                array[i++] = steep ? new Vec2I(y, x) : new Vec2I(x, y);

                error = error - dy;
                if (error < 0)
                {
                    y     += ystep;
                    error += dx;
                }
            }
        }

        return(array);
    }
Пример #16
0
    protected override void OnAwake()
    {
        base.OnAwake();

        for (int r = 0; r < Room.Rooms.Length; r++)
        {
            if (Room.Rooms[r].name == TargetRoomName)
            {
                targetRoom = r;
                break;
            }
        }

        Messaging.Mission.MissionTrigger.AddListener((s) =>
        {
            if (s != MissionTrigger)
            {
                return;
            }

            activated = true;
        });

        /*for (int r = 0; r < Room.Rooms.Length; r++)
         *  if (Room.Rooms[r].ClosestNeighborTowards[targetRoom] != -1)
         *      Debug.Log("Room \"" + Room.Rooms[r].name + "\" closest neighbor towards targetroom is \"" + Room.Rooms[Room.Rooms[r].ClosestNeighborTowards[targetRoom]].name + "\"");*/

        character.OnInputRequest = StandAround;

        Messaging.Player.PlayerGridPosition.AddListener((p) =>
        {
            playerGridPos = p;
        });
    }
            ///////////////

            private bool CreateRenderTexture()
            {
                Vec2I size = new Vec2I(512, 256);

                string textureName = TextureManager.Instance.GetUniqueName("RenderToTextureExample");
                texture = TextureManager.Instance.Create(textureName, Texture.Type.Type2D, size, 1, 0,
                    PixelFormat.R8G8B8, Texture.Usage.RenderTarget);
                if (texture == null)
                    return false;

                renderTexture = texture.GetBuffer().GetRenderTarget();
                //you can update render texture manually by means renderTexture.Update() method. For this task set AutoUpdate = false;
                renderTexture.AutoUpdate = true;

                //create camera
                string cameraName = SceneManager.Instance.GetUniqueCameraName("RenderToTextureExample");
                camera = SceneManager.Instance.CreateCamera(cameraName);
                camera.Purpose = Camera.Purposes.Special;
                camera.AllowMapCompositorManager = false;

                //add viewport
                viewport = renderTexture.AddViewport(camera);
                viewport.BackgroundColor = new ColorValue(0, 0, 0, 1);
                viewport.ShadowsEnabled = false;
                viewport.MaterialScheme = "";

                //add listener
                renderTargetListener = new SceneRenderTargetListener(this);
                renderTexture.AddListener(renderTargetListener);

                return true;
            }
Пример #18
0
        protected override void OnCreateTexture(string definitionName, ref Vec2I size, ref PixelFormat format)
        {
            base.OnCreateTexture(definitionName, ref size, ref format);

            //if (definitionName == "scene" || definitionName == "temp")
            //    size = Owner.DimensionsInPixels.Size / 2;
        }
Пример #19
0
        public static Optional <TextureXImage> From(ByteReader reader)
        {
            try
            {
                UpperString   name            = reader.StringWithoutNulls(8);
                TextureXFlags flags           = (TextureXFlags)reader.UShort();
                Vector2       scale           = new Vector2(reader.Byte(), reader.Byte());
                Dimension     dimension       = new Dimension(reader.Short(), reader.Short());
                int           columnDirectory = reader.Int();
                int           patchCount      = reader.Short();

                List <TextureXPatch> patches = Range(patchCount).Map(i =>
                {
                    Vec2I offset        = new Vec2I(reader.Short(), reader.Short());
                    short patchIndex    = reader.Short();
                    short stepDirection = reader.Short();
                    short colormap      = reader.Short();
                    return(new TextureXPatch(offset, patchIndex, stepDirection, colormap));
                }).ToList();

                return(new TextureXImage(name, flags, scale, dimension, columnDirectory, patches));
            }
            catch
            {
                return(Empty);
            }
        }
Пример #20
0
 public override void Read(IStarboundStream stream)
 {
     OutputConnectorLocation = Vec2I.FromStream(stream);
     OutputConnectorLocation = Vec2I.FromStream(stream);
     InputObjectLocation     = Vec2I.FromStream(stream);
     InputConnectorLocation  = Vec2I.FromStream(stream);
 }
        protected override void OnMaterialRender(uint passId, Material material, ref bool skipPass)
        {
            base.OnMaterialRender(passId, material, ref skipPass);

            if (passId == 700 || passId == 701)
            {
                bool horizontal = passId == 700;

                Vec2[] sampleOffsets = new Vec2[15];
                Vec4[] sampleWeights = new Vec4[15];

                // calculate gaussian texture offsets & weights
                Vec2I textureSize = Owner.DimensionsInPixels.Size;
                float texelSize   = 1.0f / (float)(horizontal ? textureSize.X : textureSize.Y);

                texelSize *= fuzziness;

                // central sample, no offset
                sampleOffsets[0] = Vec2.Zero;
                {
                    float distribution = GaussianDistribution(0, 0, 3);
                    sampleWeights[0] = new Vec4(distribution, distribution, distribution, 0);
                }

                // 'pre' samples
                for (int n = 1; n < 8; n++)
                {
                    float distribution = GaussianDistribution(n, 0, 3);
                    sampleWeights[n] = new Vec4(distribution, distribution, distribution, 1);

                    if (horizontal)
                    {
                        sampleOffsets[n] = new Vec2((float)n * texelSize, 0);
                    }
                    else
                    {
                        sampleOffsets[n] = new Vec2(0, (float)n * texelSize);
                    }
                }
                // 'post' samples
                for (int n = 8; n < 15; n++)
                {
                    sampleWeights[n] = sampleWeights[n - 7];
                    sampleOffsets[n] = -sampleOffsets[n - 7];
                }

                //convert to Vec4 array
                Vec4[] vec4Offsets = new Vec4[15];
                for (int n = 0; n < 15; n++)
                {
                    Vec2 offset = sampleOffsets[n];
                    vec4Offsets[n] = new Vec4(offset.X, offset.Y, 0, 0);
                }

                GpuProgramParameters parameters = material.GetBestTechnique().
                                                  Passes[0].FragmentProgramParameters;
                parameters.SetNamedConstant("sampleOffsets", vec4Offsets);
                parameters.SetNamedConstant("sampleWeights", sampleWeights);
            }
        }
    private bool MoveTowardsBreath()
    {
        Breath b = GameManager.Instance.Player[0].playerBreath.GetBreath(owner.cell);

        if (b == null)
        {
            return(false);
        }
        if (b.direction == 0)
        {
            return(false);
        }

        Vec2I d      = Vec2I.directions[b.direction];
        Vec2I target = owner.cell + d;

        if (AI.GetHeat(target).x >= 1f)
        {
            return(false);
        }

        if (AI.HasLedge(owner.cell, target))
        {
            return(false);
        }

        wantDirection = new Vector3(d.x, 0, d.y).normalized;
        wantMove      = true;

        return(true);
    }
Пример #23
0
        void CreateBrowser()
        {
            if (!isCefRuntimeInitialized)
            {
                InitializeCefRuntime();
            }

            if (isCefRuntimeInitialized)
            {
                this.viewSize = GetNeededSize();

                var windowInfo = CefWindowInfo.Create();
                windowInfo.SetAsWindowless(IntPtr.Zero, false);

                var client = new WebClient(this);

                var settings = new CefBrowserSettings
                {
                    // AuthorAndUserStylesDisabled = false,
                };

                CefBrowserHost.CreateBrowser(windowInfo, client, settings,
                                             !string.IsNullOrEmpty(StartURL) ? StartURL : "about:blank");

                if (!string.IsNullOrEmpty(startUrl))
                {
                    LoadURL(startUrl);
                }
            }
        }
Пример #24
0
    private void Awake()
    {
        Messaging.System.LevelLoaded.AddListener((i) =>
        {
            Vector2 size   = transform.localScale;
            Vector2 offset = transform.position;

            TheGrid.min  = Vec2I.Floor(offset - size / 2);
            TheGrid.max  = Vec2I.Ceil(offset + size / 2);
            TheGrid.size = TheGrid.max - TheGrid.min;

            Heatmap.Recalculate();
            Room.ReconstructNetwork();

            AfterInit.Invoke();

            //report room information

            /*foreach (Room r in Room.Rooms)
             * {
             *  string d = "Room \"" + r.gameObject.name + "\" has " + r.Neighbors.Count + " neigbors: \n";
             *  r.Neighbors.Perform((n) => { d += "\"" + Room.Rooms[n.Data].gameObject.name + "\" "; });
             *  Debug.Log(d);
             *
             *  Debug.Log("ROOM \"" + r.gameObject.name + "\" neighbors:");
             *  r.Neighbors.Perform((n) =>
             *  {
             *      Debug.Log("neighbor \"" + Room.Rooms[n.Data].gameObject.name + "\" distance: "+ r.DistanceToNeighbor[n.Data]);
             *  });
             * }*/
        });
    }
            internal void DestroyViewport()
            {
                if (renderTargetListener != null)
                {
                    RenderTarget renderTarget = texture.GetBuffer().GetRenderTarget();
                    renderTarget.RemoveListener(renderTargetListener);
                    renderTargetListener.Dispose();
                    renderTargetListener = null;
                }
                if (viewport != null)
                {
                    viewport.Dispose();
                    viewport = null;
                }
                if (camera != null)
                {
                    camera.Dispose();
                    camera = null;
                }
                if (texture != null)
                {
                    texture.Dispose();
                    texture = null;
                    instance.preventTextureCreationRemainingFrames = 2;
                }

                initializedTextureSize = Vec2I.Zero;
            }
Пример #26
0
    private void Awake()
    {
        Messaging.Player.Position.AddListener((v) =>
        {
            Vec2I g = TheGrid.GridPosition(v);

            if (lastPlayerGridPosition == g)
            {
                return;
            }

            lastPlayerGridPosition = g;

            int gridDistance = Vec2I.Max(g, TheGrid.GridPosition(transform.position));

            if (gridDistance <= ShowTextDistance)
            {
                if (floatingText == null)
                {
                    floatingText = Messaging.GUI.FloatingText(transform.position + Offset, ShowText, TextColorFar);
                }

                floatingText.color = gridDistance <= UseDistance ? TextColorClose : TextColorFar;
            }
            else if (floatingText != null && gridDistance > ShowTextDistance)
            {
                Destroy(floatingText.gameObject);
                floatingText = null;
            }
        });
    }
                protected override void OnPreRenderTargetUpdate(RenderTargetEvent evt)
                {
                    base.OnPreRenderTargetUpdate(evt);

                    Camera defaultCamera = RendererWorld.Instance.DefaultCamera;
                    Camera camera        = owner.camera;

                    //set camera settings to default state
                    camera.ProjectionType    = defaultCamera.ProjectionType;
                    camera.OrthoWindowHeight = defaultCamera.OrthoWindowHeight;
                    camera.NearClipDistance  = defaultCamera.NearClipDistance;
                    camera.FarClipDistance   = defaultCamera.FarClipDistance;

                    Vec2I sizeInPixels = owner.Viewport.DimensionsInPixels.Size;

                    camera.AspectRatio = (float)sizeInPixels.X / (float)sizeInPixels.Y;

                    camera.Fov       = defaultCamera.Fov;
                    camera.FixedUp   = defaultCamera.FixedUp;
                    camera.Direction = defaultCamera.Direction;
                    camera.Position  = defaultCamera.Position;

                    ////override visibility (hide main scene objects, show from lists)
                    //List<SceneNode> sceneNodes = new List<SceneNode>();
                    //if( owner.sceneNode != null )
                    //   sceneNodes.Add( owner.sceneNode );
                    //SceneManager.Instance.SetOverrideVisibleObjects( new SceneManager.OverrideVisibleObjectsClass(
                    //   new StaticMeshObject[ 0 ], sceneNodes.ToArray(), new RenderLight[ 0 ] ) );

                    if (owner.Render != null)
                    {
                        owner.Render(owner, camera);
                    }
                }
    private bool MoveToRandomNearbyCell()
    {
        List <Vec2I> possible = new List <Vec2I>();

        foreach (Vec2I neighbor in owner.cell.neighbors)
        {
            if (!AI.CanPath(neighbor))
            {
                continue;
            }

            if (AI.GetHeat(neighbor).x >= 1f)
            {
                continue;
            }

            if (AI.HasLedge(owner.cell, neighbor))
            {
                continue;
            }

            possible.Add(neighbor);
        }

        if (possible.Count == 0)
        {
            return(false);
        }

        Vec2I d = Vec2I.directions[AxMath.RogueDirection(owner.cell, possible[Random.Range(0, possible.Count)])];

        wantDirection = new Vector3(d.x, 0, d.y).normalized;

        return(true);
    }
Пример #29
0
    private void BlipMove(ref MonsterCharacter.InputFrame frame)
    {
        frame.up            = dir.y;
        frame.right         = dir.x;
        frame.WantDirection = Quaternion.Euler(0, 0, AxMath.SafeAtan2(dir.y, dir.x) * Mathf.Rad2Deg);

        if (blipTimer > 0)
        {
            blipTimer -= Time.deltaTime;
            return;
        }

        blipTimer = BlipTime;
        dir       = Vec2I.zero;

        if (Random.value < BlipWaitChance)
        {
            return;
        }

        if (Leashed)
        {
            if ((homePosition - transform.position).sqrMagnitude >= LeashRange * LeashRange)
            {
                Vector2 distance = transform.position - Camera.main.transform.position;
                if (Mathf.Max(distance.x) > Options.AlertDistance.x || Mathf.Max(distance.y) > Options.AlertDistance.y)
                {
                    Destroy(gameObject);
                }
            }
        }

        if (Random.value < BlipRandomChance)
        {
            dir = Vec2I.directions[Random.Range(1, Vec2I.directions.Length)];
            return;
        }

        if (HuntPlayer)
        {
            if (LastKnownPlayerRoom != -1)
            {
                targetRoom = LastKnownPlayerRoom;
            }
        }

        if (targetRoom >= 0 && targetRoom < Room.Rooms.Length)
        {
            //simplistic behavior
            //dir = Room.Rooms[targetRoom].parent[thing.gridPos.x, thing.gridPos.y] - thing.gridPos;
            //return;

            //to avoid monsters piling up on single point
            if (Vec2I.Manhattan(Room.Rooms[targetRoom].gridPos, thing.gridPos) < NearSteps)
            {
                return;
            }

            if (!AI.RoomPath(thing.gridPos, Room.Rooms[targetRoom], MaxSteps, out Vec2I[] path))
Пример #30
0
    public static Vec2I NaturalStep(Vec2I[] path, int maxSteps)
    {
        if (path.Length == 0)
        {
            return(Vec2I.zero);
        }
        if (path.Length < 3)
        {
            return(path[1]);
        }
        if (maxSteps < 2)
        {
            return(path[1]);
        }

        Vec2I[] lastLine = new Vec2I[0];

        int steps = 0;
        int e     = 2;

again:
        Vec2I[] line = AxMath.CartesianLine(path[0], path[e]);

        for (int i = 0; i < line.Length; i++)
        {
            HeatmapNode n = Heatmap.GetNode(line[i]);
            if (n == null)
            {
                goto failed;
            }
            if (!n.WideOpen)
            {
                goto failed;
            }
        }

        if (steps <= maxSteps)
        {
            if (e == path.Length - 1)
            {
                return(path[e]);
            }

            lastLine = line;
            steps++;
            e++;

            goto again;
        }

failed:
        if (e > 2)
        {
            return(lastLine[lastLine.Length - 1]);
        }

        return(path[1]);
    }
Пример #31
0
    //returns Vec2I direction between two points
    public static int Atan2Direction(Vec2I origo, Vec2I target)
    {
        if (origo == target)
        {
            return(0);
        }

        return((int)(((SafeAtan2(target.y - origo.y, target.x - origo.x) + Mathf.PI) / TAU * 8) % 8 + 1));
    }
Пример #32
0
    public static int GetRoomIndex(Vec2I gridpos)
    {
        if (!TheGrid.Valid(gridpos))
        {
            return(-1);
        }

        return(RoomIndex[gridpos.x, gridpos.y]);
    }
        protected override void OnBeginRenderLightmap(
			StaticLightingCalculationWorld.MeshObject meshObject, LightmapImage renderingImage )
        {
            lightmapMeshObject = meshObject;
            lightmapRenderingImage = renderingImage;
            lightmapBucketIndex = Vec2I.Zero;

            Vec2I textureSize = lightmapRenderingImage.Size;

            //generate lightmapTriangleMap
            {
                lightmapTriangleMap = new int[ textureSize.Y ][];
                for( int y = 0; y < textureSize.Y; y++ )
                {
                    lightmapTriangleMap[ y ] = new int[ textureSize.X ];
                    for( int x = 0; x < textureSize.X; x++ )
                        lightmapTriangleMap[ y ][ x ] = -1;
                }

                Mesh mesh = meshObject.Mesh;

                int triangleCount = mesh.Indices.Length / 3;
                for( int triangleIndex = 0; triangleIndex < triangleCount; triangleIndex++ )
                {
                    int index0 = mesh.Indices[ triangleIndex * 3 + 0 ];
                    int index1 = mesh.Indices[ triangleIndex * 3 + 1 ];
                    int index2 = mesh.Indices[ triangleIndex * 3 + 2 ];

                    Vec3 position0 = mesh.Positions[ index0 ];
                    Vec3 position1 = mesh.Positions[ index1 ];
                    Vec3 position2 = mesh.Positions[ index2 ];
                    if( MathUtils.IsDegenerateTriangle( position0, position1, position2 ) )
                        continue;

                    Vec2 texCoord0 = mesh.LightmapTexCoords[ index0 ];
                    Vec2 texCoord1 = mesh.LightmapTexCoords[ index1 ];
                    Vec2 texCoord2 = mesh.LightmapTexCoords[ index2 ];

                    Vec2I pixelIndex0 = GetPixelIndexByTexCoord( texCoord0 );
                    Vec2I pixelIndex1 = GetPixelIndexByTexCoord( texCoord1 );
                    Vec2I pixelIndex2 = GetPixelIndexByTexCoord( texCoord2 );

                    Geometry2D.FillTriangle( pixelIndex0, pixelIndex1, pixelIndex2,
                        new RectI( Vec2I.Zero, textureSize ), delegate( Vec2I point )
                        {
                            lightmapTriangleMap[ point.Y ][ point.X ] = triangleIndex;
                        } );
                }
            }
        }
Пример #34
0
        protected override void OnCreateTexture( string definitionName, ref Vec2I size, ref PixelFormat format )
        {
            base.OnCreateTexture( definitionName, ref size, ref format );

            if( definitionName == "rt_brightPass" )
            {
                size = Owner.DimensionsInPixels.Size / 2;
                brightPassTextureSize = size;
            }
            else if( definitionName == "rt_bloomBlur" ||
                definitionName == "rt_bloomHorizontal" || definitionName == "rt_bloomVertical" )
            {
                size = Owner.DimensionsInPixels.Size / 4;
                bloomTextureSize = size;
            }
        }
Пример #35
0
		public void ClearMotionMap()
		{
			initialized = false;
			gridCellSizeInv = 0;

			onClosedList = 0;
			openList = null;
			whichList = null;
			openX = null;
			openY = null;
			parentX = null;
			parentY = null;
			Fcost = null;
			Gcost = null;
			Hcost = null;
			pathLength = 0;

			pathArray = null;

			mapSize = Vec2I.Zero;
			mapMaxIndex = Vec2I.Zero;

			mapMotionPosition = Vec2.Zero;
			mapMotion = null;
			mapMotionRectangles = new Dictionary<MapObject, RectI[]>();

			renderVertices.Clear();
			renderFreeIndices.Clear();
			renderBusyIndices.Clear();
		}
Пример #36
0
        bool CreateRenderTarget()
        {
            DestroyRenderTarget();

            if( RendererWorld.Instance == null )
                return false;

            Vec2I textureSize = GetDemandTextureSize();
            if( textureSize.X < 1 || textureSize.Y < 1 )
                return false;

            string textureName = TextureManager.Instance.GetUniqueName( "WPFRenderTexture" );

            int hardwareFSAA = 0;
            if( !RendererWorld.InitializationOptions.AllowSceneMRTRendering )
            {
                if( !int.TryParse( RendererWorld.InitializationOptions.FullSceneAntialiasing, out hardwareFSAA ) )
                    hardwareFSAA = 0;
            }

            texture = TextureManager.Instance.Create( textureName, Texture.Type.Type2D, textureSize,
                1, 0, Engine.Renderer.PixelFormat.R8G8B8, Texture.Usage.RenderTarget, false, hardwareFSAA );

            if( texture == null )
                return false;

            currentTextureSize = textureSize;

            renderTexture = texture.GetBuffer().GetRenderTarget();
            renderTexture.AutoUpdate = false;
            renderTexture.AllowAdditionalMRTs = true;

            camera = SceneManager.Instance.CreateCamera(
                SceneManager.Instance.GetUniqueCameraName( "UserControl" ) );
            camera.Purpose = Camera.Purposes.MainCamera;

            //update camera settings
            camera.NearClipDistance = cameraNearFarClipDistance.Minimum;
            camera.FarClipDistance = cameraNearFarClipDistance.Maximum;
            camera.AspectRatio = (float)texture.Size.X / (float)texture.Size.Y;
            camera.FixedUp = cameraFixedUp;
            camera.Position = cameraPosition;
            camera.Direction = cameraDirection;
            camera.Fov = cameraFov;
            camera.ProjectionType = cameraProjectionType;
            camera.OrthoWindowHeight = cameraOrthoWindowHeight;

            viewport = renderTexture.AddViewport( camera );

            //Initialize HDR compositor for HDR render technique
            if( EngineApp.RenderTechnique == "HDR" )
            {
                viewport.AddCompositor( "HDR", 0 );
                viewport.SetCompositorEnabled( "HDR", true );
            }

            //Initialize Fast Approximate Antialiasing (FXAA)
            {
                bool useMRT = RendererWorld.InitializationOptions.AllowSceneMRTRendering;
                string fsaa = RendererWorld.InitializationOptions.FullSceneAntialiasing;
                if( ( useMRT && ( fsaa == "" || fsaa == "RecommendedSetting" ) && IsActivateFXAAByDefault() ) ||
                    fsaa == "FXAA" )
                {
                    if( RenderSystem.Instance.HasShaderModel3() )
                        InitializeFXAACompositor();
                }
            }

            //add listener
            renderTargetListener = new ViewRenderTargetListener( this );
            renderTexture.AddListener( renderTargetListener );

            if( guiRenderer == null )
                guiRenderer = new GuiRenderer( viewport );
            else
                guiRenderer.ChangeViewport( viewport );

            if( controlManager == null )
                controlManager = new ScreenControlManager( guiRenderer );

            //initialize D3DImage output
            if( d3dImageIsSupported && allowUsingD3DImage )
            {
                // create a D3DImage to host the scene and monitor it for changes in front buffer availability
                if( d3dImage == null )
                {
                    d3dImage = new D3DImage();
                    d3dImage.IsFrontBufferAvailableChanged += D3DImage_IsFrontBufferAvailableChanged;
                    CompositionTarget.Rendering += D3DImage_OnRendering;
                }

                // set output to background image
                Background = new ImageBrush( d3dImage );

                // set the back buffer using the new scene pointer
                HardwarePixelBuffer buffer = texture.GetBuffer( 0, 0 );
                GetD3D9HardwarePixelBufferData data = new GetD3D9HardwarePixelBufferData();
                data.hardwareBuffer = buffer._GetRealObject();
                data.outPointer = IntPtr.Zero;
                unsafe
                {
                    GetD3D9HardwarePixelBufferData* pData = &data;
                    if( !RenderSystem.Instance.CallCustomMethod( "Get D3D9HardwarePixelBuffer getSurface", (IntPtr)pData ) )
                        Log.Fatal( "Get D3D9HardwarePixelBuffer getSurface failed." );
                }
                d3dImage.Lock();
                d3dImage.SetBackBuffer( D3DResourceType.IDirect3DSurface9, data.outPointer );
                d3dImage.Unlock();
            }

            return true;
        }
Пример #37
0
 void Client_ReceiveIndex( RemoteEntityWorld sender, ReceiveDataReader reader )
 {
     Vec2I value = reader.ReadVec2I();
     if( !reader.Complete() )
         return;
     index = value;
 }
Пример #38
0
        static void CalculateGaussianBlur5x5SampleOffsets( Vec2I textureSize,
			Vec2[] sampleOffsets, Vec4[] sampleWeights, float multiplier )
        {
            float tu = 1.0f / (float)textureSize.X;
            float tv = 1.0f / (float)textureSize.Y;

            Vec4 white = new Vec4( 1, 1, 1, 1 );

            float totalWeight = 0.0f;
            int index = 0;
            for( int x = -2; x <= 2; x++ )
            {
                for( int y = -2; y <= 2; y++ )
                {
                    // Exclude pixels with a block distance greater than 2. This will
                    // create a kernel which approximates a 5x5 kernel using only 13
                    // sample points instead of 25; this is necessary since 2.0 shaders
                    // only support 16 texture grabs.
                    if( Math.Abs( x ) + Math.Abs( y ) > 2 )
                        continue;

                    // Get the unscaled Gaussian intensity for this offset
                    sampleOffsets[ index ] = new Vec2( x * tu, y * tv );
                    sampleWeights[ index ] = white * GaussianDistribution( (float)x, (float)y, 1 );
                    totalWeight += sampleWeights[ index ].X;

                    index++;
                }
            }

            // Divide the current weight by the total weight of all the samples; Gaussian
            // blur kernels add to 1.0f to ensure that the intensity of the image isn't
            // changed when the blur occurs. An optional multiplier variable is used to
            // add or remove image intensity during the blur.
            for( int i = 0; i < index; i++ )
            {
                sampleWeights[ i ] /= totalWeight;
                sampleWeights[ i ] *= multiplier;
            }
        }
Пример #39
0
		public bool FindPath( float unitSize, Vec2 start, Vec2 end, int maxFieldsDistance, int maxFieldsToCheck, bool smooth,
			bool visualizeForDebugging, List<Vec2> path )
		{
			if( !initialized )
				return false;

			path.Clear();

			float internalUnitSize = unitSize * gridCellSizeInv;
			int nInternalUnitSize = (int)( internalUnitSize + .99999f );

			if( nInternalUnitSize == 0 )
				Log.Fatal( "GridBasedNavigationSystem: FindPath: nInternalUnitSize == 0." );

			Vec2 internalStart = ( start - mapMotionPosition ) * gridCellSizeInv;
			Vec2 internalEnd = ( end - mapMotionPosition ) * gridCellSizeInv;

			Vec2I nInternalStart = new Vec2I( (int)internalStart.X, (int)internalStart.Y );
			Vec2I nInternalEnd = new Vec2I( (int)internalEnd.X, (int)internalEnd.Y );

			if( nInternalStart.X < 0 || nInternalStart.X >= mapSize.X ||
				nInternalStart.Y < 0 || nInternalStart.Y >= mapSize.Y )
				return false;
			if( nInternalEnd.X < 0 || nInternalEnd.X >= mapSize.X ||
				nInternalEnd.Y < 0 || nInternalEnd.Y >= mapSize.Y )
				return false;

			int nPathSize = DoFindA( nInternalStart, nInternalEnd, nInternalUnitSize,
				maxFieldsDistance, maxFieldsToCheck, visualizeForDebugging );
			if( nPathSize == 0 )
				return false;

			if( smooth )
			{
				//remove fictitious points
				nPathSize = RemoveFictitiousPoints( nInternalStart, nPathSize );
				if( nPathSize == 0 )
					return false;
			}

			pathArray[ 0 ] = nInternalStart;

			if( smooth )
			{
				//smooth path
				nPathSize = Smooth( internalStart, nPathSize + 1, internalUnitSize );
				if( nPathSize == 0 )
					return false;
			}

			for( int n = 0; n < nPathSize; n++ )
			{
				Vec2 internalPoint = new Vec2( pathArray[ n ].X, pathArray[ n ].Y ) + new Vec2( .5f, .5f );
				path.Add( internalPoint * GridCellSize + mapMotionPosition );
			}

			if( !smooth || pathLength == 1 )
				path.Add( end );

			return true;
		}
Пример #40
0
 public Vec2 GetPieceDestinationPosition( Vec2I index )
 {
     //piece size is always 1,1
     return new Vec2( .5f, .5f ) + index.ToVec2();
 }
Пример #41
0
        void ServerOrSingle_SetPieceCount( Vec2I pieceCount )
        {
            this.pieceCount = pieceCount;

            //send pieceCount to clients
            if( EntitySystemWorld.Instance.IsServer() )
                Server_SendPieceCountToClients( EntitySystemWorld.Instance.RemoteEntityWorlds );
        }
Пример #42
0
        void ServerOrSingle_GeneratePuzzles( Vec2I pieceCount )
        {
            ServerOrSingle_DestroyPuzzles();

            ServerOrSingle_SetPieceCount( pieceCount );

            for( int y = 0; y < pieceCount.Y; y++ )
                for( int x = 0; x < pieceCount.X; x++ )
                    ServerOrSingle_CreatePiece( new Vec2I( x, y ) );
        }
Пример #43
0
        void ServerOrSingle_CreatePiece( Vec2I index )
        {
            JigsawPuzzlePiece piece = (JigsawPuzzlePiece)Entities.Instance.Create(
                "JigsawPuzzlePiece", Map.Instance );

            piece.ServerOrSingle_SetIndex( index );

            //calculate position
            {
                Rect area = GetGameArea();
                area.Expand( -.5f );
                Rect exceptArea = GetDestinationArea();
                exceptArea.Expand( 1 );

                float x = 0;
                float y = 0;

                bool free = false;
                do
                {
                    free = true;

                    EngineRandom random = World.Instance.Random;
                    x = area.Minimum.X + random.NextFloat() * area.Size.X;
                    y = area.Minimum.Y + random.NextFloat() * area.Size.Y;

                    if( exceptArea.IsContainsPoint( new Vec2( x, y ) ) )
                        free = false;

                    Bounds checkBounds = new Bounds(
                        new Vec3( x - .5f, y - .5f, -100 ),
                        new Vec3( x + .5f, y + .5f, 100 ) );

                    Map.Instance.GetObjects( checkBounds, delegate( MapObject mapObject )
                        {
                            JigsawPuzzlePiece p = mapObject as JigsawPuzzlePiece;
                            if( p != null )
                                free = false;
                        } );

                } while( !free );

                piece.Position = new Vec3( x, y, .1f );
            }

            piece.PostCreate();
        }
Пример #44
0
 void Client_ReceivePieceCount( RemoteEntityWorld sender, ReceiveDataReader reader )
 {
     Vec2I value = reader.ReadVec2I();
     if( !reader.Complete() )
         return;
     pieceCount = value;
 }
Пример #45
0
		int DoFindA( Vec2I start, Vec2I end, int unitSize, int maxFieldsDistance,
			int maxFieldsToCheck, bool visualizeForDebugging )
		{
			const int found = 1, nonexistent = 2;
			const int notStarted = 0;// path-related constants
			const int walkable = 0;// walkability array constants

			int onOpenList = 0, parentXval = 0, parentYval = 0,
			a = 0, b = 0, m = 0, u = 0, v = 0, temp = 0, corner = 0, numberOfOpenListItems = 0,
			addedGCost = 0, tempGcost = 0, path = 0,
			tempx, pathX, pathY, //cellPosition,
			newOpenListItemID = 0;

			//1. Convert location data (in pixels) to coordinates in the walkability array.
			int startX = start.X;
			int startY = start.Y;
			int targetX = end.X;
			int targetY = end.Y;

			//2.Quick Path Checks: Under the some circumstances no path needs to
			//	be generated ...

			//	If starting location and target are in the same location...
			if( start == end )
				return 0;

			//	if (startX == targetX && startY == targetY && pathLocation[pathfinderID] > 0)
			//		return found;
			//	if (startX == targetX && startY == targetY && pathLocation[pathfinderID] == 0)
			//		return nonexistent;

			//	If target square is unwalkable, return that it's a nonexistent path.

			if( !IsFreeInMapMotion( new Vec2I( targetX, targetY ), unitSize ) )
				return 0;

			//3.Reset some variables that need to be cleared
			if( onClosedList > 1000000 ) //reset whichList occasionally
			{
				for( int y = 0; y < mapSize.Y; y++ )
					for( int x = 0; x < mapSize.X; x++ )
						whichList[ x, y ] = 0;
				//memset( whichList, 0, sizeof( whichList ) );
				onClosedList = 10;
			}
			onClosedList = onClosedList + 2; //changing the values of onOpenList and onClosed list is faster than redimming whichList() array
			onOpenList = onClosedList - 1;
			pathLength = notStarted;//i.e, = 0
			//pathLocation = notStarted;//i.e, = 0
			Gcost[ startX, startY ] = 0; //reset starting square's G value to 0

			//4.Add the starting location to the open list of squares to be checked.
			numberOfOpenListItems = 1;
			openList[ 1 ] = 1;//assign it as the top (and currently only) item in the open list, which is maintained as a binary heap (explained below)
			openX[ 1 ] = startX; openY[ 1 ] = startY;

			int fieldsCheckedCount = 0;

			//5.Do the following until a path is found or deemed nonexistent.
			do
			{
				//6.If the open list is not empty, take the first cell off of the list.
				//	This is the lowest F cost cell on the open list.
				if( numberOfOpenListItems != 0 )
				{

					//7. Pop the first item off the open list.
					parentXval = openX[ openList[ 1 ] ];
					parentYval = openY[ openList[ 1 ] ]; //record cell coordinates of the item
					whichList[ parentXval, parentYval ] = onClosedList;//add the item to the closed list

					//	Open List = Binary Heap: Delete this item from the open list, which
					//  is maintained as a binary heap. For more information on binary heaps, see:
					//	http://www.policyalmanac.org/games/binaryHeaps.htm
					numberOfOpenListItems = numberOfOpenListItems - 1;//reduce number of open list items by 1	

					//	Delete the top item in binary heap and reorder the heap, with the lowest F cost item rising to the top.
					openList[ 1 ] = openList[ numberOfOpenListItems + 1 ];//move the last item in the heap up to slot #1
					v = 1;

					//	Repeat the following until the new item in slot #1 sinks to its proper spot in the heap.
					do
					{
						u = v;
						if( 2 * u + 1 <= numberOfOpenListItems ) //if both children exist
						{
							//Check if the F cost of the parent is greater than each child.
							//Select the lowest of the two children.
							if( Fcost[ openList[ u ] ] >= Fcost[ openList[ 2 * u ] ] )
								v = 2 * u;
							if( Fcost[ openList[ v ] ] >= Fcost[ openList[ 2 * u + 1 ] ] )
								v = 2 * u + 1;
						}
						else
						{
							if( 2 * u <= numberOfOpenListItems ) //if only child #1 exists
							{
								//Check if the F cost of the parent is greater than child #1	
								if( Fcost[ openList[ u ] ] >= Fcost[ openList[ 2 * u ] ] )
									v = 2 * u;
							}
						}

						if( u != v ) //if parent's F is > one of its children, swap them
						{
							temp = openList[ u ];
							openList[ u ] = openList[ v ];
							openList[ v ] = temp;
						}
						else
							break; //otherwise, exit loop

					}
					while( true );


					//7.Check the adjacent squares. (Its "children" -- these path children
					//	are similar, conceptually, to the binary heap children mentioned
					//	above, but don't confuse them. They are different. Path children
					//	are portrayed in Demo 1 with grey pointers pointing toward
					//	their parents.) Add these adjacent child squares to the open list
					//	for later consideration if appropriate (see various if statements
					//	below).
					for( b = parentYval - 1; b <= parentYval + 1; b++ )
					{
						for( a = parentXval - 1; a <= parentXval + 1; a++ )
						{

							//	If not off the map (do this first to avoid array out-of-bounds errors)
							if( a != -1 && b != -1 && a != mapSize.X && b != mapSize.Y )
							{

								//	If not already on the closed list (items on the closed list have
								//	already been considered and can now be ignored).			
								if( whichList[ a, b ] != onClosedList )
								{

									//	If not a wall/obstacle square.
									if( Math.Abs( a - start.X ) <= maxFieldsDistance &&
										Math.Abs( b - start.Y ) <= maxFieldsDistance )
									{
										if( IsFreeInMapMotion( new Vec2I( a, b ), unitSize ) )
										{

											//	Don't cut across corners
											corner = walkable;
											if( a == parentXval - 1 )
											{
												if( b == parentYval - 1 )
												{
													if( !IsFreeInMapMotion( new Vec2I( parentXval - 1, parentYval ), unitSize )
														|| !IsFreeInMapMotion( new Vec2I( parentXval, parentYval - 1 ), unitSize ) )
														corner = 1;
												}
												else if( b == parentYval + 1 )
												{
													if( !IsFreeInMapMotion( new Vec2I( parentXval, parentYval + 1 ), unitSize )
														|| !IsFreeInMapMotion( new Vec2I( parentXval - 1, parentYval ), unitSize ) )
														corner = 1;
												}
											}
											else if( a == parentXval + 1 )
											{
												if( b == parentYval - 1 )
												{
													if( !IsFreeInMapMotion( new Vec2I( parentXval, parentYval - 1 ), unitSize )
														|| !IsFreeInMapMotion( new Vec2I( parentXval + 1, parentYval ), unitSize ) )
														corner = 1;
												}
												else if( b == parentYval + 1 )
												{
													if( !IsFreeInMapMotion( new Vec2I( parentXval + 1, parentYval ), unitSize )
														|| !IsFreeInMapMotion( new Vec2I( parentXval, parentYval + 1 ), unitSize ) )
														corner = 1;
												}
											}
											if( corner == walkable )
											{
												//	If not already on the open list, add it to the open list.			
												if( whichList[ a, b ] != onOpenList )
												{
													//check for max fields
													fieldsCheckedCount++;
													if( fieldsCheckedCount == maxFieldsToCheck )
													{
														goto notFound;
													}

													//visualize
													if( visualizeForDebugging )
													{
														Vec2 startPoint2 = mapMotionPosition +
															new Vec2( (float)a + .5f, (float)b + .5f ) * GridCellSize;
														Vec3 startPoint = new Vec3( startPoint2.X, startPoint2.Y,
															GetMotionMapHeight( startPoint2 ) );

														Vec2 endPoint2 = mapMotionPosition +
															new Vec2( (float)parentXval + .5f, (float)parentYval + .5f ) * GridCellSize;
														Vec3 endPoint = new Vec3( endPoint2.X, endPoint2.Y, GetMotionMapHeight( endPoint2 ) );

														Camera camera = RendererWorld.Instance.DefaultCamera;
														camera.DebugGeometry.Color = new ColorValue( 1, 1, 1, .5f );
														camera.DebugGeometry.AddArrow(
															startPoint + new Vec3( 0, 0, .1f ),
															endPoint + new Vec3( 0, 0, .1f ) );
													}

													//Create a new open list item in the binary heap.
													newOpenListItemID = newOpenListItemID + 1; //each new item has a unique ID #
													m = numberOfOpenListItems + 1;
													openList[ m ] = newOpenListItemID;//place the new open list item (actually, its ID#) at the bottom of the heap
													openX[ newOpenListItemID ] = a;
													openY[ newOpenListItemID ] = b;//record the x and y coordinates of the new item

													//Figure out its G cost
													if( Math.Abs( a - parentXval ) == 1 && Math.Abs( b - parentYval ) == 1 )
														addedGCost = 14;//cost of going to diagonal squares	
													else
														addedGCost = 10;//cost of going to non-diagonal squares				
													Gcost[ a, b ] = Gcost[ parentXval, parentYval ] + addedGCost;

													//Figure out its H and F costs and parent
													Hcost[ openList[ m ] ] = 10 * ( Math.Abs( a - targetX ) + Math.Abs( b - targetY ) );
													Fcost[ openList[ m ] ] = Gcost[ a, b ] + Hcost[ openList[ m ] ];
													parentX[ a, b ] = parentXval; parentY[ a, b ] = parentYval;

													//Move the new open list item to the proper place in the binary heap.
													//Starting at the bottom, successively compare to parent items,
													//swapping as needed until the item finds its place in the heap
													//or bubbles all the way to the top (if it has the lowest F cost).
													while( m != 1 ) //While item hasn't bubbled to the top (m=1)	
													{
														//Check if child's F cost is < parent's F cost. If so, swap them.	
														if( Fcost[ openList[ m ] ] <= Fcost[ openList[ m / 2 ] ] )
														{
															temp = openList[ m / 2 ];
															openList[ m / 2 ] = openList[ m ];
															openList[ m ] = temp;
															m = m / 2;
														}
														else
															break;
													}
													numberOfOpenListItems = numberOfOpenListItems + 1;//add one to the number of items in the heap

													//Change whichList to show that the new item is on the open list.
													whichList[ a, b ] = onOpenList;
												}

												//8.If adjacent cell is already on the open list, check to see if this 
												//	path to that cell from the starting location is a better one. 
												//	If so, change the parent of the cell and its G and F costs.	
												else //If whichList(a,b) = onOpenList
												{
													//Figure out the G cost of this possible new path
													if( Math.Abs( a - parentXval ) == 1 && Math.Abs( b - parentYval ) == 1 )
														addedGCost = 14;//cost of going to diagonal tiles	
													else
														addedGCost = 10;//cost of going to non-diagonal tiles				
													tempGcost = Gcost[ parentXval, parentYval ] + addedGCost;

													//If this path is shorter (G cost is lower) then change
													//the parent cell, G cost and F cost. 		
													if( tempGcost < Gcost[ a, b ] ) //if G cost is less,
													{
														parentX[ a, b ] = parentXval; //change the square's parent
														parentY[ a, b ] = parentYval;
														Gcost[ a, b ] = tempGcost;//change the G cost			

														//Because changing the G cost also changes the F cost, if
														//the item is on the open list we need to change the item's
														//recorded F cost and its position on the open list to make
														//sure that we maintain a properly ordered open list.
														for( int x = 1; x <= numberOfOpenListItems; x++ ) //look for the item in the heap
														{
															if( openX[ openList[ x ] ] == a && openY[ openList[ x ] ] == b ) //item found
															{
																Fcost[ openList[ x ] ] = Gcost[ a, b ] + Hcost[ openList[ x ] ];//change the F cost

																//See if changing the F score bubbles the item up from it's current location in the heap
																m = x;
																while( m != 1 ) //While item hasn't bubbled to the top (m=1)	
																{
																	//Check if child is < parent. If so, swap them.	
																	if( Fcost[ openList[ m ] ] < Fcost[ openList[ m / 2 ] ] )
																	{
																		temp = openList[ m / 2 ];
																		openList[ m / 2 ] = openList[ m ];
																		openList[ m ] = temp;
																		m = m / 2;
																	}
																	else
																		break;
																}
																break; //exit for x = loop
															} //If openX(openList(x)) = a
														} //For x = 1 To numberOfOpenListItems
													}//If tempGcost < Gcost(a,b)

												}//else If whichList(a,b) = onOpenList	
											}//If not cutting a corner
										}//If not a wall/obstacle square.
									}
								}//If not already on the closed list 
							}//If not off the map
						}//for (a = parentXval-1; a <= parentXval+1; a++){
					}//for (b = parentYval-1; b <= parentYval+1; b++){

				}//if (numberOfOpenListItems != 0)

				//9.If open list is empty then there is no path.	
				else
				{
					path = nonexistent;
					break;
				}

				//If target is added to open list then path has been found.
				if( whichList[ targetX, targetY ] == onOpenList )
				{
					path = found;
					break;
				}

			}
			while( true );//Do until path is found or deemed nonexistent

			//10.Save the path if it exists.
			if( path == found )
			{
				//a.Working backwards from the target to the starting location by checking
				//	each cell's parent, figure out the length of the path.
				pathX = targetX; pathY = targetY;
				do
				{
					//Look up the parent of the current cell.	
					tempx = parentX[ pathX, pathY ];
					pathY = parentY[ pathX, pathY ];
					pathX = tempx;

					//Figure out the path length
					pathLength = pathLength + 1;
				}
				while( pathX != startX || pathY != startY );

				//construct patharray
				{
					int pos = pathLength - 1;
					pathX = targetX; pathY = targetY;
					do
					{
						/*patharray[pos]*/
						pathArray[ pos + 1 ] = new Vec2I( pathX, pathY );
						pos--;
						tempx = parentX[ pathX, pathY ];
						pathY = parentY[ pathX, pathY ];
						pathX = tempx;
					}
					while( pathX != startX || pathY != startY );
				}
				return pathLength;
			}

			notFound:

			return 0;
		}
Пример #46
0
		void InitializeMotionMap()
		{
			initialized = true;
			if( gridCellSize != 0 )
				gridCellSizeInv = 1.0f / gridCellSize;

			Rect bounds = gridBounds;
			if( bounds == Rect.Zero )
				bounds = new Rect( Vec2.Zero, new Vec2( 10, 10 ) );

			Vec2 v = bounds.GetSize() * gridCellSizeInv;
			mapSize = new Vec2I( (int)v.X, (int)v.Y );
			mapMotionPosition = new Vec2( bounds.Minimum.X, bounds.Minimum.Y );

			mapMaxIndex = mapSize - new Vec2I( mapSize.X > 0 ? 1 : 0, mapSize.Y > 0 ? 1 : 0 );

			openList = new int[ mapSize.X * mapSize.Y + 2 ];
			whichList = new int[ mapSize.X, mapSize.Y ];
			openX = new int[ mapSize.X * mapSize.Y + 2 ];
			openY = new int[ mapSize.X * mapSize.Y + 2 ];
			parentX = new int[ mapSize.X, mapSize.Y ];
			parentY = new int[ mapSize.X, mapSize.Y ];
			Fcost = new int[ mapSize.X * mapSize.Y + 2 ];
			Gcost = new int[ mapSize.X, mapSize.Y ];
			Hcost = new int[ mapSize.X * mapSize.Y + 2 ];

			pathArray = new Vec2I[ mapSize.X * mapSize.Y ];

			renderVertices.Clear();
			renderFreeIndices.Clear();
			renderBusyIndices.Clear();

			mapMotionRectangles.Clear();

			mapMotion = new byte[ mapSize.X, mapSize.Y ];
			FillMotionMap();
		}
Пример #47
0
		Vec2I GetNearestFreeMotionMap( Vec2I pos, int unitSize )
		{
			if( IsFreeInMapMotion( pos, unitSize ) )
				return pos;

			for( int r = 1; ; r++ )
			{
				for( int n = 0; n <= r; n++ )
				{
					Vec2I p;

					p = pos + new Vec2I( n, -r );
					if( IsFreeInMapMotion( p, unitSize ) )
						return p;

					p = pos + new Vec2I( n, r );
					if( IsFreeInMapMotion( p, unitSize ) )
						return p;

					p = pos + new Vec2I( -n, -r );
					if( IsFreeInMapMotion( p, unitSize ) )
						return p;

					p = pos + new Vec2I( -n, r );
					if( IsFreeInMapMotion( p, unitSize ) )
						return p;

					p = pos + new Vec2I( -r, n );
					if( IsFreeInMapMotion( p, unitSize ) )
						return p;

					p = pos + new Vec2I( r, n );
					if( IsFreeInMapMotion( p, unitSize ) )
						return p;

					p = pos + new Vec2I( -r, -n );
					if( IsFreeInMapMotion( p, unitSize ) )
						return p;

					p = pos + new Vec2I( -r, n );
					if( IsFreeInMapMotion( p, unitSize ) )
						return p;
				}
			}
		}
Пример #48
0
		Vec2I GetMapMotionPosition( Vec2 pos )
		{
			Vec2 pf = ( pos - mapMotionPosition ) * gridCellSizeInv;
			Vec2I p = new Vec2I( (int)pf.X, (int)pf.Y );
			p.Clamp( new Vec2I( 0, 0 ), mapMaxIndex );
			return p;
		}
		protected override void OnCreateTexture( string definitionName, ref Vec2I size, ref PixelFormat format )
		{
			base.OnCreateTexture( definitionName, ref size, ref format );

			//change format of rt_scene and rt_final textures if HDR compositor is enabled.
			if( definitionName == "rt_scene" || definitionName == "rt_final" )
			{
				CompositorInstance hdrInstance = Owner.GetCompositorInstance( "HDR" );
				if( hdrInstance != null && hdrInstance.Enabled )
					format = PixelFormat.Float16RGB;
				else
					format = PixelFormat.R8G8B8;
			}

			if( definitionName == "rt_depth" || definitionName == "rt_occlusion" )
			{
				float divisor = downsampling;
				if( divisor < 1 )
					divisor = 1;
				Vec2 sizeFloat = Owner.DimensionsInPixels.Size.ToVec2() / divisor;
				size = new Vec2I( (int)sizeFloat.X, (int)sizeFloat.Y );
				if( size.X < 1 )
					size.X = 1;
				if( size.Y < 1 )
					size.Y = 1;

				downscaleTextureSize = size;
			}
		}
Пример #50
0
		RectI GetMapMotionRectangle( Rect rect )
		{
			Vec2 minf = ( rect.Minimum - mapMotionPosition ) * gridCellSizeInv;
			Vec2 maxf = ( rect.Maximum - mapMotionPosition ) * gridCellSizeInv;
			Vec2I min = new Vec2I( (int)minf.X, (int)minf.Y );
			Vec2I max = new Vec2I( (int)maxf.X, (int)maxf.Y );
			min.Clamp( new Vec2I( 0, 0 ), mapMaxIndex );
			max.Clamp( new Vec2I( 0, 0 ), mapMaxIndex );
			return new RectI( min, max );
		}
Пример #51
0
 static void CalculateDownScale4x4SampleOffsets( Vec2I sourceTextureSize, Vec2[] sampleOffsets )
 {
     // Sample from the 16 surrounding points. Since the center point will be in
     // the exact center of 16 texels, a 0.5f offset is needed to specify a texel
     // center.
     Vec2 invSize = 1.0f / sourceTextureSize.ToVec2();
     int index = 0;
     for( int y = 0; y < 4; y++ )
     {
         for( int x = 0; x < 4; x++ )
         {
             sampleOffsets[ index ] = new Vec2( ( (float)x - 1.5f ), ( (float)y - 1.5f ) ) * invSize;
             index++;
         }
     }
 }
Пример #52
0
		bool IsFreeInMapMotion( Vec2I pos, int unitSize )
		{
			if( unitSize != 1 )
			{
				if( pos.X + unitSize - 1 >= mapSize.X )
					return false;
				if( pos.Y + unitSize - 1 >= mapSize.Y )
					return false;

				for( int y = 0; y < unitSize; y++ )
					for( int x = 0; x < unitSize; x++ )
						if( !IsFreeInMapMotion( pos + new Vec2I( x, y ) ) )
							return false;
				return true;
			}
			else
				return IsFreeInMapMotion( pos );
		}
Пример #53
0
		bool IsFreeInMapMotion( Vec2I pos )
		{
			return mapMotion[ pos.X, pos.Y ] == 0;
		}
            private void CreateViewport()
            {
                int index = instance.views.IndexOf(this);

                DestroyViewport();

                Vec2I textureSize = GetNeededTextureSize();

                string textureName = TextureManager.Instance.GetUniqueName(
                    string.Format("MultiViewRendering{0}", index));
                PixelFormat format = PixelFormat.R8G8B8;

                int fsaa;
                if (!int.TryParse(RendererWorld.InitializationOptions.FullSceneAntialiasing, out fsaa))
                    fsaa = 0;

                texture = TextureManager.Instance.Create(textureName, Texture.Type.Type2D,
                    textureSize, 1, 0, format, Texture.Usage.RenderTarget, false, fsaa);
                if (texture == null)
                {
                    Log.Fatal("MultiViewRenderingManager: Unable to create texture.");
                    return;
                }

                RenderTarget renderTarget = texture.GetBuffer().GetRenderTarget();
                renderTarget.AutoUpdate = true;
                renderTarget.AllowAdditionalMRTs = true;

                //create camera
                camera = SceneManager.Instance.CreateCamera(
                    SceneManager.Instance.GetUniqueCameraName(string.Format("MultiViewRendering{0}", index)));
                camera.Purpose = Camera.Purposes.MainCamera;

                //add viewport
                viewport = renderTarget.AddViewport(camera, 0);
                viewport.ShadowsEnabled = true;

                //Create compositor for HDR render technique
                bool hdrCompositor =
                    RendererWorld.Instance.DefaultViewport.GetCompositorInstance("HDR") != null;
                if (hdrCompositor)
                {
                    viewport.AddCompositor("HDR");
                    viewport.SetCompositorEnabled("HDR", true);
                }

                //FXAA antialiasing post effect
                bool fxaaCompositor =
                    RendererWorld.Instance.DefaultViewport.GetCompositorInstance("FXAA") != null;
                if (fxaaCompositor)
                {
                    viewport.AddCompositor("FXAA");
                    viewport.SetCompositorEnabled("FXAA", true);
                }

                //add listener
                renderTargetListener = new ViewRenderTargetListener(this);
                renderTarget.AddListener(renderTargetListener);

                initializedTextureSize = textureSize;
            }
Пример #55
0
        public void ServerOrSingle_SetIndex( Vec2I index )
        {
            this.index = index;

            //send Index to clients
            if( EntitySystemWorld.Instance.IsServer() )
                Server_SendIndexToClients( EntitySystemWorld.Instance.RemoteEntityWorlds );
        }
            internal void DestroyViewport()
            {
                if (renderTargetListener != null)
                {
                    RenderTarget renderTarget = texture.GetBuffer().GetRenderTarget();
                    renderTarget.RemoveListener(renderTargetListener);
                    renderTargetListener.Dispose();
                    renderTargetListener = null;
                }
                if (viewport != null)
                {
                    viewport.Dispose();
                    viewport = null;
                }
                if (camera != null)
                {
                    camera.Dispose();
                    camera = null;
                }
                if (texture != null)
                {
                    texture.Dispose();
                    texture = null;
                    instance.preventTextureCreationRemainingFrames = 2;
                }

                initializedTextureSize = Vec2I.Zero;
            }
        protected override void OnCreateTexture( string definitionName, ref Vec2I size, ref PixelFormat format )
        {
            base.OnCreateTexture( definitionName, ref size, ref format );

            if( definitionName == "rt_scattering" || definitionName == "rt_blur" )
            {
                float divisor = 9.0f - resolution;
                if( divisor <= 1 )
                    divisor = 1;
                Vec2 sizeFloat = Owner.DimensionsInPixels.Size.ToVec2() / divisor;
                size = new Vec2I( (int)sizeFloat.X, (int)sizeFloat.Y );
            }
        }
Пример #58
0
		private void MainForm_FormClosing( object sender, FormClosingEventArgs e )
		{
			DestroyWorkAreaControl();

			showMaximized = WindowState != FormWindowState.Normal;
			startWindowSize = new Vec2I( Size.Width, Size.Height );

			if( !forceCloseForm )
			{
				string configFile = VirtualFileSystem.GetRealPathByVirtual( dockingConfigFileName );
				if( !Directory.Exists( Path.GetDirectoryName( configFile ) ) )
					Directory.CreateDirectory( Path.GetDirectoryName( configFile ) );
				dockPanel.SaveAsXml( configFile );
			}

			instance = null;
		}
Пример #59
0
        Vec2I GetDemandTextureSize()
        {
            double dpiFactor = GetDPIFactor();

            Vec2I size = new Vec2I(
                (int)( ActualWidth / dpiFactor + .999 ),
                (int)( ActualHeight / dpiFactor + .999 ) );

            return size;
        }
Пример #60
0
        protected override void OnCreateTexture( string definitionName, ref Vec2I size, ref PixelFormat format )
        {
            base.OnCreateTexture( definitionName, ref size, ref format );

            if( definitionName == "rt_downscale" || definitionName == "rt_blurHorizontal" ||
                definitionName == "rt_blurVertical" )
            {
                float divisor = 8.0f - blurTextureResolution;
                if( divisor <= 1 )
                    divisor = 1;
                Vec2 sizeFloat = Owner.DimensionsInPixels.Size.ToVec2() / divisor;
                size = new Vec2I( (int)sizeFloat.X, (int)sizeFloat.Y );
                if( size.X < 1 )
                    size.X = 1;
                if( size.Y < 1 )
                    size.Y = 1;

                downscaleTextureSize = size;
            }
        }