Exemple #1
0
        public static void Construct()
        {
            try
            {
                ModuleN.InitN();

                JNIEnv          env        = JNIEnv.ThreadEnv;
                JniGlobalHandle hmHandle   = env.NewGlobalRef((JniHandle)domain.GetData("hostManager"));
                JniGlobalHandle peerHandle = env.NewGlobalRef((JniHandle)domain.GetData("peer"));
                JniGlobalHandle itemHandle = env.NewGlobalRef((JniHandle)domain.GetData("item"));
                hostManager   = Bridge.CreateProxy <IHostManager>(hmHandle);
                robotPeer     = Bridge.CreateProxy <IRobotPeer>(peerHandle);
                specification = Bridge.CreateProxy <IRobotItem>(itemHandle);

                statics = ((RobotStatics)domain.GetData("statics"));
                CreateProxy();

                Assembly assembly = Assembly.LoadFrom(robotAssemblyShadowFileName);
                Reflection.CheckAssembly(assembly);
                string robotFullName = specification.getFullClassName();
                robotType = assembly.GetType(robotFullName, false);
                robotProxy.setRobotType(robotType);
            }
            catch (Exception ex)
            {
                LoggerN.logError(ex);
                throw;
            }
        }
Exemple #2
0
 public static void FindRobots()
 {
     try
     {
         var      sb       = new StringBuilder();
         Assembly assembly = Assembly.LoadFrom(robotAssemblyShadowFileName);
         foreach (Type type in assembly.GetTypes())
         {
             if (Reflection.CheckInterfaces(type) != RobotTypeN.INVALID)
             {
                 sb.Append("file:///");
                 sb.Append(robotAssemblyFileName);
                 sb.Append("!/");
                 sb.Append(type.FullName);
                 sb.Append(";");
             }
         }
         if (sb.Length > 0)
         {
             sb.Length--;
         }
         domain.SetData("robotsFound", sb.ToString());
     }
     catch (Exception ex)
     {
         LoggerN.logError(ex);
         throw;
     }
 }
Exemple #3
0
 public void Dispose()
 {
     if (domain != null)
     {
         try
         {
             AppDomain.Unload(domain);
             domain = null;
             GC.Collect();
         }
         catch (Exception ex)
         {
             LoggerN.logError(ex);
             if (robotPeer != null)
             {
                 robotPeer.punishBadBehavior(BadBehavior.UNSTOPPABLE);
             }
         }
     }
     if (tempDir != null && Directory.Exists(tempDir))
     {
         try
         {
             Directory.Delete(tempDir, true);
         }
         catch (IOException)
         {
             //ignore
         }
         tempDir = null;
     }
 }
        public static void init()
        {
            if (initialized)
            {
                return;
            }
            MethodInfo method;

            try
            {
                method      = typeof(Event).GetMethod("createHiddenHelper", BindingFlags.Static | BindingFlags.NonPublic);
                eventHelper = (IHiddenEventHelper)method.Invoke(null, null);

                method       = typeof(Bullet).GetMethod("createHiddenHelper", BindingFlags.Static | BindingFlags.NonPublic);
                bulletHelper = (IHiddenBulletHelper)method.Invoke(null, null);

                method = typeof(RobotStatus).GetMethod("createHiddenSerializer",
                                                       BindingFlags.Static | BindingFlags.NonPublic);
                statusHelper = (IHiddenStatusHelper)method.Invoke(null, null);

                method = typeof(BattleRules).GetMethod("createHiddenHelper",
                                                       BindingFlags.Static | BindingFlags.NonPublic);
                rulesHelper = (IHiddenRulesHelper)method.Invoke(null, null);

                initialized = true;
            }
            catch (Exception e)
            {
                LoggerN.logError(e);
                Environment.Exit(-1);
            }
        }
Exemple #5
0
 public static void Bind()
 {
     try
     {
         bool fullBind = (bool)domain.GetData("fullBind");
         if (fullBind)
         {
             var setup = new BridgeSetup(false);
             setup.BindCoreOnly = true;
             setup.BindNative   = false;
             setup.BindStatic   = false;
             setup.JavaHome     = (string)domain.GetData("JavaHome");
             Bridge.CreateJVM(setup);
             JNIEnv env = JNIEnv.ThreadEnv;
             Registry.RegisterType(typeof(ByteBuffer), true, env);
             Registry.RegisterType(typeof(Buffer), true, env);
             Registry.RegisterType(typeof(DirectByteBuffer), true, env);
             Registry.RegisterType(typeof(java.lang.System), true, env);
             Registry.RegisterType(typeof(ByteOrder), true, env);
             Bridge.RegisterAssembly(typeof(RbSerializer).Assembly);
         }
     }
     catch (Exception ex)
     {
         LoggerN.logError(ex);
         throw;
     }
 }
Exemple #6
0
        public static void InitN()
        {
            System.Threading.Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
            HiddenAccessN.init();
            LoggerN.IsSafeThread = true;
            LoggerN.setLogListener(new Logger(true));
            HiddenAccessN.randomHelper = new RandomFactory(true);

            var versionManager =
                Bridge.Cast <IVersionManagerBase>(ContainerBase.getComponent(IVersionManagerBase_._class));
            int currentVersion = versionManager.getVersionAsInt();

            RbSerializer.Init(currentVersion);
            RbSerializerN.Init(currentVersion);

            RbSerializerN.register(typeof(RobotStatus), RbSerializerN.RobotStatus_TYPE);
            RbSerializerN.register(typeof(BattleResults), RbSerializerN.BattleResults_TYPE);
            RbSerializerN.register(typeof(Bullet), RbSerializerN.Bullet_TYPE);
            RbSerializerN.register(typeof(RobotStatics), RbSerializerN.RobotStatics_TYPE);

            // events
            RbSerializerN.register(typeof(RoundEndedEvent), RbSerializerN.RoundEndedEvent_TYPE);
            RbSerializerN.register(typeof(BattleEndedEvent), RbSerializerN.BattleEndedEvent_TYPE);
            RbSerializerN.register(typeof(BulletHitBulletEvent), RbSerializerN.BulletHitBulletEvent_TYPE);
            RbSerializerN.register(typeof(BulletHitEvent), RbSerializerN.BulletHitEvent_TYPE);
            RbSerializerN.register(typeof(BulletMissedEvent), RbSerializerN.BulletMissedEvent_TYPE);
            RbSerializerN.register(typeof(DeathEvent), RbSerializerN.DeathEvent_TYPE);
            RbSerializerN.register(typeof(WinEvent), RbSerializerN.WinEvent_TYPE);
            RbSerializerN.register(typeof(HitWallEvent), RbSerializerN.HitWallEvent_TYPE);
            RbSerializerN.register(typeof(RobotDeathEvent), RbSerializerN.RobotDeathEvent_TYPE);
            RbSerializerN.register(typeof(SkippedTurnEvent), RbSerializerN.SkippedTurnEvent_TYPE);
            RbSerializerN.register(typeof(ScannedRobotEvent), RbSerializerN.ScannedRobotEvent_TYPE);
            RbSerializerN.register(typeof(HitByBulletEvent), RbSerializerN.HitByBulletEvent_TYPE);
            RbSerializerN.register(typeof(HitRobotEvent), RbSerializerN.HitRobotEvent_TYPE);
            RbSerializerN.register(typeof(KeyPressedEvent), RbSerializerN.KeyPressedEvent_TYPE);
            RbSerializerN.register(typeof(KeyReleasedEvent), RbSerializerN.KeyReleasedEvent_TYPE);
            RbSerializerN.register(typeof(KeyTypedEvent), RbSerializerN.KeyTypedEvent_TYPE);
            RbSerializerN.register(typeof(MouseClickedEvent), RbSerializerN.MouseClickedEvent_TYPE);
            RbSerializerN.register(typeof(MouseDraggedEvent), RbSerializerN.MouseDraggedEvent_TYPE);
            RbSerializerN.register(typeof(MouseEnteredEvent), RbSerializerN.MouseEnteredEvent_TYPE);
            RbSerializerN.register(typeof(MouseExitedEvent), RbSerializerN.MouseExitedEvent_TYPE);
            RbSerializerN.register(typeof(MouseMovedEvent), RbSerializerN.MouseMovedEvent_TYPE);
            RbSerializerN.register(typeof(MousePressedEvent), RbSerializerN.MousePressedEvent_TYPE);
            RbSerializerN.register(typeof(MouseReleasedEvent), RbSerializerN.MouseReleasedEvent_TYPE);
            RbSerializerN.register(typeof(MouseWheelMovedEvent), RbSerializerN.MouseWheelMovedEvent_TYPE);

            RbSerializerN.register(typeof(ExecCommands), RbSerializerN.ExecCommands_TYPE);
            RbSerializerN.register(typeof(BulletCommand), RbSerializerN.BulletCommand_TYPE);
            RbSerializerN.register(typeof(TeamMessage), RbSerializerN.TeamMessage_TYPE);
            RbSerializerN.register(typeof(DebugProperty), RbSerializerN.DebugProperty_TYPE);
            RbSerializerN.register(typeof(ExecResults), RbSerializerN.ExecResults_TYPE);
            RbSerializerN.register(typeof(BulletStatus), RbSerializerN.BulletStatus_TYPE);
        }
Exemple #7
0
 public static void Cleanup()
 {
     try
     {
         robotProxy.cleanup();
     }
     catch (Exception ex)
     {
         LoggerN.logError(ex);
         throw;
     }
 }
Exemple #8
0
 public static void Open()
 {
     try
     {
         robotAssemblyFileName       = (string)domain.GetData("robotAssemblyFileName");
         robotAssemblyShadowFileName = (string)domain.GetData("robotAssemblyShadowFileName");
     }
     catch (Exception ex)
     {
         LoggerN.logError(ex);
         throw;
     }
 }
Exemple #9
0
 public void cleanup()
 {
     foreach (QuotaStream stream in streams)
     {
         try
         {
             stream.Dispose();
         }
         catch (Exception ex)
         {
             LoggerN.logError(ex);
         }
     }
 }
Exemple #10
0
 public static void Load(string[] args)
 {
     try
     {
         domain = AppDomain.CurrentDomain;
         domain.UnhandledException += (domain_UnhandledException);
         domain.AssemblyLoad       += (domain_AssemblyLoad);
     }
     catch (Exception ex)
     {
         LoggerN.logError(ex);
         throw;
     }
 }
Exemple #11
0
 public static void ForceStopThread()
 {
     try
     {
         LoggerN.logMessage(HiddenAccessN.GetRobotName() + " is not stopping.  Forcing a stop.");
         robotThread.Priority = ThreadPriority.Lowest;
         robotThread.Abort();
         robotThread.Interrupt();
     }
     catch (Exception ex)
     {
         LoggerN.logError(ex);
         throw;
     }
 }
Exemple #12
0
 private static int CheckCount()
 {
     lock (syncRoot)
     {
         if (runningCounter > 5)
         {
             string message = "Preventing " + HiddenAccessN.GetRobotName() + "from thread creation. You may only create 5 threads at same time.";
             LoggerN.logError(message);
             LoggerN.WriteLineToRobotsConsole(message);
             throw new AccessViolationException(message);
         }
         runningCounter++;
         return(runningCounter);
     }
 }
Exemple #13
0
 /// <summary>
 /// Hidden method for setting the priority from the game engine without checking for the 'addedToQueue' flag.
 /// </summary>
 /// <remarks>
 /// This method is called by the game engine only.
 /// </remarks>
 /// <param name="newPriority">the new priority of this event.</param>
 // This method must be invisible on Robot API
 private void SetPriorityHidden(int newPriority)
 {
     if (newPriority < 0)
     {
         LoggerN.WriteLineToRobotsConsole("SYSTEM: Priority must be between 0 and 99");
         LoggerN.WriteLineToRobotsConsole("SYSTEM: Priority for " + GetType().Name + " will be 0");
         newPriority = 0;
     }
     else if (newPriority > 99)
     {
         LoggerN.WriteLineToRobotsConsole("SYSTEM: Priority must be between 0 and 99");
         LoggerN.WriteLineToRobotsConsole("SYSTEM: Priority for " + GetType().Name + " will be 99");
         newPriority = 99;
     }
     priority = newPriority;
 }
Exemple #14
0
 public static void WaitForStopThread()
 {
     try
     {
         if (!robotThread.Join(1000))
         {
             LoggerN.logError("Unable to stop thread for " + statics.getName());
             robotPeer.punishBadBehavior(BadBehavior.UNSTOPPABLE);
             robotPeer.setRunning(false);
         }
     }
     catch (Exception ex)
     {
         LoggerN.logError(ex);
         throw;
     }
 }
 /// <summary>
 /// Creates a new Condition with the specified name and priority.
 /// A condition priority is a value from 0 - 99. The higher value, the
 /// higher priority. The default priority is 80.
 /// </summary>
 /// <param name="name">The name for the new condition</param>
 /// <param name="priority">The priority of the new condition</param>
 protected Condition(string name, int priority)
 {
     this.name = name;
     if (priority < 0)
     {
         LoggerN.WriteLineToRobotsConsole("SYSTEM: Priority must be between 0 and 99.");
         LoggerN.WriteLineToRobotsConsole("SYSTEM: Priority for condition " + name + " will be 0.");
         priority = 0;
     }
     else if (priority > 99)
     {
         LoggerN.WriteLineToRobotsConsole("SYSTEM: Priority must be between 0 and 99.");
         LoggerN.WriteLineToRobotsConsole("SYSTEM: Priority for condition " + name + " will be 99.");
         priority = 99;
     }
     this.priority = priority;
 }
Exemple #16
0
        static void domain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
        {
            bool knownLocation = args.LoadedAssembly.Location != null &&
                                 robotAssemblyShadowFileName != null &&
                                 Path.GetFullPath(args.LoadedAssembly.Location).ToLower() ==
                                 Path.GetFullPath(robotAssemblyShadowFileName).ToLower();

            if (args.LoadedAssembly != typeof(Bridge).Assembly &&
                args.LoadedAssembly != typeof(AppDomainSeed).Assembly &&
                args.LoadedAssembly != typeof(RobocodeEngine).Assembly &&
                !knownLocation &&
                !args.LoadedAssembly.GlobalAssemblyCache)
            {
                string message = "dependent assemblies are not alowed" + args.LoadedAssembly.Location;
                LoggerN.logError(message);
                throw new SecurityException(message);
            }
        }
        private bool loadRobotRound()
        {
            robot = null;
            try
            {
                object instance = Activator.CreateInstance(robotType);
                robot = instance as IBasicRobot;
                if (robot == null)
                {
                    println("SYSTEM: Skipping robot: " + statics.getName());
                    return(false);
                }
                robot.SetOut(output);
                robot.SetPeer((IBasicRobotPeer)this);
                Console.SetOut(output);
                Console.SetError(output);
                eventManager.SetRobot(robot);
            }

            catch (MissingMethodException e)
            {
                punishSecurityViolation(statics.getName() + " " + e.Message);
                return(false);
            }
            catch (SecurityException e)
            {
                punishSecurityViolation(statics.getName() + " " + e.Message);
                return(false);
            }
            catch (Exception e)
            {
                if (e.InnerException is SecurityException)
                {
                }
                println("SYSTEM: An error occurred during initialization of " + statics.getName());
                println("SYSTEM: " + e);
                println(e);
                robot = null;
                LoggerN.logMessage(e);
                return(false);
            }
            return(true);
        }
Exemple #18
0
 public static void GetRobotType()
 {
     try
     {
         var      robotFullName = (string)domain.GetData("loadRobot");
         Assembly assembly      = Assembly.LoadFrom(robotAssemblyShadowFileName);
         Reflection.CheckAssembly(assembly);
         Type robotType = assembly.GetType(robotFullName, false);
         if (robotType != null)
         {
             domain.SetData("robotLoaded", (int)Reflection.CheckInterfaces(robotType));
         }
     }
     catch (Exception ex)
     {
         domain.SetData("robotLoaded", 0);
         LoggerN.logError(ex);
     }
 }
Exemple #19
0
        public static void register(Type realClass, byte type)
        {
            try
            {
                if (realClass != null)
                {
                    MethodInfo method = realClass.GetMethod("createHiddenSerializer",
                                                            BindingFlags.NonPublic | BindingFlags.Static);
                    var helper = (ISerializableHelperN)method.Invoke(null, null);

                    typeToHelper[type] = helper;
                    classToType.Add(realClass, type);
                }
            }
            catch (Exception e)
            {
                LoggerN.logError(e);
            }
        }
        public void punishSecurityViolation(java.lang.String message)
        {
            // Prevent unit tests of failing if multiple threads are calling this method in the same time.
            // We only want the a specific type of security violation logged once so we only get one error
            // per security violation.
            lock (securityViolations)
            {
                if (!securityViolations.ContainsKey(message))
                {
                    securityViolations.Add(message, null);
                    LoggerN.logError(message);
                    println("SYSTEM: " + message);

                    if (securityViolations.Count == 1)
                    {
                        peer.drainEnergy();
                        peer.punishBadBehavior(BadBehavior.SECURITY_VIOLATION);
                    }
                }
            }
        }
Exemple #21
0
        public static void StartRound()
        {
            try
            {
                var commands = (ExecCommands)domain.GetData("commands");
                var status   = (RobotStatus)domain.GetData("status");

                robotProxy.initializeRound(commands, status);

                robotThread = new Thread(RobotMain);
                robotThread.CurrentCulture   = CultureInfo.InvariantCulture;
                robotThread.CurrentUICulture = CultureInfo.InvariantCulture;
                robotThread.Start(null);
                robotThread.Name = "Robot: " + robotProxy.getStatics().getName();
            }
            catch (Exception ex)
            {
                LoggerN.logError(ex);
                throw;
            }
        }
Exemple #22
0
        protected override sealed void waitForBattleEndImpl()
        {
            eventManager.ClearAllEvents(false);
            graphicsProxy.setPaintingEnabled(false);
            do
            {
                commands.setOutputText(GetOutTextAndReset());
                commands.setGraphicsCalls(graphicsProxy.readoutQueuedCalls());

                // call server
                try
                {
                    SerializeCommands();
                    peer.waitForBattleEndImplSerial();
                    DeserializeResults();
                }
                catch (Exception ex)
                {
                    LoggerN.logMessage(statics.getName() + ": Exception: " + ex); // without stack here
                    return;
                }

                updateStatus(execResults.getCommands(), execResults.getStatus());

                // add new events
                if (execResults.getEvents() != null)
                {
                    foreach (Event evnt in execResults.getEvents())
                    {
                        if (evnt is BattleEndedEvent)
                        {
                            eventManager.Add(evnt);
                        }
                    }
                }
                eventManager.ResetCustomEvents();

                eventManager.ProcessEvents();
            } while (!execResults.isHalt() && execResults.isShouldWait());
        }
Exemple #23
0
 static void domain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     LoggerN.logError(e.ExceptionObject.ToString());
 }
        public void run()
        {
            peer.setRunning(true);

            if (robotSpecification.isValid() && loadRobotRound())
            {
                try
                {
                    if (robot != null)
                    {
//                        peer.setRunning(true); // Does not work with .NET version

                        // Process all events for the first turn.
                        // This is done as the first robot status event must occur before the robot
                        // has started running.
                        eventManager.ProcessEvents();

                        // Call user code
                        CallUserCode();
                    }

                    // noinspection InfiniteLoopStatement
                    for (;;)
                    {
                        executeImpl();
                    }
                }
                catch (WinException)
                {
                    // Do nothing
                }
                catch (AbortedException)
                {
                    // Do nothing
                }
                catch (DeathException)
                {
                    println("SYSTEM: " + statics.getName() + " has died");
                }
                catch (DisabledException e)
                {
                    drainEnergy();

                    string msg = e.getMessage();
                    if (msg == null)
                    {
                        msg = "";
                    }
                    else
                    {
                        msg = ": " + msg;
                    }
                    println("SYSTEM: Robot disabled: " + msg);
                    LoggerN.logMessage("Robot disabled: " + statics.getName());
                }
                catch (SecurityException e)
                {
                    punishSecurityViolation(statics.getName() + " Exception: " + e);
                }
                catch (Exception e)
                {
                    if (e.InnerException is SecurityException)
                    {
                        punishSecurityViolation(statics.getName() + " " + e.InnerException + " Exception: " + e);
                    }
                    else
                    {
                        drainEnergy();
                        println(e);
                        LoggerN.logMessage(statics.getName() + ": Exception: " + e); // without stack here
                    }
                }
                finally
                {
                    waitForBattleEndImpl();
                }
            }
            else
            {
                drainEnergy();
                peer.punishBadBehavior(BadBehavior.CANNOT_START);
                waitForBattleEndImpl();
            }

            peer.setRunning(false);
        }