Exemple #1
0
        private Shape CreateShape(Container container)
        {
            Shape shape = new StaticShape()
            {
                Fill            = Brushes.Green,
                Stroke          = Brushes.Red,
                StrokeThickness = 5,
                Kind            = AwesomeShape.Geometries.StaticShapeKind.Decagon
            };

            _container = new Container()
            {
                Width  = 200,
                Height = 120
            };

            BindingOperations.SetBinding(shape, Shape.WidthProperty, new Binding("Width")
            {
                Source = _container,
                Mode   = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });

            BindingOperations.SetBinding(shape, Shape.HeightProperty, new Binding("Height")
            {
                Source = _container,
                Mode   = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });
            return(shape);
        }
 public static StaticShape FadePlatform(string position, string rotation, string scale)
 {
     StaticShape ret = new StaticShape("FadePlatform", new Vector(position), new AngAxis(rotation), new Vector(scale));
     ret.dynamicFields.Add("fadeStyle", "Fade");
     ret.dynamicFields.Add("functionality", "trapdoor");
     ret.dynamicFields.Add("Permanent", "0");
     return ret;
 }
 public static StaticShape Help(string position, string rotation, string scale, string helptext)
 {
     StaticShape ret = new StaticShape("HelpBubble", new Vector(position), new AngAxis(rotation), new Vector(scale));
     ret.dynamicFields.Add("text", helptext);
     ret.dynamicFields.Add("triggerRadius", "3");
     ret.dynamicFields.Add("persistTime", "2000");
     ret.dynamicFields.Add("displayOnce", "0");
     return ret;
 }
        public void OnCollision(StaticShape coin, CoinCollector other, Point3F vec, float len)
        {
            ParticleEmitterNode emitterNode = new ParticleEmitterNode {
                DataBlock = Sim.FindObject <ParticleEmitterNodeData>("CoinNode"),
                Emitter   = Sim.FindObject <ParticleEmitterData>("CoinEmitter"),
                Position  = coin.GetPosition()
            };

            emitterNode.RegisterObject();
            emitterNode.Schedule("200", "delete");
            coin.Delete();

            SimGroup Coins = Sim.FindObject <SimGroup>("Coins");

            other.Client.CoinsFound++;
            Core.Functions.MessageAll("MsgCoinPickedUp".Tag(), "-1", other.Client.PlayerName,
                                      other.Client, other.Client.CoinsFound.ToString(), other.Client.Kills.ToString(), other.Client.Deaths.ToString());
            if (Coins is null || Coins.GetCount() > 0)
            {
                return;
            }
            CoinCollectionGameConnection winnerClient =
                Core.Objects.ClientGroup.GetObject(0).As <CoinCollectionGameConnection>();

            List <CoinCollectionGameConnection> loserClients = new List <CoinCollectionGameConnection>();

            for (uint i = 1; i < Core.Objects.ClientGroup.GetCount(); i++)
            {
                var client = Core.Objects.ClientGroup.GetObject(i).As <CoinCollectionGameConnection>();
                if (client.CoinsFound > winnerClient.CoinsFound)
                {
                    loserClients.Add(winnerClient);
                    winnerClient = client;
                }
                else
                {
                    loserClients.Add(client);
                }
            }

            loserClients.ForEach(client =>
                                 Global.CommandToClient(
                                     client,
                                     "ShowDefeat".Tag(),
                                     client.CoinsFound.ToString()
                                     ));

            Global.CommandToClient(
                winnerClient,
                "ShowVictory".Tag(),
                winnerClient.CoinsFound.ToString());
        }
        public string ExecuteTemplate(string liquidSource, dynamic model)
        {
            EnsureTemplateConfigured();

            var templateModel = new StaticShape(model);

            var liquidTemplate = _cacheService.Get(liquidSource, () => Template.Parse(liquidSource));

            return(liquidTemplate.Render(new RenderParameters
            {
                LocalVariables = Hash.FromAnonymousObject(new { Model = templateModel }),
                RethrowErrors = true
            }));
        }
Exemple #6
0
        public void Render(ViewContext context, TextWriter writer)
        {
            var filename = context.HttpContext.Server.MapPath(ViewPath);

            var scope         = new ScriptScopeImpl(ViewPath);
            var orchardGlobal = new Dictionary <string, dynamic>();

            orchardGlobal["VIEW_CONTEXT"] = context;
            orchardGlobal["MODEL"]        = new StaticShape(context.ViewData.Model);
            scope.SetVariable("_ORCHARD", orchardGlobal);

            var output = _phpRuntime.ExecuteFile(filename, scope);

            writer.Write(output);
        }
        public static string Display(Context context, dynamic input)
        {
            if (input == null || !(input is StaticShape))
            {
                return(string.Empty);
            }

            StaticShape shape = input;
            var         wc    = HttpContext.Current.GetWorkContext();

            if (wc == null)
            {
                return(string.Empty);
            }

            return(wc.Resolve <IShapeDisplay>().Display(shape.Shape));
        }
Exemple #8
0
        public string ExecuteTemplate(string liquidSource, dynamic model, ITemplateRenderingContext templateExecutionContext)
        {
            EnsureTemplateConfigured();

            model.WorkContext = _wca.GetContext();
            var templateModel = new StaticShape(model);

            var liquidTemplate     = _cacheService.Get(liquidSource, () => Template.Parse(liquidSource));
            var localVariablesHash = Hash.FromAnonymousObject(new { Model = templateModel });

            localVariablesHash[Constants.TemplateRenderingContextKey] = templateExecutionContext;
            return(liquidTemplate.Render(new RenderParameters
            {
                LocalVariables = localVariablesHash,
                RethrowErrors = true
            }));
        }
        public static string Display(Context context, dynamic input)
        {
            if (input == null || !(input is StaticShape))
            {
                return(string.Empty);
            }

            StaticShape shape = input;

            var wc = context.GetWorkContext();

            // Checking if the shape is displayed multiple times. If yes it can be legitimate (although rare) but
            // can also indicate unwanted recursion, so capping it.
            if (shape.Shape.DisplayedCount == null)
            {
                shape.Shape.DisplayedCount = 0;
            }

            if (shape.Shape.DisplayedCount >= Constants.MaxAllowedShapeDisplayCount)
            {
                wc.LogSecurityNotificationWithContext(typeof(DisplayFilter), "Too many displays of the same shape prevented.");

                return(string.Empty);
            }

            shape.Shape.DisplayedCount++;

            if (!context.ShapeIsWithinAllowedRecursionDepth(shape.Metadata.Type))
            {
                wc.LogSecurityNotificationWithContext(typeof(DisplayFilter), "Too many recursive shape displays prevented.");

                return(string.Empty);
            }

            context.AddCurrentShapeAsParentToShape((IShape)shape.Shape);

            return(wc.Resolve <IShapeDisplay>().Display(shape.Shape));
        }
Exemple #10
0
        /// <summary>
        /// Open the specified WFile and load all the scenery objects into the viewer.
        /// If the file doesn't exist, then return an empty WorldFile object.
        /// </summary>
        /// <param name="visible">Tiles adjacent to the current visible tile may not be modelled.
        /// This flag decides whether a missing file leads to a warning message.</param>
        public WorldFile(Viewer viewer, int tileX, int tileZ, bool visible)
        {
            Viewer = viewer;
            TileX  = tileX;
            TileZ  = tileZ;

            var cancellation = Viewer.LoaderProcess.CancellationToken;

            // determine file path to the WFile at the specified tile coordinates
            var WFileName = WorldFileNameFromTileCoordinates(tileX, tileZ);
            var WFilePath = viewer.Simulator.RoutePath + @"\World\" + WFileName;

            // if there isn't a file, then return with an empty WorldFile object
            if (!File.Exists(WFilePath))
            {
                if (visible)
                {
                    Trace.TraceWarning("World file missing - {0}", WFilePath);
                }
                return;
            }

            // read the world file
            var WFile = new Orts.Formats.Msts.WorldFile(WFilePath);

            // check for existence of world file in OpenRails subfolder

            WFilePath = viewer.Simulator.RoutePath + @"\World\Openrails\" + WFileName;
            if (File.Exists(WFilePath))
            {
                // We have an OR-specific addition to world file
                WFile.InsertORSpecificData(WFilePath);
            }



            // to avoid loop checking for every object this pre-check is performed
            bool containsMovingTable = false;

            if (Program.Simulator.MovingTables != null)
            {
                foreach (var movingTable in Program.Simulator.MovingTables)
                {
                    if (movingTable.WFile == WFileName)
                    {
                        containsMovingTable = true;
                        break;
                    }
                }
            }

            // create all the individual scenery objects specified in the WFile
            foreach (var worldObject in WFile.Tr_Worldfile)
            {
                if (worldObject.StaticDetailLevel > viewer.Settings.WorldObjectDensity)
                {
                    continue;
                }

                // If the loader has been asked to temrinate, bail out early.
                if (cancellation.IsCancellationRequested)
                {
                    break;
                }

                // Get the position of the scenery object into ORTS coordinate space.
                WorldPosition worldMatrix;
                if (worldObject.Matrix3x3 != null && worldObject.Position != null)
                {
                    worldMatrix = WorldPositionFromMSTSLocation(WFile.TileX, WFile.TileZ, worldObject.Position, worldObject.Matrix3x3);
                }
                else if (worldObject.QDirection != null && worldObject.Position != null)
                {
                    worldMatrix = WorldPositionFromMSTSLocation(WFile.TileX, WFile.TileZ, worldObject.Position, worldObject.QDirection);
                }
                else
                {
                    Trace.TraceWarning("{0} scenery object {1} is missing Matrix3x3 and QDirection", WFileName, worldObject.UID);
                    continue;
                }

                var shadowCaster = (worldObject.StaticFlags & (uint)StaticFlag.AnyShadow) != 0 || viewer.Settings.ShadowAllShapes;
                var animated     = (worldObject.StaticFlags & (uint)StaticFlag.Animate) != 0;
                var global       = (worldObject is TrackObj) || (worldObject is HazardObj) || (worldObject.StaticFlags & (uint)StaticFlag.Global) != 0;

                // TransferObj have a FileName but it is not a shape, so we need to avoid sanity-checking it as if it was.
                var fileNameIsNotShape = (worldObject is TransferObj || worldObject is HazardObj);

                // Determine the file path to the shape file for this scenery object and check it exists as expected.
                var shapeFilePath = fileNameIsNotShape || String.IsNullOrEmpty(worldObject.FileName) ? null : global ? viewer.Simulator.BasePath + @"\Global\Shapes\" + worldObject.FileName : viewer.Simulator.RoutePath + @"\Shapes\" + worldObject.FileName;
                if (shapeFilePath != null)
                {
                    shapeFilePath = Path.GetFullPath(shapeFilePath);
                    if (!File.Exists(shapeFilePath))
                    {
                        Trace.TraceWarning("{0} scenery object {1} with StaticFlags {3:X8} references non-existent {2}", WFileName, worldObject.UID, shapeFilePath, worldObject.StaticFlags);
                        shapeFilePath = null;
                    }
                }

                if (shapeFilePath != null && File.Exists(shapeFilePath + "d"))
                {
                    var shape = new ShapeDescriptorFile(shapeFilePath + "d");
                    if (shape.shape.ESD_Bounding_Box != null)
                    {
                        var min       = shape.shape.ESD_Bounding_Box.Min;
                        var max       = shape.shape.ESD_Bounding_Box.Max;
                        var transform = Matrix.Invert(worldMatrix.XNAMatrix);
                        // Not sure if this is needed, but it is to correct for center-of-gravity being not the center of the box.
                        //transform.M41 += (max.X + min.X) / 2;
                        //transform.M42 += (max.Y + min.Y) / 2;
                        //transform.M43 += (max.Z + min.Z) / 2;
                        BoundingBoxes.Add(new BoundingBox(transform, new Vector3((max.X - min.X) / 2, (max.Y - min.Y) / 2, (max.Z - min.Z) / 2), worldMatrix.XNAMatrix.Translation.Y));
                    }
                }

                try
                {
                    if (worldObject.GetType() == typeof(TrackObj))
                    {
                        var trackObj = (TrackObj)worldObject;
                        // Switch tracks need a link to the simulator engine so they can animate the points.
                        var trJunctionNode = trackObj.JNodePosn != null?viewer.Simulator.TDB.GetTrJunctionNode(TileX, TileZ, (int)trackObj.UID) : null;

                        // We might not have found the junction node; if so, fall back to the static track shape.
                        if (trJunctionNode != null)
                        {
                            if (viewer.Simulator.UseSuperElevation > 0)
                            {
                                SuperElevationManager.DecomposeStaticSuperElevation(viewer, dTrackList, trackObj, worldMatrix, TileX, TileZ, shapeFilePath);
                            }
                            sceneryObjects.Add(new SwitchTrackShape(viewer, shapeFilePath, worldMatrix, trJunctionNode));
                        }
                        else
                        {
                            //if want to use super elevation, we will generate tracks using dynamic tracks
                            if (viewer.Simulator.UseSuperElevation > 0 &&
                                SuperElevationManager.DecomposeStaticSuperElevation(viewer, dTrackList, trackObj, worldMatrix, TileX, TileZ, shapeFilePath))
                            {
                                //var success = SuperElevation.DecomposeStaticSuperElevation(viewer, dTrackList, trackObj, worldMatrix, TileX, TileZ, shapeFilePath);
                                //if (success == 0) sceneryObjects.Add(new StaticTrackShape(viewer, shapeFilePath, worldMatrix));
                            }
                            //otherwise, use shapes
                            else if (!containsMovingTable)
                            {
                                sceneryObjects.Add(new StaticTrackShape(viewer, shapeFilePath, worldMatrix));
                            }
                            else
                            {
                                var found = false;
                                foreach (var movingTable in Program.Simulator.MovingTables)
                                {
                                    if (worldObject.UID == movingTable.UID && WFileName == movingTable.WFile)
                                    {
                                        found = true;
                                        if (movingTable is Simulation.Turntable)
                                        {
                                            var turntable = movingTable as Simulation.Turntable;
                                            turntable.ComputeCenter(worldMatrix);
                                            var startingY = Math.Asin(-2 * (worldObject.QDirection.A * worldObject.QDirection.C - worldObject.QDirection.B * worldObject.QDirection.D));
                                            sceneryObjects.Add(new TurntableShape(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None, turntable, startingY));
                                        }
                                        else
                                        {
                                            var transfertable = movingTable as Simulation.Transfertable;
                                            transfertable.ComputeCenter(worldMatrix);
                                            sceneryObjects.Add(new TransfertableShape(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None, transfertable));
                                        }
                                        break;
                                    }
                                }
                                if (!found)
                                {
                                    sceneryObjects.Add(new StaticTrackShape(viewer, shapeFilePath, worldMatrix));
                                }
                            }
                        }
                        if (viewer.Simulator.Settings.Wire == true && viewer.Simulator.TRK.Tr_RouteFile.Electrified == true &&
                            worldObject.StaticDetailLevel != 2 &&   // Make it compatible with routes that use 'HideWire', a workaround for MSTS that
                            worldObject.StaticDetailLevel != 3      // allowed a mix of electrified and non electrified track see http://msts.steam4me.net/tutorials/hidewire.html
                            )
                        {
                            int success = Wire.DecomposeStaticWire(viewer, dTrackList, trackObj, worldMatrix);
                            //if cannot draw wire, try to see if it is converted. modified for DynaTrax
                            if (success == 0 && trackObj.FileName.Contains("Dyna"))
                            {
                                Wire.DecomposeConvertedDynamicWire(viewer, dTrackList, trackObj, worldMatrix);
                            }
                        }
                    }
                    else if (worldObject.GetType() == typeof(DyntrackObj))
                    {
                        if (viewer.Simulator.Settings.Wire == true && viewer.Simulator.TRK.Tr_RouteFile.Electrified == true)
                        {
                            Wire.DecomposeDynamicWire(viewer, dTrackList, (DyntrackObj)worldObject, worldMatrix);
                        }
                        // Add DyntrackDrawers for individual subsections
                        if (viewer.Simulator.UseSuperElevation > 0 && SuperElevationManager.UseSuperElevationDyn(viewer, dTrackList, (DyntrackObj)worldObject, worldMatrix))
                        {
                            SuperElevationManager.DecomposeDynamicSuperElevation(viewer, dTrackList, (DyntrackObj)worldObject, worldMatrix);
                        }
                        else
                        {
                            DynamicTrack.Decompose(viewer, dTrackList, (DyntrackObj)worldObject, worldMatrix);
                        }
                    } // end else if DyntrackObj
                    else if (worldObject.GetType() == typeof(ForestObj))
                    {
                        if (!(worldObject as ForestObj).IsYard)
                        {
                            forestList.Add(new ForestViewer(viewer, (ForestObj)worldObject, worldMatrix));
                        }
                    }
                    else if (worldObject.GetType() == typeof(SignalObj))
                    {
                        sceneryObjects.Add(new SignalShape(viewer, (SignalObj)worldObject, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None));
                    }
                    else if (worldObject.GetType() == typeof(TransferObj))
                    {
                        sceneryObjects.Add(new TransferShape(viewer, (TransferObj)worldObject, worldMatrix));
                    }
                    else if (worldObject.GetType() == typeof(LevelCrossingObj))
                    {
                        sceneryObjects.Add(new LevelCrossingShape(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None, (LevelCrossingObj)worldObject));
                    }
                    else if (worldObject.GetType() == typeof(HazardObj))
                    {
                        var h = HazzardShape.CreateHazzard(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None, (HazardObj)worldObject);
                        if (h != null)
                        {
                            sceneryObjects.Add(h);
                        }
                    }
                    else if (worldObject.GetType() == typeof(SpeedPostObj))
                    {
                        sceneryObjects.Add(new SpeedPostShape(viewer, shapeFilePath, worldMatrix, (SpeedPostObj)worldObject));
                    }
                    else if (worldObject.GetType() == typeof(CarSpawnerObj))
                    {
                        if (Program.Simulator.CarSpawnerLists != null && ((CarSpawnerObj)worldObject).ListName != null)
                        {
                            ((CarSpawnerObj)worldObject).CarSpawnerListIdx = Program.Simulator.CarSpawnerLists.FindIndex(x => x.ListName == ((CarSpawnerObj)worldObject).ListName);
                            if (((CarSpawnerObj)worldObject).CarSpawnerListIdx < 0 || ((CarSpawnerObj)worldObject).CarSpawnerListIdx > Program.Simulator.CarSpawnerLists.Count - 1)
                            {
                                ((CarSpawnerObj)worldObject).CarSpawnerListIdx = 0;
                            }
                        }
                        else
                        {
                            ((CarSpawnerObj)worldObject).CarSpawnerListIdx = 0;
                        }
                        carSpawners.Add(new RoadCarSpawner(viewer, worldMatrix, (CarSpawnerObj)worldObject));
                    }
                    else if (worldObject.GetType() == typeof(SidingObj))
                    {
                        sidings.Add(new TrItemLabel(viewer, worldMatrix, (SidingObj)worldObject));
                    }
                    else if (worldObject.GetType() == typeof(PlatformObj))
                    {
                        platforms.Add(new TrItemLabel(viewer, worldMatrix, (PlatformObj)worldObject));
                    }
                    else if (worldObject.GetType() == typeof(StaticObj))
                    {
                        //          preTestShape for lookup if it is an animated clock shape with subobjects named as clock hands
                        StaticShape preTestShape    = (new StaticShape(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None));
                        var         animNodes       = preTestShape.SharedShape.Animations?[0]?.anim_nodes ?? new List <anim_node>();
                        var         isAnimatedClock = animNodes.Exists(node => Regex.IsMatch(node.Name, @"^orts_[hmsc]hand_clock", RegexOptions.IgnoreCase));
                        if (isAnimatedClock)
                        {
                            sceneryObjects.Add(new AnalogClockShape(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None));
                        }
                        else if (animated)
                        {
                            sceneryObjects.Add(new AnimatedShape(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None));
                        }
                        else
                        {
                            sceneryObjects.Add(new StaticShape(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None));
                        }
                    }
                    else if (worldObject.GetType() == typeof(PickupObj))
                    {
                        sceneryObjects.Add(new FuelPickupItemShape(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None, (PickupObj)worldObject));
                        PickupList.Add((PickupObj)worldObject);
                    }
                    else // It's some other type of object - not one of the above.
                    {
                        sceneryObjects.Add(new StaticShape(viewer, shapeFilePath, worldMatrix, shadowCaster ? ShapeFlags.ShadowCaster : ShapeFlags.None));
                    }
                }
                catch (Exception error)
                {
                    Trace.WriteLine(new FileLoadException(String.Format("{0} scenery object {1} failed to load", worldMatrix, worldObject.UID), error));
                }
            }

            // Check if there are activity restricted speedposts to be loaded

            if (Viewer.Simulator.ActivityRun != null && Viewer.Simulator.Activity.Tr_Activity.Tr_Activity_File.ActivityRestrictedSpeedZones != null)
            {
                foreach (TempSpeedPostItem tempSpeedItem in Viewer.Simulator.ActivityRun.TempSpeedPostItems)
                {
                    if (tempSpeedItem.WorldPosition.TileX == TileX && tempSpeedItem.WorldPosition.TileZ == TileZ)
                    {
                        if (Viewer.SpeedpostDatFile == null)
                        {
                            Trace.TraceWarning(String.Format("{0} missing; speed posts for temporary speed restrictions in tile {1} {2} will not be visible.", Viewer.Simulator.RoutePath + @"\speedpost.dat", TileX, TileZ));
                            break;
                        }
                        else
                        {
                            sceneryObjects.Add(new StaticShape(viewer,
                                                               tempSpeedItem.IsWarning ? Viewer.SpeedpostDatFile.TempSpeedShapeNames[0] : (tempSpeedItem.IsResume ? Viewer.SpeedpostDatFile.TempSpeedShapeNames[2] : Viewer.SpeedpostDatFile.TempSpeedShapeNames[1]),
                                                               tempSpeedItem.WorldPosition, ShapeFlags.None));
                        }
                    }
                }
            }

            // Model instancing requires feature level 9_3 or higher.
            if (Viewer.Settings.ModelInstancing && Viewer.Settings.IsDirectXFeatureLevelIncluded(ORTS.Settings.UserSettings.DirectXFeature.Level9_3))
            {
                // Instancing collapsed multiple copies of the same model in to a single set of data (the normal model
                // data, plus a list of position information for each copy) and then draws them in a single batch.
                var instances = new Dictionary <string, List <StaticShape> >();
                foreach (var shape in sceneryObjects)
                {
                    // Only allow StaticShape and StaticTrackShape instances for now.
                    if (shape.GetType() != typeof(StaticShape) && shape.GetType() != typeof(StaticTrackShape))
                    {
                        continue;
                    }

                    // Must have a file path so we can collapse instances on something.
                    var path = shape.SharedShape.FilePath;
                    if (path == null)
                    {
                        continue;
                    }

                    if (path != null && !instances.ContainsKey(path))
                    {
                        instances.Add(path, new List <StaticShape>());
                    }

                    if (path != null)
                    {
                        instances[path].Add(shape);
                    }
                }
                foreach (var path in instances.Keys)
                {
                    if (instances[path].Count >= MinimumInstanceCount)
                    {
                        var sharedInstance = new SharedStaticShapeInstance(Viewer, path, instances[path]);
                        foreach (var model in instances[path])
                        {
                            sceneryObjects.Remove(model);
                        }
                        sceneryObjects.Add(sharedInstance);
                    }
                }
            }

            if (viewer.Simulator.UseSuperElevation > 0)
            {
                SuperElevationManager.DecomposeStaticSuperElevation(Viewer, dTrackList, TileX, TileZ);
            }
            if (Viewer.World.Sounds != null)
            {
                Viewer.World.Sounds.AddByTile(TileX, TileZ);
            }
        }
Exemple #11
0
        public SimGroup Import(string filename)
        {
            var rawMission = File.ReadLines(filename).ToList();

            rawMission = rawMission.GetRange(rawMission.IndexOf("//--- OBJECT WRITE BEGIN ---"), rawMission.IndexOf("//--- OBJECT WRITE END ---") - rawMission.IndexOf("//--- OBJECT WRITE BEGIN ---") + 1);
            SimObject curobj = null;
            var       status = new ImportStatus();

            int curpos = 0;

            int bracestartindex = 0;
            int braceendindex   = 0;

            int braceskip = 0;

            for (var i = 0; i < rawMission.Count; i++)
            {
                var a = rawMission[i];
                rawMission[i] = a.Trim();
                if (rawMission[i].Contains("//"))
                {
                    rawMission[i] = rawMission[i].Split(new string[] { "//" }, StringSplitOptions.None)[0];
                }
            }

            status = ImportStatus.Class;

            foreach (var line in rawMission)
            {
                string l = line;

                if (l.Contains("new") && status == ImportStatus.Class)
                {
                    var raw      = l.Split(' ')[1];
                    var objclass = raw.Substring(0, raw.IndexOf('('));
                    var name     = raw.Substring(raw.IndexOf('(') + 1, raw.IndexOf(')') - raw.IndexOf('(') - 1);
                    switch (objclass)
                    {
                    case "SimGroup":
                        curobj = new SimGroup()
                        {
                            objname = name
                        };
                        break;

                    case "ScriptObject":
                        curobj = new ScriptObject(name);
                        break;

                    case "Sky":
                        curobj = new Sky()
                        {
                            objname = name
                        };
                        break;

                    case "Sun":
                        curobj = new Sun()
                        {
                            objname = name
                        };
                        break;

                    case "Item":
                        curobj = new Item()
                        {
                            objname = name
                        };
                        break;

                    case "InteriorInstance":
                        curobj = new InteriorInstance()
                        {
                            objname = name
                        };
                        break;

                    case "Path":
                        curobj = new Path()
                        {
                            objname = name
                        };
                        break;

                    case "Marker":
                        curobj = new Marker()
                        {
                            objname = name
                        };
                        break;

                    case "PathedInterior":
                        curobj = new PathedInterior()
                        {
                            objname = name
                        };
                        break;

                    case "Trigger":
                        curobj = new Trigger()
                        {
                            objname = name
                        };
                        break;

                    case "StaticShape":
                        curobj = new StaticShape()
                        {
                            objname = name
                        };
                        break;

                    default:
                        curobj = new SimObject()
                        {
                            objname = name
                        };
                        break;
                    }
                    status = ImportStatus.BracesStart;
                }

                if (status == ImportStatus.BracesStart)
                {
                    if (l.Contains("{"))
                    {
                        bracestartindex = curpos;
                        status          = ImportStatus.BracesEnd;
                    }
                }
                if (status == ImportStatus.BracesEnd)
                {
                    if (l.Contains("{"))
                    {
                        braceskip++;
                    }

                    if (l.Contains("};"))
                    {
                        if (braceskip == 1)
                        {
                            braceendindex = curpos;
                            status        = ImportStatus.Children;
                            var childlines = rawMission.GetRange(bracestartindex + 1, braceendindex - bracestartindex - 1);
                            Import(childlines, ref curobj);
                        }
                        braceskip--;
                    }
                }
                curpos++;
            }

            return(curobj as SimGroup);
        }
Exemple #12
0
        void Import(List <string> lines, ref SimObject parent)
        {
            SimObject curobj = null;
            var       status = new ImportStatus();

            status = ImportStatus.Properties;

            int bracestartindex = 0;
            int braceendindex   = 0;
            int curpos          = 0;

            int braceskip = 0;

            foreach (var line in lines)
            {
                string l = line;

                if (l.Contains("new") && status == ImportStatus.Properties)
                {
                    var raw      = l.Split(' ')[1];
                    var objclass = raw.Substring(0, raw.IndexOf('('));
                    var name     = raw.Substring(raw.IndexOf('(') + 1, raw.IndexOf(')') - raw.IndexOf('(') - 1);
                    switch (objclass)
                    {
                    case "SimGroup":
                        curobj = new SimGroup()
                        {
                            objname = name
                        };
                        break;

                    case "ScriptObject":
                        curobj = new ScriptObject(name);
                        break;

                    case "Sky":
                        curobj = new Sky()
                        {
                            objname = name
                        };
                        break;

                    case "Sun":
                        curobj = new Sun()
                        {
                            objname = name
                        };
                        break;

                    case "Item":
                        curobj = new Item()
                        {
                            objname = name
                        };
                        break;

                    case "InteriorInstance":
                        curobj = new InteriorInstance()
                        {
                            objname = name
                        };
                        break;

                    case "Path":
                        curobj = new Path()
                        {
                            objname = name
                        };
                        break;

                    case "Marker":
                        curobj = new Marker()
                        {
                            objname = name
                        };
                        break;

                    case "PathedInterior":
                        curobj = new PathedInterior()
                        {
                            objname = name
                        };
                        break;

                    case "Trigger":
                        curobj = new Trigger()
                        {
                            objname = name
                        };
                        break;

                    case "StaticShape":
                        curobj = new StaticShape()
                        {
                            objname = name
                        };
                        break;

                    default:
                        curobj = new SimObject()
                        {
                            objname = name
                        };
                        break;
                    }
                    status = ImportStatus.BracesStart;
                    (parent as SimGroup).Add(curobj);
                }

                if (status == ImportStatus.BracesStart)
                {
                    if (l.Contains("{"))
                    {
                        bracestartindex = curpos;
                        status          = ImportStatus.BracesEnd;
                    }
                }
                if (status == ImportStatus.BracesEnd)
                {
                    if (l.Contains("{"))
                    {
                        braceskip++;
                    }

                    if (l.Contains("};"))
                    {
                        if (braceskip == 1)
                        {
                            braceendindex = curpos;
                            status        = ImportStatus.Children;
                            var childlines = lines.GetRange(bracestartindex + 1, braceendindex - bracestartindex - 1);
                            Import(childlines, ref curobj);
                            status = ImportStatus.Properties;
                        }
                        braceskip--;
                    }
                }

                if (l.Contains("=") && status == ImportStatus.Properties)
                {
                    var property = l.Substring(0, l.IndexOf("=")).Trim();
                    var value    = l.Substring(l.IndexOf("=") + 1, l.IndexOf(";") - l.IndexOf("=") - 1).Trim();
                    value            = value.Trim('"');
                    parent[property] = value;
                }
                curpos++;
            }
        }
        private dynamic RunPhpExecutor(Action <RequestContext> executor, ScriptScope scope)
        {
            try
            {
                var workContext = _wcaWork.Value.GetContext();

                using (var requestContext = RequestContext.Initialize(ApplicationContext.Default, workContext.HttpContext.ApplicationInstance.Context))
                {
                    var scriptContext = requestContext.ScriptContext;
                    using (scriptContext.OutputStream = new MemoryStream())
                    {
                        using (scriptContext.Output = new StreamWriter(scriptContext.OutputStream))
                        {
                            var assemblyLoader = scriptContext.ApplicationContext.AssemblyLoader;
                            assemblyLoader.Load(typeof(PhpHash).Assembly, null); // PhpNetClassLibrary.dll

                            foreach (var assembly in scope.Assemblies)
                            {
                                assemblyLoader.Load(assembly, null);
                            }

                            var orchardGlobal = new Dictionary <string, dynamic>();
                            orchardGlobal["WORK_CONTEXT"]     = workContext;
                            orchardGlobal["ORCHARD_SERVICES"] = workContext.Resolve <IOrchardServices>();
                            orchardGlobal["LAYOUT"]           = new StaticShape(workContext.Layout);

                            var existing = scope.GetVariable("_ORCHARD");
                            if (existing != null)
                            {
                                if (!(existing is IDictionary <string, object>))
                                {
                                    throw new ArgumentException("The $_ORCHARD superglobal variable should be an IDictionary<string, dynamic>.");
                                }

                                var existingDictionary = existing as IDictionary <string, dynamic>;
                                foreach (var existingItem in existingDictionary)
                                {
                                    orchardGlobal[existingItem.Key] = existingItem.Value;
                                }
                            }

                            scope.SetVariable("_ORCHARD", orchardGlobal);

                            foreach (var item in scope.Variables)
                            {
                                scriptContext.Globals.TrySetMember(item.Key, item.Value);
                            }

                            // Setting globals like this only works for primitive types.
                            // Operators.SetVariable(scriptContext, null, "test", "");

                            _eventHandler.BeforeExecution(new BeforePhpExecutionContext(scope, scriptContext));
                            executor(requestContext);
                            _eventHandler.AfterExecution(new AfterPhpExecutionContext(scope, scriptContext));

                            foreach (var variable in scriptContext.GlobalVariables)
                            {
                                scope.SetVariable(variable.Key.ToString(), variable.Value);
                            }

                            scriptContext.Output.Flush();
                            scriptContext.OutputStream.Position = 0;
                            using (var streamReader = new StreamReader(scriptContext.OutputStream))
                            {
                                return(streamReader.ReadToEnd());
                            }
                        }
                    }
                }
            }
            catch (PhpException ex)
            {
                throw new ScriptRuntimeException("The PHP script could not be executed.", ex);
            }
        }