コード例 #1
0
        public static float[,,] BlendLayers(Matrix[] matrices, Matrix[] masks, Area area, StopToken stop = null)
        {
            int fullSize   = area.full.rect.size.x;
            int activeSize = area.active.rect.size.x;
            int margins    = area.Margins;

            float[,,] splats3D = new float[activeSize, activeSize, matrices.Length];

            for (int x = 0; x < activeSize; x++)
            {
                if (stop != null && stop.stop)
                {
                    return(null);
                }
                for (int z = 0; z < activeSize; z++)
                {
                    //int pos = (z+margins-area.full.rect.offset.z)*area.full.rect.size.x + x+margins - area.full.rect.offset.x;
                    int pos = area.full.rect.GetPos(x + area.full.rect.offset.x + margins, z + area.full.rect.offset.z + margins);

                    float sum = 0;
                    for (int i = 0; i < matrices.Length; i++)
                    {
                        float val = matrices[i].arr[pos] * (masks[i] == null ? 1 : masks[i].arr[pos]);
                        sum += val;
                    }

                    if (sum != 0)
                    {
                        for (int i = 0; i < matrices.Length; i++)
                        {
                            float val = matrices[i].arr[pos] * (masks[i] == null ? 1 : masks[i].arr[pos]);
                            val /= sum;

                            if (val < 0)
                            {
                                val = 0;
                            }
                            if (val > 1)
                            {
                                val = 1;
                            }

                            splats3D[z, x, i] = val;
                        }
                    }
                }
            }

            return(splats3D);
        }
コード例 #2
0
        public static void NormalizeLayers(INormalizableLayer[] layers, TileData data, StopToken stop)
        {
            //reading products
            MatrixWorld[] matrices  = new MatrixWorld[layers.Length];
            float[]       opacities = new float[layers.Length];

            if (stop != null && stop.stop)
            {
                return;
            }
            for (int i = 0; i < layers.Length; i++)
            {
                if (stop != null && stop.stop)
                {
                    return;
                }

                MatrixWorld srcMatrix = data.products.ReadInlet(layers[i]);
                if (srcMatrix != null)
                {
                    matrices[i] = new MatrixWorld(srcMatrix);
                }

                //if (matrices[i] != null)
                //	matrices[i].Clamp01();

                opacities[i] = layers[i].Opacity;
            }

            //normalizing
            if (stop != null && stop.stop)
            {
                return;
            }
            matrices.FillNulls(() => new MatrixWorld(data.area.full.rect, (Vector3)data.area.full.worldPos, (Vector3)data.area.full.worldSize));
            matrices[0].Fill(1);
            Matrix.BlendLayers(matrices, opacities);

            //saving products
            if (stop != null && stop.stop)
            {
                return;
            }
            for (int i = 0; i < layers.Length; i++)
            {
                data.products[layers[i]] = matrices[i];
            }
        }
コード例 #3
0
 public void OnBeforeTileGenerateCheckFirst(TerrainTile tile, TileData data, StopToken stop)
 {
     OnBeforeTileGenerateCheck(tile, data);
 }
コード例 #4
0
 protected override void startAction()
 {
     MasterSpellLibrary.SpellFeedbackSFX.Play(Volume, true);
     StopToken.Register(() => MasterSpellLibrary.SpellFeedbackSFX.Stop());
 }
コード例 #5
0
        public static void OnOutputFinalized_WriteLocksInThread(Type type, TileData tileData, IApplyData applyData, StopToken stop)
        {
            Dictionary <Lock, LockDataSet> lockDatasDict;

            if (!lockDatas.TryGetValue(tileData, out lockDatasDict))
            {
                return;
            }

            foreach (var kvp in lockDatasDict)
            {
                Lock        lk       = kvp.Key;
                LockDataSet lockData = kvp.Value;

                if (!lk.locked)
                {
                    continue;
                }

                bool relativeHeight = lk.relativeHeight;
                if (lk.IsIntersecting(tileData.area.active) && !lk.IsContained(tileData.area.active))
                {
                    relativeHeight = false;
                }

                lockData.WriteInThread(applyData, relativeHeight);
            }
        }
コード例 #6
0
ファイル: HeightOut.cs プロジェクト: louis030195/niwrad
        public static FinalizeAction finalizeAction = Finalize;         //class identified for FinalizeData
        public static void Finalize(TileData data, StopToken stop)
        {
            //blending all biomes in data.height matrix
            if (data.heights == null ||
                data.heights.rect.size != data.area.full.rect.size ||
                data.heights.worldPos != (Vector3)data.area.full.worldPos ||
                data.heights.worldSize != (Vector3)data.area.full.worldSize)
            {
                data.heights = new MatrixWorld(data.area.full.rect, data.area.full.worldPos, data.area.full.worldSize, data.globals.height);
            }
            data.heights.worldSize.y = data.globals.height;
            data.heights.Fill(0);

            foreach ((HeightOutput200 output, MatrixWorld product, MatrixWorld biomeMask)
                     in data.finalize.ProductSets <HeightOutput200, MatrixWorld, MatrixWorld>(finalizeAction, data.subDatas))
            {
                for (int a = 0; a < data.heights.arr.Length; a++)
                {
                    if (stop != null && stop.stop)
                    {
                        return;
                    }

                    float val      = product.arr[a];
                    float biomeVal = biomeMask != null ? biomeMask.arr[a] : 1;

                    data.heights.arr[a] += val * biomeVal;
                }
            }

            //determining resolutions
            if (stop != null && stop.stop)
            {
                return;
            }
            Interpolation interpolation = data.globals.heightInterpolation;
            int           upscale       = GetUpscale(interpolation);
            int           margins       = data.area.Margins;
            int           matrixRes     = (data.heights.rect.size.x - margins * 2 - 1) * upscale + margins * 2 * upscale + 1;

            //creating upscaled/blurred height matrix
            if (stop != null && stop.stop)
            {
                return;
            }
            Matrix matrix;

            switch (interpolation)
            {
            default: matrix = data.heights; break;

            case Interpolation.Smooth:
                matrix = new Matrix(data.heights);
                MatrixOps.GaussianBlur(matrix, 0.5f);
                break;

            //case Interpolation.Scale2X:
            //	matrix = new Matrix( new CoordRect(data.heights.rect.offset, new Coord(matrixRes)) );
            //	MatrixOps.UpscaleFast(data.heights, matrix);
            //	MatrixOps.GaussianBlur(matrix, 0.5f); //upscaleFast interpolates linear, so each new vert is exactly between the old ones
            //	break;
            //nah, summary effect is better with classic resize
            case Interpolation.Scale4X:
            case Interpolation.Scale2X:
                matrix = new Matrix(new CoordRect(data.heights.rect.offset, new Coord(matrixRes)));
                MatrixOps.Resize(data.heights, matrix);
                break;
            }

            //2Darray resolution and
            int arrRes = matrix.rect.size.x - margins * upscale * 2;

            //splits number (used for SetHeightsDelayLOD and Texture)
            int splitSize = data.globals.heightSplit;
            int numSplits = arrRes / splitSize;

            if (arrRes % splitSize != 0)
            {
                numSplits++;
            }

            //getting apply data
            ApplyType  applyType = data.isDraft ? data.globals.heightDraftApply : data.globals.heightMainApply;
            IApplyData applyData;

            if (applyType == ApplyType.SetHeights)
            {
                float[,] heights2Dfull = new float[arrRes, arrRes];
                matrix.ExportHeights(heights2Dfull, matrix.rect.offset + margins * upscale);
                applyData = new ApplySetData()
                {
                    heights2D = heights2Dfull, height = data.globals.height
                };
            }

            else if (applyType == ApplyType.SetHeightsDelayLOD)
            {
                float[][,] height2DSplits = new float[numSplits][, ];

                int offset = 0;
                for (int i = 0; i < numSplits; i++)
                {
                    int spaceLeft     = arrRes - offset;
                    int currSplitSize = Mathf.Min(splitSize, arrRes - offset);

                    float[,] heights2D = new float[currSplitSize, arrRes];

                    Coord heights2Dcoord = new Coord(
                        matrix.rect.offset.x + margins * upscale,
                        matrix.rect.offset.z + margins * upscale + offset);

                    matrix.ExportHeights(heights2D, heights2Dcoord);

                    height2DSplits[i] = heights2D;

                    offset += currSplitSize;
                }

                applyData = new ApplySplitData()
                {
                    heights2DSplits = height2DSplits, height = data.globals.height
                };
            }

                        #if UNITY_2019_1_OR_NEWER
            else             //if TextureToHeightmap
            {
                byte[] bytes         = new byte[arrRes * arrRes * 4];
                float  ushortEpsilon = 1f / 65535;                //since setheights is using not full ushort range, but range-1
                matrix.ExportRawFloat(bytes, matrix.rect.offset + margins * upscale, new Coord(arrRes, arrRes), mult: 0.5f - ushortEpsilon);
                //not coord(margins) since matrix rect has -margins offset
                //somehow requires halved values

                applyData = new ApplyTexData()
                {
                    res = arrRes, margins = margins, splitSize = splitSize, height = data.globals.height, texBytes = bytes
                };
            }
コード例 #7
0
ファイル: WigglerMini.cs プロジェクト: twobob/TownGenerator
        public override void Generate(TileData data, StopToken stop)
        {
            if (divisions < 1)
            {
                divisions = 1;
            }



            SplineSys src = data.ReadInletProduct(this);

            if (src == null)
            {
                return;
            }

            SplineSys dst = new SplineSys(src);

            if (src == null)
            {
                return;
            }

            if (!enabled)
            {
                data.StoreProduct(this, src);
                return;
            }

            // setup the clamp mask
            var tileLocation = data.area.Coord.ToVector3(1000);
            var tileSize     = new Vector3(1000, 500, 1000);

            // now magically create perfect size slices for this tile.  Thanks Denis.

            if (clampIn)
            {
                dst.Clamp(tileLocation, tileSize);
            }

            // avoid non offsets for our imaginary pair.
            if (FractalStep == 0)
            {
                FractalStep = 1;
            }

            // setup the imaginary offset
            Full_I_Value = new Vector2(FractalStep, FractalStep);


            /// if (data.isDraft) return;
            dst.Subdivide(divisions);



            foreach (var item in dst.lines)
            {
                ActualLength = item.segments.Select(x => x.StartEndLength).Sum();

                if (AutoScale)
                {
                    scalar = averageLength / ActualLength;
                }


                for (int i = 1; i < item.NodesCount - 1; i++)
                {
                    var cur             = item.GetNodePos(i);
                    var nv              = Vector3.zero;
                    var newFull_I_Value = new Vector3(Full_I_Value.x, 0, Full_I_Value.y);
                    var loc             = new Vector3(cur.x, 0, cur.y);

                    if (useNoise)
                    {
                        nv = ReturnWigglyVector3UsingPerlinNoise(wiggliness, cur);
                        // sanity check.

                        // nv = new Vector3(cur.x + ReturnPerlinNoiseValueAtSpot(wiggliness, cur), cur.y, cur.z + ReturnPerlinNoiseValueAtSpot(wiggliness, cur + newFull_I_Value));

                        // var holder = new Vector3(cur.x + ReturnWiggly(wiggliness), cur.y, cur.z + ReturnWiggly(wiggliness));
                    }
                    else
                    {
                        nv = new Vector3(cur.x + ReturnWiggly(wiggliness), cur.y, cur.z + ReturnWiggly(wiggliness));
                        //  var holder = new Vector3(cur.x + ReturnPerlinNoiseValueAtSpot(wiggliness, cur), cur.y, cur.z + ReturnPerlinNoiseValueAtSpot(wiggliness, cur + newFull_I_Value));
                    }
                    item.SetNodePos(i, nv);
                }
            }



            //if (doRelax)
            //{
            //    dst.Relax(blur, ri);
            //}

            // bend nodes

            //if (doBendy)
            //{
            //    for (int i = 0; i < dst.lines.Length; i++)
            //    {
            //        for (int j = 0; j < dst.lines[i].segments.Length; j++)
            //        {
            //            // Skip the very first two.
            //            if (j > 0)
            //            {

            //                Node start = dst.lines[i].segments[j].start;
            //                Vector2 startpos = new Vector2(start.pos.x, start.pos.z);


            //                if (useNoise)
            //                {
            //                    Vector3 place = ReturnWigglyVector3UsingPerlinNoise(bendiness, startpos.V3());

            //                    start.dir =
            //                            (FlipALocationCoin(startpos)) ?
            //                          start.dir + place :
            //                          start.dir - place;

            //                }
            //                else
            //                {
            //                    Vector3 place = ReturnWigglyVector3(bendiness);

            //                    start.dir =
            //                         (FlipALocationCoin(startpos)) ?
            //                       start.dir + place :
            //                       start.dir - place;
            //                }


            //                start.type = nodeType;
            //            }
            //            // Skip the lasties
            //            if (j < dst.lines[i].segments.Length )
            //            {

            //                Node end = dst.lines[i].segments[j].end;
            //                Vector2 endpos = new Vector2(end.pos.x, end.pos.z);

            //                if (useNoise)
            //                {

            //                    Vector3 place = ReturnWigglyVector3UsingPerlinNoise(bendiness, endpos.V3());

            //                    end.dir =
            //                            (FlipALocationCoin(endpos)) ?
            //                          end.dir + place :
            //                          end.dir - place;
            //                }
            //                else
            //                {

            //                    Vector3 place =
            //                    ReturnWigglyVector3(bendiness);
            //                   end.dir =  (FlipALocationCoin(endpos)) ?
            //                   end.dir + place :
            //                   end.dir - place;
            //                }

            //                end.type = nodeType;
            //            }
            //        }
            //    }
            //}

            //if (useNoise)
            //{
            //    for (int i = 0; i < dst.lines.Length; i++)
            //    {
            //        for (int j = 0; j < dst.lines[i].segments.Length; j++)
            //        {
            //            // Skip the very first.
            //            if (j > 0)
            //            {

            //                Node start = dst.lines[i].segments[j].start;
            //                Vector2 startpos = new Vector2(start.pos.x, start.pos.z);
            //                Vector3 mag = ReturnWigglyVector3UsingPerlinNoise(bendiness, startpos.V3());

            //                start.dir =
            //                     (FlipALocationCoin(startpos)) ?
            //                   start.dir + mag :
            //                   start.dir - mag ;

            //                start.type = nodeType;
            //            }
            //            // Skip the last
            //            if (j < dst.lines[i].segments.Length - 1)
            //            {

            //                Node end = dst.lines[i].segments[j].end;
            //                Vector2 endpos = new Vector2(end.pos.x, end.pos.z);
            //                Vector3 mag = ReturnWigglyVector3UsingPerlinNoise(bendiness, endpos.V3());

            //                end.dir =
            //                    (FlipALocationCoin(endpos)) ?
            //                   end.dir + mag :
            //                   end.dir - mag;

            //                end.type = nodeType;
            //            }
            //        }
            //    }
            //}


            // setup the clamp mask
            //  var tileLocation = data.area.Coord.ToVector3(1000);
            // var tileSize = new Vector3(1000, 500, 1000);

            // now magically create perfect size slices for this tile.  Thanks Denis.


            if (clampOUT)
            {
                dst.Clamp(tileLocation, tileSize);
            }

            data.StoreProduct(this, dst);
        }
コード例 #8
0
    public static void OnTileAppliedRenderMeshSplines(TerrainTile tile, TileData data, StopToken stop)
    {
        /*
         *
         * IN THE NEXT SECTION WE HANDLE THE SPLINE MESH RENDERING
         *
         *
         */

        //TODO: Just make a parent holder for all splines on a tile and delete THAT


        //for (int i = tile.transform.childCount - 1; i > 0; i--)
        //{

        //    if (tile.transform.GetChild(i).name.StartsWith("__SPLINE__"))
        //        DestroyImmediate(tile.transform.GetChild(i).gameObject);

        //}

        // we only do this on Main pass and when we actually have made something to process.
        if (data.isDraft)// || !TownGlobalObject.splinesNodesDataForTile.ContainsKey(data.area.Coord))
        {
            return;
        }

        //  int numberOfSplineNodes = 0;


        if (!TownGlobalObject.splinesNodesDataForTile.ContainsKey(data.area.Coord))
        {
            // this is not a mesh spline tile
            return;
        }

        // By this point this should absolutely exist - unless there is no spline data!
        int totalNumberOfListsOfSplineMeshSplines = TownGlobalObject.splinesNodesDataForTile[data.area.Coord].Count;

        // There is nothing in the list
        if (totalNumberOfListsOfSplineMeshSplines == 0)
        {
            return;
        }


        //public void Test(ConcurrentDictionary<string, int> dictionary)
        //{
        //    dictionary.AddOrUpdate("key", 1, (key, current) => current += 2);
        //}



        //  TownHolder.Instance.SplineMeshWallMasterSpawner.SetActive(false);

        List <GameObject> thingsToActivate = new List <GameObject>();



        Coord locality = TownGlobalObject.GetIndexAtCoord(data.area.Coord);



        // Coord offset = locality - data.area.Coord;

        Coord offset = data.area.Coord;

        // SplinePowerExtended

        var DynamicHolder = TownHolder.Instance.MapMagicObjectReference.transform.Find(string.Format("Tile {0},{1}", offset.x, offset.z));


        // For like the 4th time we check this  TODO: Make it part of the Town Instancing
        TownGlobalObject.townsData[locality].TownGameObject ??= new GameObject(TownGlobalObject.townsData[locality].name);


        //create or use the holder now it has the right name.
        var go = TownGlobalObject.townsData[locality].TownGameObject;



        // We walk over the nodes assuming pairs?

        for (int i = 0; i < totalNumberOfListsOfSplineMeshSplines; i++)
        {
            //SplineMesh.Spline();
            TypedSpline newValue = TownGlobalObject.GetSplineList(data.area.Coord)[i];

            // No splines for us...
            if (newValue.nodes.Count == 0)
            {
                continue;
            }


            if ((newValue.nodes[1].Position - newValue.nodes[0].Position).sqrMagnitude == 0)
            {
                continue;
            }

            //  Transform child = null;


            // TODO make this an actual hash and shove it in a table
            // string hash = string.Format("{0}_{1}_{4}_{5}|{2}_{3}", startvec.x, startvec.y, startvec.z, endvec.x, endvec.y, endvec.z);
            //  string fullhash = string.Format("{0}_{1}|{4}_{5}|{2}_{3}", startvec.x, startvec.y, startvec.z, endvec.x, endvec.y, endvec.z);
            string hash = string.Format("__SPLINE__{0}__{2}|{3}__{5}", newValue.nodes[0].Position.x, newValue.nodes[0].Position.y, newValue.nodes[0].Position.z, newValue.nodes[newValue.nodes.Count - 1].Position.x, newValue.nodes[newValue.nodes.Count - 1].Position.y, newValue.nodes[newValue.nodes.Count - 1].Position.z);


            // TODO replace this with a lookup  SOOOOON


            //foreach (Transform children in DynamicHolder.parent)
            //{
            //   // if(child.IsNull())
            //    child ??= children.Find(hash);
            //}

            //// we already rendered this  remove the gmeobject then and do it again.?
            //if (child !=null)
            //    {
            //        var code = child.GetComponent<SplineMesh.Spline>();
            //        bool wipeit = false;
            //        for (int nodeat = 0; nodeat < code.nodes.Count; nodeat++)
            //        {

            //            var thisnode = code.nodes[nodeat];
            //            if (thisnode.Position.y == 0)
            //            {
            //                wipeit = true;
            //            }
            //        }

            //        if (wipeit)
            //        {
            //            DestroyImmediate(child.gameObject);
            //        }
            //        else
            //        {
            //            continue;
            //        }

            //    }



            var newSpline = ((objectRendered)newValue.chosenType) switch
            {
                objectRendered.wall => GameObject.Instantiate(TownHolder.Instance.SplineMeshWallMasterSpawner, DynamicHolder, true),
                objectRendered.fence => GameObject.Instantiate(TownHolder.Instance.SplineMeshFenceMasterSpawner, DynamicHolder, true),
                objectRendered.gatehouse => GameObject.Instantiate(TownHolder.Instance.SplineMeshGatehouseMasterSpawner, DynamicHolder, true),
                _ => GameObject.Instantiate(TownHolder.Instance.SplineMeshWallMasterSpawner, DynamicHolder, true),
            };

            newSpline.name = hash + ((objectRendered)newValue.chosenType).ToString();

            newSpline.GetComponent <SplineMesh.Spline>().nodes = newValue.nodes;


            if (newValue.tryToFloor)
            {
                var scrp = newSpline.AddComponent <AlignNodesToTerrainOnEnable>();

                //  scrp.checkVal = 0.07f;
            }

            thingsToActivate.Add(newSpline);


            // mark it as finally processed. but only if we havent already.

            //  if (!TownGlobalObject.isSplinesMeshRenderedOnTile.ContainsKey(data.area.Coord))
            //       TownGlobalObject.isSplinesMeshRenderedOnTile.Add(data.area.Coord, true);
        }

        // Activate them as a group.
        for (int i = 0; i < thingsToActivate.Count; i++)
        {
            thingsToActivate[i].SetActive(true);
        }
    }
コード例 #9
0
        public ModeBase(
            ILoggerFactory loggerFactory,
            Setups.Databases repos,
            BaseConfig baseConfig,
            StopToken stopToken,
            OverlayConnection overlayConnection,
            ProcessMessage?processMessage = null)
        {
            IClock clock = SystemClock.Instance;

            _logger = loggerFactory.CreateLogger <ModeBase>();
            PokedexData pokedexData = PokedexData.Load();
            ArgsParser  argsParser  = Setups.SetUpArgsParser(repos.UserRepo, pokedexData);

            _processMessage = processMessage ?? (_ => Task.FromResult(false));

            var chats       = new Dictionary <string, IChat>();
            var chatFactory = new ChatFactory(loggerFactory, clock,
                                              repos.UserRepo, repos.TokensBank, repos.SubscriptionLogRepo, repos.LinkedAccountRepo,
                                              overlayConnection);

            foreach (ConnectionConfig connectorConfig in baseConfig.Chat.Connections)
            {
                IChat chat = chatFactory.Create(connectorConfig);
                if (chats.ContainsKey(chat.Name))
                {
                    throw new ArgumentException($"chat name '{chat.Name}' was used multiple times. It must be unique.");
                }
                chats[chat.Name] = chat;
            }
            _chats = chats.ToImmutableDictionary();
            foreach (IChat chat in _chats.Values)
            {
                chat.IncomingMessage += MessageReceived;
            }
            _commandResponders = _chats.Values.ToImmutableDictionary(
                c => c.Name,
                c => (ICommandResponder) new CommandResponder(c));
            _commandProcessors = _chats.Values.ToImmutableDictionary(
                c => c.Name,
                c => Setups.SetUpCommandProcessor(loggerFactory, argsParser, repos, stopToken, c, c,
                                                  pokedexData.KnownSpecies));

            _messagequeueRepo           = repos.MessagequeueRepo;
            _messagelogRepo             = repos.MessagelogRepo;
            _forwardUnprocessedMessages = baseConfig.Chat.ForwardUnprocessedMessages;
            _clock = SystemClock.Instance;

            ILogger <Moderator> moderatorLogger = loggerFactory.CreateLogger <Moderator>();

            IImmutableList <IModerationRule> availableRules = ImmutableList.Create <IModerationRule>(
                new BannedUrlsRule(),
                new SpambotRule(),
                new EmoteRule(),
                new CopypastaRule(clock),
                new UnicodeCharacterCategoryRule()
                );

            foreach (string unknown in baseConfig.DisabledModbotRules.Except(availableRules.Select(rule => rule.Id)))
            {
                moderatorLogger.LogWarning("unknown modbot rule '{UnknownRule}' marked as disabled", unknown);
            }
            IImmutableList <IModerationRule> rules = availableRules
                                                     .Where(rule => !baseConfig.DisabledModbotRules.Contains(rule.Id))
                                                     .ToImmutableList();

            _moderators = _chats.Values.ToImmutableDictionary(
                c => c.Name,
                c => (IModerator) new Moderator(moderatorLogger, c, rules, repos.ModLogRepo, clock));
        }
コード例 #10
0
        public override void Generate(TileData data, StopToken stop)
        {
            if (!enabled)
            {
                return;
            }
            // if (data.isDraft) return;

            if (stop != null && stop.stop)
            {
                return;
            }

            // nodes for spline
            List <Vector3> markers = new List <Vector3>(); //TownGlobalObjectService.TownRequests.Count + TownInitService.__totalCities + 1);

            //data - whatever data
            foreach (var subtown in TownGlobalObject.townsData)
            {
                Town.Geom.Vector2 offsetted = (subtown.Value.Center + subtown.Value.townOffset);

                var offsettedstore = new Vector3(offsetted.x, 499f, offsetted.y);

                if (!markers.Contains(offsettedstore))
                {
                    markers.Add(offsettedstore);
                }
            }

            if (stop != null && stop.stop)
            {
                return;
            }
            // add the first one again, as a node. for a loop.
            markers.Add(markers[0]);


            foreach (var subtown in TownGlobalObject.townsData.Reverse())
            {
                foreach (var road in subtown.Value.Roads)
                {
                    if (road.Count < 1)
                    {
                        continue;
                    }

                    Town.Geom.Vector2 offsettedroad = new Town.Geom.Vector2(
                        road[road.Count - 1].x * TownGlobalObjectService.WorldMultiplier + subtown.Value.townOffset.x,
                        road[road.Count - 1].y * TownGlobalObjectService.WorldMultiplier + subtown.Value.townOffset.y
                        );

                    var store = new Vector3(offsettedroad.x, 499f, offsettedroad.y);

                    if (!markers.Contains(store))
                    {
                        markers.Add(store);
                    }
                }
            }

            if (stop != null && stop.stop)
            {
                return;
            }

            // make some holders
            SplineSys spline = new SplineSys();
            Line      line   = new Line();

            line.SetNodes(markers.ToArray());
            spline.AddLine(line);

            if (stop != null && stop.stop)
            {
                return;
            }

            // setup the clamp mask
            var tileLocation = data.area.Coord.ToVector3(1000);
            var tileSize     = new Vector3(1000, 500, 1000);

            // now magically create perfect size slices for this tile.  Thanks Denis.
            spline.Clamp(tileLocation, tileSize);

            if (stop != null && stop.stop)
            {
                return;
            }

            //save it.
            data.StoreProduct(this, spline);
        }
コード例 #11
0
        // [Val("NoiseRadius")] public float radius = 1000f;

        public override void Generate(TileData data, StopToken stop)
        {
            SplineSys splineSys = data.ReadInletProduct(this);

            if (splineSys == null || !enabled)
            {
                return;
            }

            //stroking
            if (stop != null && stop.stop)
            {
                return;
            }
            MatrixWorld strokeMatrix = new MatrixWorld(data.area.full.rect, data.area.full.worldPos, data.area.full.worldSize, data.globals.height);

            Vector2D center = data.area.active.rect.Center.vector2d;

            SplineMatrixOps.Stroke(splineSys, strokeMatrix, white: true, antialiased: true);

            //spreading
            if (stop != null && stop.stop)
            {
                return;
            }
            MatrixWorld spreadMatrix = Spread(strokeMatrix, width);

            MatrixWorld noiseWorld = new MatrixWorld(spreadMatrix.rect, spreadMatrix.worldPos, spreadMatrix.worldSize);

            noiseWorld.Fill(0);

            CoordRect intersection = CoordRect.Intersected(noiseWorld.rect, spreadMatrix.rect);


            Coord min = intersection.Min; Coord max = intersection.Max;

            Coord coord = new Coord(); //temporary coord to call GetFallof

            // float falloff = 0.6f;


            //   if (noiseFallof)

            {
                for (int x = min.x; x < max.x; x++)
                {
                    for (int z = min.z; z < max.z; z++)
                    {
                        coord.x = x;
                        coord.z = z;

                        int pos = (z - noiseWorld.rect.offset.z) * noiseWorld.rect.size.x + x - noiseWorld.rect.offset.x;  //coord.GetPos
                        if (spreadMatrix.arr[pos] < 0.00001f)
                        {
                            continue;
                        }

                        float falloff = 1;

                        if (noiseFallof)
                        {
                            float maxNoise = 1 - spreadMatrix.arr[pos]; if (spreadMatrix.arr[pos] < 0.5f)
                            {
                                maxNoise = spreadMatrix.arr[pos];
                            }
                            falloff += (data.random.Fractal(x, z, noiseSize) * 2 - 1) * maxNoise * noiseAmount;
                        }

                        noiseWorld.arr[pos] =
                            spreadMatrix.arr[pos]
                            * falloff;
                    }
                }
            }

            //hardness
            if (hardness > 0.0001f)
            {
                float h = 1f / (1f - hardness);
                if (h > 9999)
                {
                    h = 9999;           //infinity if hardness is 1
                }
                noiseWorld.Multiply(h);
            }

            noiseWorld.Clamp01();

            if (stop != null && stop.stop)
            {
                return;
            }
            // data.StoreProduct(this, spreadMatrix);
            data.StoreProduct(this, noiseWorld);
        }
コード例 #12
0
ファイル: TerrainTile.cs プロジェクト: galqawala/Senganget
        private void Generate(Graph graph, TerrainTile tile, DetailLevel det, StopToken stop)
        /// Note that referencing det.task is illegal since task could be changed
        {
            OnBeforeTileGenerate?.Invoke(tile, det.data, stop);

            //do not return (for draft) until the end (apply)
//				if (!stop.stop) graph.CheckClear(det.data, stop);
            if (!stop.stop)
            {
                graph.Generate(det.data, stop);
            }
            if (!stop.stop)
            {
                graph.Finalize(det.data, stop);
            }

            //finalize event
            OnTileFinalized?.Invoke(tile, det.data, stop);

            //flushing products for playmode (all except apply)
            if (MapMagicObject.isPlaying)
            {
                det.data.Clear(clearApply: false);
            }

            //welding (before apply since apply will flush 2d array)
            if (!stop.stop)
            {
                Weld.ReadEdges(det.data, det.edges);
            }
            if (!stop.stop)
            {
                Weld.WeldEdgesInThread(det.edges, tile.mapMagic.tiles, tile.coord, det.data.isDraft);
            }
            if (!stop.stop)
            {
                Weld.WriteEdges(det.data, det.edges);
            }

            //enqueue apply
            if (!MapMagicObject.isPlaying || det.data.isDraft)                     //editor is applied right after the generating is done (drafts apply now in any case)
            //tile.StartApply(tile, det, stop); //could be called in thread
            {
                if (det.data.isDraft)
                {
                    det.coroutine = CoroutineManager.Enqueue(() => ApplyNow(det, stop), Priority + 1000, "ApplyNow " + coord);
                }

                else
                {
                    IEnumerator coroutine = ApplyRoutine(det, stop);
                    det.coroutine = CoroutineManager.Enqueue(coroutine, Priority, "ApplyRoutine " + coord);
                }
            }

            else                     //while the playmode is applied on SwitchLod to avoid unnecessary lags
            {
                det.switchLodCoroutine = CoroutineManager.Enqueue(SwitchLod, Priority - 1, "LodSwitch " + coord);
            }

            det.generateReady = true;
        }
コード例 #13
0
 /// <summary>
 /// Throws OperationCanceledException if <see cref="StopToken"/> has been set
 /// </summary>
 public void ThrowIfStopRequested()
 {
     StopToken.ThrowIfCancellationRequested();
 }
コード例 #14
0
 public DummyMode(ILoggerFactory loggerFactory, BaseConfig baseConfig)
 {
     _logger    = loggerFactory.CreateLogger <DummyMode>();
     _stopToken = new StopToken();
 }
コード例 #15
0
        private void StopEnqueueTask(DetailLevel det, Graph graph, int priority = 0, string name = "Task")
        /// Will stop previous task before running
        {
            if (det.applyMainCoroutines == null)
            {
                det.applyMainCoroutines = new Stack <CoroutineManager.Task>();
            }
            while (det.applyMainCoroutines.Count != 0)
            {
                CoroutineManager.Stop(det.applyMainCoroutines.Pop());
            }

            if (det.switchLodCoroutine != null)
            {
                CoroutineManager.Stop(det.switchLodCoroutine);
            }

            if (det.coroutine != null)
            {
                CoroutineManager.Stop(det.coroutine);
            }

            if (det.task != null && det.task.Active)
            {
                det.stop.stop = true;
                //and forget about this task
            }

            if (det.task == null || !det.task.Enqueued)
            {
                Prepare(graph, this, main);

                det.stop = new StopToken();
                StopToken stop = det.stop;                         //closure var
                det.task = new ThreadManager.Task()
                {
                    action   = () => Generate(graph, this, det, stop),
                    priority = priority,
                    name     = name + " " + coord
                };
                ThreadManager.Enqueue(det.task);
            }
            //do nothing if task enqueued

            det.task.priority = priority;


            //Alternative:

            /*if (det.task != null)
             * {
             *      ThreadManager.Dequeue(det.task); //if enqueued
             *      det.stop.stop = true;			  //if active
             *      //and forget about this task
             * }
             *
             * Prepare(graph, this, main);
             *
             * det.stop = new StopToken();
             * StopToken mainStop = det.stop; //closure var
             * det.task = new ThreadManager.Task() {
             *      action = ()=>Generate(graph, this, main, mainStop),
             *      priority = Priority,
             *      name = "Main " + coord };
             * ThreadManager.Enqueue(det.task);*/
        }
コード例 #16
0
        public override void Generate(TileData data, StopToken stop)
        {
            if (divisions < 1)
            {
                divisions = 1;
            }

            SplineSys src = data.ReadInletProduct(this);


            if (src == null || src.NodesCount == 0)
            {
                return;
            }



            SplineSys bend = new SplineSys(src);

            if (!enabled)
            {
                data.StoreProduct(this, src);
                return;
            }

            // setup the clamp mask
            var tileLocation = data.area.Coord.ToVector3(1000);
            var tileSize     = new Vector3(1000, 500, 1000);

            // now magically create perfect size slices for this tile.  Thanks Denis.

            // avoid non offsets for our imaginary pair.
            if (FractalStep == 0)
            {
                FractalStep = 1;
            }

            // setup the imaginary offset
            Full_I_Value = new Vector2(FractalStep, FractalStep);

            /// if (data.isDraft) return;
            bend.Subdivide(divisions);

            if (clampIN)
            {
                bend.Clamp(tileLocation, tileSize);
            }

            // bend nodes

            for (int i = 0; i < bend.lines.Length; i++)
            {
                for (int j = 0; j < bend.lines[i].segments.Length; j++)
                {
                    // Skip the very first two.
                    if (j > 0)
                    {
                        Node start = bend.lines[i].segments[j].start;
                        start.type = Node.TangentType.auto;
                        Vector2 startpos = new Vector2(start.pos.x, start.pos.z);


                        if (useNoise)
                        {
                            Vector3 place = ReturnWigglyVector3UsingPerlinNoise(bendiness, startpos.V3(), false);

                            start.dir =   //place;
                                        (FlipALocationCoin(startpos)) ?
                                        start.dir +
                                        place :
                                        start.dir
                                        - place;
                        }
                        else
                        {
                            Vector3 place = ReturnWigglyVector3(bendiness);

                            start.dir =// place;
                                        (FlipALocationCoin(startpos)) ?
                                        start.dir +
                                        place :
                                        start.dir
                                        - place;
                        }



                        bend.lines[i].segments[j].start = start;
                    }
                    // Skip the lasties
                    if (j < bend.lines[i].segments.Length)
                    {
                        Node end = bend.lines[i].segments[j].end;
                        end.type = Node.TangentType.auto;
                        Vector2 endpos = new Vector2(end.pos.x, end.pos.z);

                        if (useNoise)
                        {
                            Vector3 place = ReturnWigglyVector3UsingPerlinNoise(bendiness, endpos.V3(), false);

                            end.dir = //place;
                                      (FlipALocationCoin(endpos)) ?
                                      end.dir +
                                      place :
                                      end.dir
                                      - place;
                        }
                        else
                        {
                            Vector3 place =
                                ReturnWigglyVector3(bendiness);
                            end.dir = //place;
                                      (FlipALocationCoin(endpos)) ?
                                      end.dir +
                                      place :
                                      end.dir
                                      - place;
                        }


                        bend.lines[i].segments[j].end = end;
                    }
                }
            }

            bend.Update();
            // now magically create perfect size slices for this tile.  Thanks Denis.
            if (clampOUT)
            {
                bend.Clamp(tileLocation, tileSize);
            }

            data.StoreProduct(this, bend);
            //  }
        }
コード例 #17
0
        private IEnumerator ApplyRoutine(DetailLevel det, StopToken stop)
        {
            if (this == null)
            {
                yield break;
            }

            if (stop == null || !stop.stop)
            {
                while (det.data.ApplyMarksCount != 0)
                {
                    if (stop != null && stop.stop)
                    {
                        yield break;
                    }

                    IApplyData apply = det.data.DequeueApply();                                 //this will remove apply from the list
                    //coroutines guarantee FIFO
                    if (apply is IApplyDataRoutine)
                    {
                        IEnumerator routine = (apply as IApplyDataRoutine).ApplyRoutine(det.terrain);
                        while (true)
                        {
                            if (stop != null && stop.stop)
                            {
                                yield break;
                            }

                            bool move = routine.MoveNext();
                            yield return(null);

                            if (!move)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        apply.Apply(det.terrain);
                        yield return(null);
                    }
                }
            }

            if (stop == null || !(stop.stop || stop.restart))  //can't set ready when restart enqueued
            {
                det.applyReady = true;                         //enabling ready before switching lod (otherwise will leave draft)

                SwitchLod();

                OnTileApplied?.Invoke(this, det.data, stop);

                //if (!mapMagic.IsGenerating()) //won't be called since this couroutine still left
                if (!ThreadManager.IsWorking && CoroutineManager.IsQueueEmpty)
                {
                    OnAllComplete?.Invoke(mapMagic);
                }
            }

            if (stop != null && stop.restart)
            {
                stop.restart = false;
                //Prepare(graph, this, det);
                if (!det.task.Enqueued)
                {
                    ThreadManager.Enqueue(det.task);
                }
            }
        }
コード例 #18
0
        public static void OnGenerateStarted_ResizeDrafts(TerrainTile tile, TileData draftTileData, StopToken stop)
        {
            if (!draftTileData.isDraft)
            {
                return;
            }

            TileData mainTileData = tile.main?.data;

            if (mainTileData == null)
            {
                return;
            }

            if (!lockDatas.TryGetValue(draftTileData, out Dictionary <Lock, LockDataSet> draftLockDatasDict))
            {
                return;
            }
            if (!lockDatas.TryGetValue(mainTileData, out Dictionary <Lock, LockDataSet> mainLockDatasDict))
            {
                return;
            }

            foreach (var kvp in draftLockDatasDict)
            {
                Lock lk = kvp.Key;
                if (!lk.rescaleDraft)
                {
                    continue;
                }

                LockDataSet draftLockData = kvp.Value;
                LockDataSet mainLockData;

                if (!mainLockDatasDict.TryGetValue(lk, out mainLockData))
                {
                    continue;
                }

                LockDataSet.Resize(mainLockData, draftLockData);
            }
        }
コード例 #19
0
        public override void Generate(TileData data, StopToken stop)
        {
            if (!enabled)
            {
                return;
            }
            // if (data.isDraft) return;

            TransitionsList src = data.ReadInletProduct <TransitionsList>(this);

            TransitionsList copy = new TransitionsList(src);

            RemoveAnyBlanksInTransitionListArrayHelper(ref copy);

            // nodes for spline
            List <Vector3> markers = new List <Vector3>(copy.count);

            // setup the clamp mask
            var tileLocation   = data.area.Coord.ToVector3(1000); // x 0 z
            var tileLocationV2 = tileLocation.V2();               // x z
            var tileSize       = new Vector3(1000, 500, 1000);    // TODO: Set this to the mapmagic tile size... not assume 1k

            // now magically create perfect size slices for this tile.  Thanks Denis.
            // dst.Clamp(tileLocation, tileSize);

            //data - whatever data
            foreach (var item in copy.arr)
            {
                Vector2 offsetted = (item.pos.V2() + tileLocationV2);


                var offsettedstore = new Vector3(offsetted.x, item.pos.y, offsetted.y);

                if (!markers.Contains(offsettedstore))
                {
                    try
                    {
                        markers.Add(offsettedstore);
                    }
                    catch (Exception e)
                    {
                        Debug.LogErrorFormat(" Edge case {0} with location {1},{2},{3} and a list of Length {4}", e.Message, offsettedstore.x, offsettedstore.y, offsettedstore.z, markers.Count);
                        // ignore this weird edge case.
                    }
                }
            }


            // add the first one again, as a node. for a loop. and to ensure we have two.. which we will now test for..
            markers.Add(markers[0]);

            // there was one object ONLY...
            if (markers[0] == markers[1])
            {
                // this will just give is an N/A rather than bombing.
                Debug.LogErrorFormat(" Please add at least TWO objects");
                return;
            }

            // make some holders
            SplineSys spline = new SplineSys();
            Line      line   = new Line();

            line.SetNodes(markers.ToArray());
            spline.AddLine(line);


            // now magically create perfect size slices for this tile.  Thanks Denis.
            spline.Clamp(tileLocation, tileSize);


            //save it.
            data.StoreProduct(this, spline);
        }
コード例 #20
0
        public static void OnTileApplied_WriteLocksInApply(TerrainTile tile, TileData tileData, StopToken stop)
        {
            Dictionary <Lock, LockDataSet> lockDatasDict;

            if (!lockDatas.TryGetValue(tileData, out lockDatasDict))
            {
                return;
            }

            Terrain terrain = tile.GetTerrain(tileData.isDraft);

            foreach (LockDataSet lockData in lockDatasDict.Values)
            {
                lockData.WriteInApply(terrain);
            }

            if (!tileData.isDraft)
            {
                lockDatas.Remove(tileData);
            }
            //leaving lock data for draft since it might be currently generating and nearly applyied (and there is no data left!)
        }
コード例 #21
0
ファイル: DualcoreMode.cs プロジェクト: Yoso2/tpp-core
 public DualcoreMode(ILoggerFactory loggerFactory, BaseConfig baseConfig)
 {
     _logger    = loggerFactory.CreateLogger <DualcoreMode>();
     _stopToken = new StopToken();
     _modeBase  = new ModeBase(loggerFactory, baseConfig, _stopToken);
 }
コード例 #22
0
ファイル: VSProMapsOut.cs プロジェクト: AJ213/Awitu
        public static void BlendLayer(Color[][] colors, Area area, MatrixWorld matrix, MatrixWorld biomeMask, float opacity, int maskGroup, int textureChannel, StopToken stop = null)
        {
            Color[] cols       = colors[maskGroup];
            int     splatsSize = area.active.rect.size.x;
            int     fullSize   = area.full.rect.size.x;
            int     margins    = area.Margins;

            for (int x = 0; x < splatsSize; x++)
            {
                for (int z = 0; z < splatsSize; z++)
                {
                    if (stop != null && stop.stop)
                    {
                        return;
                    }

                    int matrixPos = (z + margins) * fullSize + (x + margins);

                    float val = matrix.arr[matrixPos];

                    if (biomeMask != null)                     //no empty biomes in list (so no mask == root biome)
                    {
                        val *= biomeMask.arr[matrixPos];       //if mask is not assigned biome was ignored, so only main outs with mask==null left here
                    }
                    val *= opacity;

                    if (val < 0)
                    {
                        val = 0;
                    }
                    if (val > 1)
                    {
                        val = 1;
                    }

                    int colsPos = z * splatsSize + x;
                    switch (textureChannel)
                    {
                    case 0: cols[colsPos].r += val; break;

                    case 1: cols[colsPos].g += val; break;

                    case 2: cols[colsPos].b += val; break;

                    case 3: cols[colsPos].a += val; break;
                    }
                }
            }
        }
コード例 #23
0
 protected override void startAction()
 {
     Current.TumblerLiftingSFX.Play(playLooping: true, useSpeakers: true);
     StopToken.Register(() => { Current.TumblerLiftingSFX.Stop(); });
 }
コード例 #24
0
        [Val("Spread")]         public float spread    = 10;      //actually the pixel size (in world units) of the lowerest mipmap. Same for draft and main

        public override void Generate(TileData data, StopToken stop)
        {
            MatrixWorld src = data.products.ReadInlet(this);

            if (src == null)
            {
                return;
            }
            if (!enabled)
            {
                data.products[this] = src; return;
            }

            if (stop != null && stop.stop)
            {
                return;
            }
            MatrixWorld dst = new MatrixWorld(src.rect, src.worldPos, src.worldSize);

            MatrixOps.Cavity(src, dst);             //produces the map with range -1 - 1
            dst.Multiply(1f / Mathf.Pow(dst.PixelSize.x, 0.25f));

            float minResolution = data.area.active.worldSize.x / spread;              //area worldsize / (spread = min pixel size)
            float downsample    = Mathf.Log(src.rect.size.x, 2);

            downsample -= Mathf.Log(minResolution, 2);

            if (stop != null && stop.stop)
            {
                return;
            }
            MatrixOps.OverblurMipped(dst, downsample: Mathf.Max(0, downsample), escalate: 1.5f);

            if (stop != null && stop.stop)
            {
                return;
            }
            dst.Multiply(intensity * 100f);

            switch (type)
            {
            case CavityType.Convex: dst.Invert(); break;

            //case CavityType.Concave: break;
            case CavityType.Both: dst.Invert(); dst.Multiply(0.5f); dst.Add(0.5f); break;
            }

            dst.Clamp01();

            //blending 50% map if downsample doesn't allow cavity here (for drafts or low-res)
            if (stop != null && stop.stop)
            {
                return;
            }
            if (downsample < 0f)
            {
                float subsample = -downsample / 4;
                if (subsample > 1)
                {
                    subsample = 1;
                }

                float avg = dst.Average();
                dst.Fill(avg, subsample);
            }

            if (stop != null && stop.stop)
            {
                return;
            }
            data.products[this] = dst;
        }
コード例 #25
0
ファイル: MatrixInitial.cs プロジェクト: couleurs/loopdeleau
        public void SimpleForm(MatrixWorld matrix, Vector2D formOffset, Vector2D formSize, StopToken stop = null)
        {
            Vector2D center = formSize / 2 + formOffset;
            float    radius = Mathf.Min(formSize.x, formSize.z) / 2f;

            Coord min = matrix.rect.Min; Coord max = matrix.rect.Max;

            for (int x = min.x; x < max.x; x++)
            {
                if (stop != null && stop.stop)
                {
                    return;
                }

                for (int z = min.z; z < max.z; z++)
                {
                    //Vector3 worldPos = matrix.PixelToWorld(x,z);

                    Vector2D relativePos = new Vector2D(
                        (float)(x - matrix.rect.offset.x) / (matrix.rect.size.x - 1),
                        (float)(z - matrix.rect.offset.z) / (matrix.rect.size.z - 1));

                    Vector2D worldPos = new Vector2D(
                        relativePos.x * matrix.worldSize.x + matrix.worldPos.x,
                        relativePos.z * matrix.worldSize.z + matrix.worldPos.z);

                    Vector2D formPos = Tile(worldPos, formOffset, formSize, wrap);

                    float val = 0;
                    switch (type)
                    {
                    case FormType.GradientX:
                        val = (formPos.x - formOffset.x) / formSize.x;
                        break;

                    case FormType.GradientZ:
                        val = (formPos.z - formOffset.z) / formSize.z;
                        break;

                    case FormType.Pyramid:
                        float valX = (formPos.x - formOffset.x) / formSize.x; if (valX > 1 - valX)
                        {
                            valX = 1 - valX;
                        }
                        float valZ = (formPos.z - formOffset.z) / formSize.z; if (valZ > 1 - valZ)
                        {
                            valZ = 1 - valZ;
                        }
                        val = valX < valZ? valX * 2 : valZ * 2;
                        break;

                    case FormType.Cone:
                        val = 1 - ((center - formPos).Magnitude) / radius;
                        if (val < 0)
                        {
                            val = 0;
                        }
                        break;
                    }

                    matrix[x, z] = val * intensity;
                }
            }
        }
コード例 #26
0
 protected override void startAction()
 {
     Speech.SayAllOf($"Train glyph {TargetGlyph.Name}.  {TargetGlyph.Instruction_Short}.").Wait();
     MasterSpellLibrary.SpellFeedbackSFX.Play(Volume, true);
     StopToken.Register(() => MasterSpellLibrary.SpellFeedbackSFX.Stop());
 }
コード例 #27
0
ファイル: MatrixInitial.cs プロジェクト: couleurs/loopdeleau
 private static extern float GeneratorNoise200(Matrix matrix, Noise noise, StopToken stop,
                                               int type, float intensity, float size, float detail, float turbulence, float offsetX, float offsetZ,
                                               float worldRectPosX, float worldRectPosZ, float worldRectSizeX, float worldRectSizeZ);
コード例 #28
0
        }                                                      //make some specific tasks (like internal graph creation for function)

        public abstract void Generate(TileData data, StopToken stop);
コード例 #29
0
ファイル: VSProMapsPlaceholder.cs プロジェクト: fanfer/CSharp
 public override void Generate(TileData data, StopToken stop)
 {
 }
コード例 #30
0
            private Token DeserializeNext( byte tokenCode = Byte.MaxValue )
            {
                var tokenPosition = CodePosition;
                if( tokenCode == Byte.MaxValue )
                {
                    tokenCode = FixToken( Buffer.ReadByte() );
                    AlignSize( sizeof(byte) );
                }

                Token tokenItem = null;
                if( tokenCode >= (byte)ExprToken.FirstNative )
                {
                    tokenItem = FindNativeTable( tokenCode );
                }
                else if( tokenCode >= (byte)ExprToken.ExtendedNative )
                {
                    tokenItem = FindNativeTable( (tokenCode - (byte)ExprToken.ExtendedNative) << 8 | Buffer.ReadByte() );
                    AlignSize( sizeof(byte) );
                }
                else switch( tokenCode )
                {
                    #region Cast
                    case (byte)ExprToken.DynamicCast:
                        tokenItem = new DynamicCastToken();
                        break;

                    case (byte)ExprToken.MetaCast:
                        tokenItem = new MetaCastToken();
                        break;

                    case (byte)ExprToken.InterfaceCast:
                        if( Buffer.Version < PrimitveCastVersion )      // UE1
                        {
                            tokenItem = new IntToStringToken();
                        }
                        else
                        {
                            tokenItem = new InterfaceCastToken();
                        }
                        break;

                    // Redefined, can be RotatorToVector!(UE1)
                    case (byte)ExprToken.PrimitiveCast:
                        if( Buffer.Version < PrimitveCastVersion )      // UE1
                        {
                            tokenItem = new RotatorToVectorToken();
                        }
                        else                                            // UE2+
                        {
                            // Next byte represents the CastToken!
                            tokenCode = Buffer.ReadByte();
                            AlignSize( sizeof(byte) );

                            tokenItem = DeserializeCastToken( tokenCode );
                            //tokenitem = new PrimitiveCastToken();
                        }
                        break;
                    #endregion

                    #region Context
                    case (byte)ExprToken.ClassContext:
                        tokenItem = new ClassContextToken();
                        break;

                    case (byte)ExprToken.InterfaceContext:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new ByteToStringToken();
                        }
                        else
                        {
                            tokenItem = new InterfaceContextToken();
                        }
                        break;

                    case (byte)ExprToken.Context:
                        tokenItem = new ContextToken();
                        break;

                    case (byte)ExprToken.StructMember:
                        tokenItem = new StructMemberToken();
                        break;
                    #endregion

                    #region Assigns
                    case (byte)ExprToken.Let:
                        tokenItem = new LetToken();
                        break;

                    case (byte)ExprToken.LetBool:
                        tokenItem = new LetBoolToken();
                        break;

                    case (byte)ExprToken.EndParmValue:
                        tokenItem = new EndParmValueToken();
                        break;

                    // Redefined, can be FloatToBool!(UE1)
                    case (byte)ExprToken.LetDelegate:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new FloatToBoolToken();
                        }
                        else
                        {
                            tokenItem = new LetDelegateToken();
                        }
                        break;

                    // Redefined, can be NameToBool!(UE1)
                    case (byte)ExprToken.Conditional:
                        tokenItem = new ConditionalToken();
                        break;

                    case (byte)ExprToken.Eval: // case (byte)ExprToken.DynArrayFindStruct: case (byte)ExprToken.Conditional:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new NameToBoolToken();
                        }
                        else if( Buffer.Version >= 300 )
                        {
                            tokenItem = new DynamicArrayFindStructToken();
                        }
                        else
                        {
                            tokenItem = new ConditionalToken();
                        }
                        break;
                    #endregion

                    #region Jumps
                    case (byte)ExprToken.Return:
                        tokenItem = new ReturnToken();
                        break;

                    case (byte)ExprToken.ReturnNothing:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new ByteToIntToken();
                        }
                            // Definitely existed since GoW(490)
                        else if( Buffer.Version > 420 && (DeserializedTokens.Count > 0 && !(DeserializedTokens[DeserializedTokens.Count - 1] is ReturnToken)) ) // Should only be done if the last token wasn't Return
                        {
                            tokenItem = new DynamicArrayInsertToken();
                        }
                        else
                        {
                            tokenItem = new ReturnNothingToken();
                        }
                        break;

                    case (byte)ExprToken.GotoLabel:
                        tokenItem = new GoToLabelToken();
                        break;

                    case (byte)ExprToken.Jump:
                        tokenItem = new JumpToken();
                        break;

                    case (byte)ExprToken.JumpIfNot:
                        tokenItem = new JumpIfNotToken();
                        break;

                    case (byte)ExprToken.Switch:
                        tokenItem = new SwitchToken();
                        break;

                    case (byte)ExprToken.Case:
                        tokenItem = new CaseToken();
                        break;

                    case (byte)ExprToken.DynArrayIterator:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new RotatorToStringToken();
                        }
                        else
                        {
                            tokenItem = new ArrayIteratorToken();
                        }
                        break;

                    case (byte)ExprToken.Iterator:
                        tokenItem = new IteratorToken();
                        break;

                    case (byte)ExprToken.IteratorNext:
                        tokenItem = new IteratorNextToken();
                        break;

                    case (byte)ExprToken.IteratorPop:
                        tokenItem = new IteratorPopToken();
                        break;

                    case (byte)ExprToken.FilterEditorOnly:
                        tokenItem = new FilterEditorOnlyToken();
                        break;

                    #endregion

                    #region Variables
                    case (byte)ExprToken.NativeParm:
                        tokenItem = new NativeParameterToken();
                        break;

                    // Referenced variables that are from this function e.g. Local and params
                    case (byte)ExprToken.InstanceVariable:
                        tokenItem = new InstanceVariableToken();
                        break;

                    case (byte)ExprToken.LocalVariable:
                        tokenItem = new LocalVariableToken();
                        break;

                    case (byte)ExprToken.StateVariable:
                        tokenItem = new StateVariableToken();
                        break;

                    // Referenced variables that are default
                    case (byte)ExprToken.UndefinedVariable:
                        #if BORDERLANDS2
                            if( _Container.Package.Build == UnrealPackage.GameBuild.BuildName.Borderlands2 )
                            {
                                tokenItem = new DynamicVariableToken();
                                break;
                            }
                        #endif
                        tokenItem = new UndefinedVariableToken();
                        break;

                    case (byte)ExprToken.DefaultVariable:
                        tokenItem = new DefaultVariableToken();
                        break;

                    // UE3+
                    case (byte)ExprToken.OutVariable:
                        tokenItem = new OutVariableToken();
                        break;

                    case (byte)ExprToken.BoolVariable:
                        tokenItem = new BoolVariableToken();
                        break;

                    // Redefined, can be FloatToInt!(UE1)
                    case (byte)ExprToken.DelegateProperty:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new FloatToIntToken();
                        }
                        else
                        {
                            tokenItem = new DelegatePropertyToken();
                        }
                        break;

                    case (byte)ExprToken.DefaultParmValue:
                        if( Buffer.Version < PrimitveCastVersion )   // StringToInt
                        {
                            tokenItem = new StringToIntToken();
                        }
                        else
                        {
                            tokenItem = new DefaultParameterToken();
                        }
                        break;
                    #endregion

                    #region Misc
                    // Redefined, can be BoolToFloat!(UE1)
                    case (byte)ExprToken.DebugInfo:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new BoolToFloatToken();
                        }
                        else
                        {
                            tokenItem = new DebugInfoToken();
                        }
                        break;

                    case (byte)ExprToken.Nothing:
                        tokenItem = new NothingToken();
                        break;

                    case (byte)ExprToken.EndFunctionParms:
                        tokenItem = new EndFunctionParmsToken();
                        break;

                    case (byte)ExprToken.IntZero:
                        tokenItem = new IntZeroToken();
                        break;

                    case (byte)ExprToken.IntOne:
                        tokenItem = new IntOneToken();
                        break;

                    case (byte)ExprToken.True:
                        tokenItem = new TrueToken();
                        break;

                    case (byte)ExprToken.False:
                        tokenItem = new FalseToken();
                        break;

                    case (byte)ExprToken.NoDelegate:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new IntToFloatToken();
                        }
                        else
                        {
                            tokenItem = new NoDelegateToken();
                        }
                        break;

                        // No value passed to an optional parameter.
                    case (byte)ExprToken.NoParm:
                        tokenItem = new NoParmToken();
                        break;

                    case (byte)ExprToken.NoObject:
                        tokenItem = new NoObjectToken();
                        break;

                    case (byte)ExprToken.Self:
                        tokenItem = new SelfToken();
                        break;

                    // End of state code.
                    case (byte)ExprToken.Stop:
                        tokenItem = new StopToken();
                        break;

                    case (byte)ExprToken.Assert:
                        tokenItem = new AssertToken();
                        break;

                    case (byte)ExprToken.LabelTable:
                        tokenItem = new LabelTableToken();
                        break;

                    case (byte)ExprToken.EndOfScript:   //CastToken.BoolToString:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new BoolToStringToken();
                        }
                        else
                        {
                            tokenItem = new EndOfScriptToken();
                        }
                        break;

                    case (byte)ExprToken.Skip:
                        tokenItem = new SkipToken();
                        break;

                    case (byte)ExprToken.StructCmpEq:
                        tokenItem = new StructCmpEqToken();
                        break;

                    case (byte)ExprToken.StructCmpNE:
                        tokenItem = new StructCmpNeToken();
                        break;

                    case (byte)ExprToken.DelegateCmpEq:
                        tokenItem = new DelegateCmpEqToken();
                        break;

                    case (byte)ExprToken.DelegateFunctionCmpEq:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new IntToBoolToken();
                        }
                        else
                        {
                            tokenItem = new DelegateFunctionCmpEqToken();
                        }
                        break;

                    case (byte)ExprToken.DelegateCmpNE:
                        tokenItem = new DelegateCmpNEToken();
                        break;

                    case (byte)ExprToken.DelegateFunctionCmpNE:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new IntToBoolToken();
                        }
                        else
                        {
                            tokenItem = new DelegateFunctionCmpNEToken();
                        }
                        break;

                    case (byte)ExprToken.InstanceDelegate:
                        tokenItem = new InstanceDelegateToken();
                        break;

                    case (byte)ExprToken.EatString:
                        tokenItem = new EatStringToken();
                        break;

                    case (byte)ExprToken.New:
                        tokenItem = new NewToken();
                        break;

                    case (byte)ExprToken.FunctionEnd: // case (byte)ExprToken.DynArrayFind:
                        if( Buffer.Version < 300 )
                        {
                            tokenItem = new EndOfScriptToken();
                        }
                        else
                        {
                            tokenItem = new DynamicArrayFindToken();
                        }
                        break;

                    case (byte)ExprToken.VarInt:
                    case (byte)ExprToken.VarFloat:
                    case (byte)ExprToken.VarByte:
                    case (byte)ExprToken.VarBool:
                    //case (byte)ExprToken.VarObject:   // See UndefinedVariable
                        if (_Container.Package.Build == UnrealPackage.GameBuild.BuildName.Mass_Effect)
                        {
                            // Don't know what this op code is for.... just know it takes two bytes.
                            tokenItem = new MassEffectUnknownToken();
                        }
                        else
                        {
                            tokenItem = new DynamicVariableToken();
                        }
                        break;
                    #endregion

                    #region Constants
                    case (byte)ExprToken.IntConst:
                        tokenItem = new IntConstToken();
                        break;

                    case (byte)ExprToken.ByteConst:
                        tokenItem = new ByteConstToken();
                        break;

                    case (byte)ExprToken.IntConstByte:
                        tokenItem = new IntConstByteToken();
                        break;

                    case (byte)ExprToken.FloatConst:
                        tokenItem = new FloatConstToken();
                        break;

                    // ClassConst?
                    case (byte)ExprToken.ObjectConst:
                        tokenItem = new ObjectConstToken();
                        break;

                    case (byte)ExprToken.NameConst:
                        tokenItem = new NameConstToken();
                        break;

                    case (byte)ExprToken.StringConst:
                        tokenItem = new StringConstToken();
                        break;

                    case (byte)ExprToken.UniStringConst:
                        tokenItem = new UniStringConstToken();
                        break;

                    case (byte)ExprToken.RotatorConst:
                        tokenItem = new RotatorConstToken();
                        break;

                    case (byte)ExprToken.VectorConst:
                        tokenItem = new VectorConstToken();
                        break;
                    #endregion

                    #region Functions
                    case (byte)ExprToken.FinalFunction:
                        tokenItem = new FinalFunctionToken();
                        break;

                    case (byte)ExprToken.VirtualFunction:
                        tokenItem = new VirtualFunctionToken();
                        break;

                    case (byte)ExprToken.GlobalFunction:
                        tokenItem = new GlobalFunctionToken();
                        break;

                    // Redefined, can be FloatToByte!(UE1)
                    case (byte)ExprToken.DelegateFunction:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new FloatToByteToken();
                        }
                        else
                        {
                            tokenItem = new DelegateFunctionToken();
                        }
                        break;
                    #endregion

                    #region Arrays
                    case (byte)ExprToken.ArrayElement:
                        tokenItem = new ArrayElementToken();
                        break;

                    case (byte)ExprToken.DynArrayElement:
                        tokenItem = new DynamicArrayElementToken();
                        break;

                    case (byte)ExprToken.DynArrayLength:
                        tokenItem = new DynamicArrayLengthToken();
                        break;

                    case (byte)ExprToken.DynArrayInsert:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new BoolToByteToken();
                        }
                        else
                        {
                            tokenItem = new DynamicArrayInsertToken();
                        }
                        break;

                    case (byte)ExprToken.DynArrayInsertItem:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new VectorToStringToken();
                        }
                        else
                        {
                            tokenItem = new DynamicArrayInsertItemToken();
                        }
                        break;

                    // Redefined, can be BoolToInt!(UE1)
                    case (byte)ExprToken.DynArrayRemove:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new BoolToIntToken();
                        }
                        else
                        {
                            tokenItem = new DynamicArrayRemoveToken();
                        }
                        break;

                    case (byte)ExprToken.DynArrayRemoveItem:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new NameToStringToken();
                        }
                        else
                        {
                            tokenItem = new DynamicArrayRemoveItemToken();
                        }
                        break;

                    case (byte)ExprToken.DynArrayAdd:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new FloatToStringToken();
                        }
                        else
                        {
                            tokenItem = new DynamicArrayAddToken();
                        }
                        break;

                    case (byte)ExprToken.DynArrayAddItem:
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            tokenItem = new ObjectToStringToken();
                        }
                        else
                        {
                            tokenItem = new DynamicArrayAddItemToken();
                        }
                        break;

                    case (byte)ExprToken.DynArraySort:
                        tokenItem = new DynamicArraySortToken();
                        break;

                    // See FunctionEnd and Eval
                    /*case (byte)ExprToken.DynArrayFind:
                        break;

                    case (byte)ExprToken.DynArrayFindStruct:
                        break;*/

                    #endregion

                    default:
                    {
                        #region Casts
                        if( Buffer.Version < PrimitveCastVersion )
                        {
                            // No other token was matched. Check if it matches any of the CastTokens
                            // We don't just use PrimitiveCast detection due compatible with UE1 games
                            tokenItem = DeserializeCastToken( tokenCode );
                        }
                        break;
                        #endregion
                    }
                }

                if( tokenItem == null )
                {
                    tokenItem = new UnknownExprToken();
                }

                Console.Out.WriteLine("Token is: "+ tokenCode.ToString("X") + " type: " + tokenItem.GetType().Name + " pos: " + Buffer.Position);

                tokenItem.Decompiler = this;
                tokenItem.RepresentToken = tokenCode;
                tokenItem.Position = tokenPosition;// + (uint)Owner._ScriptOffset;
                tokenItem.StoragePosition = (uint)Buffer.Position - (uint)_Container.ScriptOffset - 1;
                // IMPORTANT:Add before deserialize, due the possibility that the tokenitem might deserialize other tokens as well.
                DeserializedTokens.Add( tokenItem );
                tokenItem.Deserialize( Buffer );
                // Includes all sizes of followed tokens as well! e.g. i = i + 1; is summed here but not i = i +1; (not>>)i ++;
                tokenItem.Size = (ushort)(CodePosition - tokenPosition);
                tokenItem.StorageSize = (ushort)((uint)Buffer.Position - (uint)_Container.ScriptOffset - tokenItem.StoragePosition);
                tokenItem.PostDeserialized();
                return tokenItem;
            }
コード例 #31
0
 public virtual bool Stop()
 {
     StopToken?.Cancel();
     return(true);
 }