Ejemplo n.º 1
0
        public RequestInfo(Verb method, HttpUrl url, Stream body, IClaimBasedIdentity identity, HeaderCollection headers)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            if (body == null)
            {
                throw new ArgumentNullException("body");
            }

            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }

            Method = method;
            Url = url;
            Body = new UnclosableStream(_stream = body);
            _identity = identity;
            Headers = headers ?? new HeaderCollection();
        }
Ejemplo n.º 2
0
        public UriRoute(Uri baseUri, string template = null, Verb verbs = Verb.All, Func<IOwinContext, bool> filter = null)
        {
            Contract.Assert(baseUri != null);
            BaseUri = baseUri;
            Template = template ?? baseUri.PathAndQuery;
            Verbs = verbs;

            if (template == null)
            {
                Template = baseUri.PathAndQuery;
            }
            else
            {
                if (template.StartsWith("/") || !baseUri.PathAndQuery.EndsWith("/"))
                {
                    Template = template;
                }
                else
                {
                    Template = baseUri.PathAndQuery + template;
                }
            }

            Mapper = new UriRouteMapper(this, filter);
        }
Ejemplo n.º 3
0
 Act(Person s, Verb v, Noun o1, Noun o2, Act c, System.Action<Act> R)
     : this()
 {
     //Debug.Assert(Arity(v) == 2 || o2, v.ToString() + " is a ternary verb.");
     subject = s; verb = v; primaryObject = o1; secondaryObject = o2; parent = c; Register = R;
     args = new VerbArguments(this);
     Register(this);
 }
Ejemplo n.º 4
0
        /// <summary>Initializes a new instance of the <see cref="OnVerbAttribute" /> class.</summary>
        /// <param name="verb">Target HTTP verb.</param>
        public OnVerbAttribute(Verb verb)
        {
            if (verb == null)
            {
                throw new ArgumentNullException("verb");
            }

            Verb = verb;
        }
Ejemplo n.º 5
0
        /// <summary>Initializes a new instance of the <see cref="OperationInfo" /> class.</summary>
        /// <param name="underlyingMethod">Actual underlying method.</param>
        /// <param name="verb">An HTTP verb for given operation</param>
        /// <param name="uri">Base relative uri of the method without arguments.</param>
        /// <param name="templateRegex">Uri template regular expression.</param>
        /// <param name="uriTemplate">Relative uri template with all arguments included.</param>
        /// <param name="arguments">Argument descriptions.</param>
        public OperationInfo(MethodInfo underlyingMethod, Verb verb, Uri uri, Regex templateRegex, string uriTemplate, params ArgumentInfo[] arguments) : base(underlyingMethod, uri, uriTemplate, arguments)
        {
            if (verb == null)
            {
                throw new ArgumentNullException("verb");
            }

            Verb = verb;
            TemplateRegex = templateRegex;
        }
Ejemplo n.º 6
0
        internal static IEnumerable<HttpStatusCode> DiscoverCrudStatusCodes(this MethodInfo method, Verb verb, Type controllerType = null)
        {
            var methods = (controllerType ?? method.DeclaringType).DiscoverCrudMethods();
            MethodInfo matchedMethod;
            Verb matchedVerb;
            if (((!methods.TryGetValue(matchedVerb = verb, out matchedMethod)) || (matchedMethod != method)) &&
                ((!methods.TryGetValue(matchedVerb = Verb.Empty, out matchedMethod)) || (matchedMethod != method)))
            {
                return DefaultStatusCodes;
            }

            return ControllerCrudMethodStatusCodes[matchedVerb];
        }
Ejemplo n.º 7
0
        private static Stream WebInvoke(Uri uri, Verb verb, Stream input, bool hasOutput)
        {
            var request = WebRequest.Create(uri);
            switch (verb)
            {
                case Verb.Get:
                    request.Method = "GET";
                    break;
                case Verb.Post:
                    request.Method = "POST";
                    break;
                case Verb.Put:
                    request.Method = "PUT";
                    break;
                case Verb.Delete:
                    request.Method = "DELETE";
                    break;
            }

            WebResponse response;

            if (input != null)
            {
                input.Seek(0, SeekOrigin.Begin);

                request.ContentType = "application/xml";
                request.ContentLength = input.Length;

                using (var requestStream = request.GetRequestStream())
                {
                    var bytes = new byte[1024];
                    var read = 1;
                    while (read > 0)
                    {
                        read = input.Read(bytes, 0, bytes.Length);
                        requestStream.Write(bytes, 0, read);
                    }
                }
            }

            using (response = request.GetResponse())
			{
				if (!hasOutput)
					return null;
				var temp = new MemoryStream();
				response.GetResponseStream().CopyTo(temp);
				temp.Seek(0L, SeekOrigin.Begin);
				return temp;
			}
        }
Ejemplo n.º 8
0
        public bool TryMap(Uri uri, Verb verb, out IDictionary<string, string> parameters)
        {
            parameters = null;

            if (!(string.Equals(_route.BaseUri.Host, uri.Host) && _route.BaseUri.Port == uri.Port)) return false;

            if (!_route.Verbs.HasFlag(verb)) return false;

            try
            {
                parameters = Parse(uri);
                return true;
            }
            catch (ArgumentException)
            {
                return false;
            }
        }
Ejemplo n.º 9
0
        public TransferHandle(
            string path, 
            Verb verb,
            string clientId, 
            Socket clientSocket,
            bool disposeSocket,
            ICompressionProvider compression, 
            Action<TransferHandle> onConnect)
        {
            ClientSocket = clientSocket;
            ClientId = clientId;
            Path = path;
            OnConnect = onConnect ?? (h => { });
            Id = Util.GenerateId();
            BufferSize = 1024;
            Verb = verb;

            _compression = compression;
            _disposeSocket = disposeSocket;
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Creates a fictive test <see cref="CapabilityList"/>.
 /// </summary>
 public static CapabilityList CreateTestCapabilityList()
 {
     var testIcon = new Icon {Href = new Uri("http://0install.de/feeds/icons/test.ico"), MimeType = "image/vnd.microsoft.icon"};
     var testVerb = new Verb {Name = Verb.NameOpen, Descriptions = {"Verb description"}, Command = Command.NameRun, Arguments = "--open"};
     return new CapabilityList
     {
         OS = Architecture.CurrentSystem.OS,
         Entries =
         {
             new AppRegistration {ID = "myapp", CapabilityRegPath = @"SOFTWARE\MyApp\Capabilities"},
             new AutoPlay {ID = "autoplay", Descriptions = {"Do somthing"}, Icons = {testIcon}, Provider = "MyApp", Verb = testVerb, Events = {new AutoPlayEvent {Name = AutoPlayEvent.NameBurnCD}}},
             new ComServer {ID = "com-server"},
             new ContextMenu {ID = "context-menu", Verb = testVerb},
             new DefaultProgram {ID = "default-program", Descriptions = {"My mail client"}, Icons = {testIcon}, Verbs = {testVerb}, Service = "Mail", InstallCommands = new InstallCommands {ShowIcons = "helper.exe --show", HideIcons = "helper.exe --hide", Reinstall = "helper.exe --reinstall.exe"}},
             new FileType {ID = "my_ext1", Descriptions = {"Text file"}, Icons = {testIcon}, Extensions = {new FileTypeExtension {Value = "txt", MimeType = "text/plain"}}, Verbs = {testVerb}},
             new FileType {ID = "my_ext2", Descriptions = {"JPG image"}, Icons = {testIcon}, Extensions = {new FileTypeExtension {Value = "jpg", MimeType = "image/jpg"}}, Verbs = {testVerb}},
             new UrlProtocol {ID = "my_protocol", Descriptions = {"My protocol"}, Icons = {testIcon}, Verbs = {testVerb}, KnownPrefixes = {new KnownProtocolPrefix {Value = "my-protocol"}}}
         }
     };
 }
Ejemplo n.º 11
0
 private HecpRequest(IAcDomain acDomain, IMessageDto cmdDto)
     : this(acDomain)
 {
     if (cmdDto == null)
     {
         throw new ArgumentNullException("cmdDto");
     }
     if (cmdDto.Body == null)
     {
         throw new AnycmdException();
     }
     this._message = cmdDto;
     if (cmdDto.Body.InfoId == null)
     {
         _infoId = new DataItem[0];
     }
     if (cmdDto.Body.InfoValue == null)
     {
         _infoValue = new DataItem[0];
     }
     if (cmdDto.Body.InfoId != null)
     {
         _infoId = cmdDto.Body.InfoId.Where(a => a != null).Select(a => new DataItem(a.Key, a.Value)).ToArray();
     }
     if (cmdDto.Body.InfoValue != null)
     {
         _infoValue = cmdDto.Body.InfoValue.Where(a => a != null).Select(a => new DataItem(a.Key, a.Value)).ToArray();
     }
     this._queryList = cmdDto.Body.QueryList;
     this.Credential = new CredentialObject(cmdDto.Credential);
     this._verb = new Verb(cmdDto.Verb);
     if (cmdDto.Body.Event == null) return;
     _eventSourceType = cmdDto.Body.Event.SourceType;
     _eventSubject = cmdDto.Body.Event.Subject;
     _eventStatus = cmdDto.Body.Event.Status;
     _eventReasonPhrase = cmdDto.Body.Event.ReasonPhrase;
 }
Ejemplo n.º 12
0
        public Task<ITransferHandle> BeginTransfer(string path, Verb verb = Verb.Default, Action<TransferHandle> onConnect = null)
        {
            var socket = _socket ?? CreateSocket();

            if (socket.Connected) throw new InvalidOperationException("Already connected");

            var state = new TransferHandle(path, verb, _clientId, socket, _socket == null, _compression, onConnect);
            var connectedHandle = new ManualResetEvent(false);

            return Task<ITransferHandle>.Factory.StartNew(() =>
            {
                if (!socket.Connected)
                {
                    DebugOutput.Log("Connecting to " + _endpoint);

                    socket.BeginConnect(_endpoint, a =>
                    {
                        var handle = (TransferHandle)a.AsyncState;

                        handle.ClientSocket.EndConnect(a);
                        handle.OnConnect(handle);
                        connectedHandle.Set();
                    }, state);

                    connectedHandle.WaitOne();

                    if (socket.Connected) DebugOutput.Log("Connected to " + _endpoint);
                }
                else
                {
                    connectedHandle.Set();
                }

                return state;
            });
        }
Ejemplo n.º 13
0
        private TwiMLBuilder AddVerb(Verb verb, string value, object attributes, params Tuple<Verb, string, object>[] children)
        {
            this.Elements.Add(CreateBuilderElement(verb, value, attributes, children));

            return this;
        }
Ejemplo n.º 14
0
 public Responder(Verb verb, string expression, Callback callback)
 {
     Verb = verb;
     Expression = expression;
     Callback = callback;
 }
Ejemplo n.º 15
0
        private static Verb GetVerb([NotNull] RegistryKey typeKey, [NotNull] CommandMapper commandMapper, [NotNull] string verbName)
        {
            #region Sanity checks
            if (typeKey == null) throw new ArgumentNullException(nameof(typeKey));
            if (string.IsNullOrEmpty(verbName)) throw new ArgumentNullException(nameof(verbName));
            if (commandMapper == null) throw new ArgumentNullException(nameof(commandMapper));
            #endregion

            using (var verbKey = typeKey.OpenSubKey(@"shell\" + verbName))
            {
                if (verbKey == null) return null;

                string description = verbKey.GetValue("", "").ToString();
                string commandLine;
                using (var commandKey = verbKey.OpenSubKey("command"))
                {
                    if (commandKey == null) return null;
                    commandLine = commandKey.GetValue("", "").ToString();
                }

                string additionalArgs;
                var command = commandMapper.GetCommand(commandLine, out additionalArgs);
                if (command == null) return null;
                string commandName = command.Name;

                if (commandName == Command.NameRun) commandName = null;
                var verb = new Verb
                {
                    Name = verbName,
                    Command = commandName,
                    Arguments = additionalArgs
                };
                if (!string.IsNullOrEmpty(description)) verb.Descriptions.Add(description);
                return verb;
            }
        }
Ejemplo n.º 16
0
        internal static FsResult Parse(Verb verb, string command, string xml)
        {
            var xdoc = XDocument.Parse(xml);
            var status = xdoc.Descendants("status").First().Value;
            if (status != "FS_OK")
            {
                throw new FsException(status);
            }
            if (verb == Verb.CreateSession)
            {
                var sessionId = xdoc.Descendants("sessionId").First().Value;
                return new FsResult<int>(int.Parse(sessionId));
            }
            if (verb == Verb.DeleteSession)
            {
                return new FsResult<int>(0);
            }
            else if (verb == Verb.Get)
            {
                var value = xdoc.Descendants("value").Single();
                switch (command)
                {
                    case Command.POWER:
                    case Command.NAVSTATUS:
                    case Command.PLAY_REPEATE:
                    case Command.PLAY_SCROBBLE:
                    case Command.PLAY_SUFFLE:
                    case Command.MUTE:
                    case Command.MULTI_GROUP_MUTE_CLIENT:
                    case Command.STANDBY_NETWORK:
                    case Command.CUSTOM_EQ_LOUDNESS:
                        return new FsResult<bool>(ParseBool(value));

                    case Command.SELECTPRESET:
                    case Command.MODE:
                    case Command.PLAY_DURATION:
                    case Command.PLAY_POS:
                    case Command.MAX_FM_FREQ:
                    case Command.MIN_FM_FREQ:
                    case Command.STEP_FM_FREQ:
                    case Command.DAB_SID:
                    case Command.SLEEP:
                        return new FsResult<int>(ParseInt(value));

                    case Command.PLAY_FREQU:
                        return new FsResult<uint>(ParseuInt(value));

                    case Command.DAB_EID:
                    case Command.FM_RDSPI:
                        return new FsResult<ushort>(ParseUshort(value));

                    case Command.VOLUME:
                    case Command.VOLUME_STEPS:
                    case Command.PLAY_CONTROL:
                    case Command.PLAY_SIGNAL:
                    case Command.PLAY_STATUS:
                    case Command.EQ_PRESET:
                    case Command.DAB_ECC:
                    case Command.DAB_SCID:
                    case Command.WLAN_STREGHT:
                    case Command.MULTI_DEVICE_SERVER_STATE:
                    case Command.MULTI_DEVICE_CLIENT:
                    case Command.MULTI_GROUP_STATE:
                    case Command.MULTI_GROUP_VOL:
                    case Command.MULTI_GROUP_VOL_CLIENT:
                        return new FsResult<byte>(ParseByte(value));

                    case Command.PLAY_INFO_NAME:
                    case Command.PLAY_INFO_TEXT:
                    case Command.PLAY_INFO_GRAPHIC:
                    case Command.PLAY_ALBUM:
                    case Command.PLAY_ARTIST:
                    case Command.NAME:
                    case Command.VERSION:
                    case Command.DATE:
                    case Command.TIME:
                    case Command.WIRED_MAC:
                    case Command.WIRELESS_MAC:
                    case Command.MULTI_GROUP_NAME:
                    case Command.MULTI_GROUP_ID:
                        return new FsResult<string>(ParseString(value));

                    case Command.CUSTOM_EQ_BASS:
                    case Command.CUSTOM_EQ_TREBLE:
                    case Command.CUSTOM_EQ_RAW:
                        return new FsResult<short>(ParseShort(value));

                    case Command.NUMENTRIES:
                        return new FsResult<long>(ParseLong(value));
                }
                throw new NotImplementedException(command);
            }
            else if (verb == Verb.ListGetNext)
            {
                switch (command)
                {
                    case Command.VALID_MODES:
                        return new FsResult<IEnumerable<RadioMode>>(ParseValidModes(xdoc));

                    case Command.EQUALIZER_PRESETS:
                        return new FsResult<IEnumerable<EqualizerPreset>>(ParseEqualizerPresets(xdoc));

                    case Command.PRESETS:
                        return new FsResult<IEnumerable<Preset>>(ParsePresets(xdoc));

                    case Command.NAVLIST:
                        return new FsResult<IEnumerable<NavListItem>>(ParseNavList(xdoc));

                    case Command.CUSTOM_EQ_BANDS:
                        return new FsResult<IEnumerable<EQBandListItem>>(ParseEQBandList(xdoc));

                    case Command.MULTI_LIST_ALL:
                        return new FsResult<IEnumerable<MutliRoomItem>>(ParseMultiroomList(xdoc));

                }
                throw new NotImplementedException(command);
            }
            else if (verb == Verb.GetNotify)
            {
                return new FsResult<IEnumerable<FsNotification>>(ParseNotifications(xdoc));
            }
            else if (verb == Verb.Set)
            {
                return new FsResult<FsVoid>();
            }
            throw new NotImplementedException(verb.ToString());
        }
Ejemplo n.º 17
0
    static void ProcessType()
    {
        switch (RawArgs[PassIndex].ToLower())
        {
        case "-get-class":
        case "-gc":
            Console.WriteLine(CtxType.Class);
            break;

        case "-set-class":
        case "-sc":
            CtxType.Class = ReadParameter();
            break;

        case "-get-default":
        case "-gd":
            Console.WriteLine(CtxType.Verbs.Default);
            break;

        case "-set-default":
        case "-sd":
            CtxType.Verbs.Default = ReadParameter();
            break;

        case "-list-verbs":
        case "-lv":
            foreach (Verb v in CtxType.Verbs)
            {
                Console.WriteLine(v.ID);
            }
            break;

        case "-delete-verb":
        case "-dv":
            CtxType.Verbs.Delete(ReadParameter());
            break;

        case "-get-extension-visibility":
        case "-gxv":

            switch (CtxType.ShowExtension)
            {
            case -1: Console.WriteLine("Hidden"); break;

            case  0: Console.WriteLine("Default"); break;

            case +1: Console.WriteLine("Visible"); break;
            }

            break;

        case "-set-extension-visibility":
        case "-sxv":

            switch (ReadParameter().ToLower())
            {
            case "hidden":
            case "h": CtxType.ShowExtension = -1; break;

            case "default":
            case "d": CtxType.ShowExtension = 0; break;

            case "visible":
            case "v": CtxType.ShowExtension = +1; break;
            }

            break;

        case "-get-icon":
        case "-gi":
            Console.WriteLine(CtxType.Icon);
            break;

        case "-set-icon":
        case "-si":
            CtxType.Icon = ReadParameter();
            break;

        case "-get-perceived":
        case "-gp":
            Console.WriteLine(CtxType.Perceived);
            break;

        case "-set-perceived":
        case "-sp":
            CtxType.Perceived = ReadParameter();
            break;

        case "-get-name":
        case "-gn":
            Console.WriteLine(CtxType.Title);
            break;

        case "-set-name":
        case "-sn":
            CtxType.Title = ReadParameter();
            break;

        case "-associate":
        case "-a":
            CtxType.Verbs["open"].Command = "\"" + ReadParameter() + "\" \"%1\"";
            CtxType.Verbs.Default         = "open";
            break;

        case "-verb":
        case "-v":
            CtxVerb = CtxType.Verbs[ReadParameter()];
            break;

        default:
            CtxVerb = CtxType.Verbs[RawArgs[PassIndex]];
            break;
        }
    }
        public static void AdjustedCooldown_RapidFire_Postfix(ref Verb_Shoot __instance, Verb ownerVerb, Pawn attacker, ref float __result)
        {
            bool RapidFire = false;

            if (ownerVerb.EquipmentSource != null)
            {
                //    Log.Message("ownerVerb.EquipmentSource");
                if (!ownerVerb.EquipmentSource.AllComps.NullOrEmpty())
                {
                    if (ownerVerb.EquipmentSource.GetComp <CompWeapon_GunSpecialRules>() != null)
                    {
                        if (ownerVerb.EquipmentSource.GetComp <CompWeapon_GunSpecialRules>() is CompWeapon_GunSpecialRules GunExt)
                        {
                            RapidFire = GunExt.RapidFire;
                        }
                    }
                }
            }
            if (ownerVerb.HediffCompSource != null && !ownerVerb.IsMeleeAttack)
            {
                //    Log.Message("ownerVerb.HediffCompSource");
                HediffComp_VerbGiverExtra _VGE = (HediffComp_VerbGiverExtra)ownerVerb.HediffCompSource;

                RapidFire = _VGE.Props.verbEntrys[_VGE.VerbProperties.IndexOf(ownerVerb.verbProps)].RapidFire;
            }
            if (RapidFire && AMASettings.Instance.AllowRapidFire)
            {
                if (ownerVerb.caster.Position.InHorDistOf(((Pawn)ownerVerb.caster).TargetCurrentlyAimingAt.Cell, ownerVerb.verbProps.range / 2))
                {
                    __result = __result / 2;
                }
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Sets the http verb to be used in the request.
 /// </summary>
 /// <param name="httpVerb">The <see cref="Verb"/>.</param>
 /// <returns>The current instance of <see cref="WebApiRequest"/>.</returns>
 public WebApiRequest WithVerb(Verb httpVerb)
 {
     verb = httpVerb;
     return this;
 }
Ejemplo n.º 20
0
 public bool AllowVerbCast(Pawn caster, LocalTargetInfo targ, Verb verb)
 {
     return(!(verb is Verb_LaunchProjectile) || ReachabilityImmediate.CanReachImmediate(caster.Position, targ, caster.Map, PathEndMode.Touch, null));
 }
 public static void HarmsHealthPostfix(Verb verb, ref bool __result)
 {
     __result = __result || verb is Verb_Launch_Stuffable_Projectile || verb is Verb_Shoot_Stuffable;
 }
Ejemplo n.º 22
0
 public ClueItem(Noun n1, Noun n2, Verb v, string sprite, string desc)
 {
     info        = new ClueInfo(n1, n2, v);
     description = desc;
     spriteName  = sprite;
 }
Ejemplo n.º 23
0
 public string GetRequestString()
 {
     return(Verb.ToString() + " " + Parameters);
 }
Ejemplo n.º 24
0
 private void CheckForAutoAttack()
 {
     if (!base.pawn.Downed && !base.pawn.stances.FullBodyBusy)
     {
         collideWithPawns = false;
         bool flag  = base.pawn.story == null || !base.pawn.story.WorkTagIsDisabled(WorkTags.Violent);
         bool flag2 = base.pawn.RaceProps.ToolUser && base.pawn.Faction == Faction.OfPlayer && !base.pawn.story.WorkTagIsDisabled(WorkTags.Firefighting);
         if (flag || flag2)
         {
             Fire fire = null;
             for (int i = 0; i < 9; i++)
             {
                 IntVec3 c = base.pawn.Position + GenAdj.AdjacentCellsAndInside[i];
                 if (c.InBounds(base.pawn.Map))
                 {
                     List <Thing> thingList = c.GetThingList(base.Map);
                     for (int j = 0; j < thingList.Count; j++)
                     {
                         if (flag)
                         {
                             Pawn pawn = thingList[j] as Pawn;
                             if (pawn != null && !pawn.Downed && base.pawn.HostileTo(pawn))
                             {
                                 base.pawn.meleeVerbs.TryMeleeAttack(pawn);
                                 collideWithPawns = true;
                                 return;
                             }
                         }
                         if (flag2)
                         {
                             Fire fire2 = thingList[j] as Fire;
                             if (fire2 != null && (fire == null || fire2.fireSize < fire.fireSize || i == 8) && (fire2.parent == null || fire2.parent != base.pawn))
                             {
                                 fire = fire2;
                             }
                         }
                     }
                 }
             }
             if (fire != null && (!base.pawn.InMentalState || base.pawn.MentalState.def.allowBeatfire))
             {
                 base.pawn.natives.TryBeatFire(fire);
             }
             else if (flag && base.pawn.Faction != null && job.def == JobDefOf.Wait_Combat && (base.pawn.drafter == null || base.pawn.drafter.FireAtWill))
             {
                 Verb currentEffectiveVerb = base.pawn.CurrentEffectiveVerb;
                 if (currentEffectiveVerb != null && !currentEffectiveVerb.verbProps.IsMeleeAttack)
                 {
                     TargetScanFlags targetScanFlags = TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedLOSToNonPawns | TargetScanFlags.NeedThreat;
                     if (currentEffectiveVerb.IsIncendiary())
                     {
                         targetScanFlags |= TargetScanFlags.NeedNonBurning;
                     }
                     Thing thing = (Thing)AttackTargetFinder.BestShootTargetFromCurrentPosition(base.pawn, targetScanFlags);
                     if (thing != null)
                     {
                         base.pawn.TryStartAttack(thing);
                         collideWithPawns = true;
                     }
                 }
             }
         }
     }
 }
        public AdjacencyPairPrefab_request(AdjacencyPair parent, ConversationalParamaters conversationalParamaters, PairParamaters q, Verb verb)
        {
            //init preset paramaters, then pass them up to the base class

            /*describe purpose of paramaters
             * 1. initiating part: request
             * 2. prefered response: grant request
             * 3. disprefered response: deny request
             * 4. default response: noncomittal
             * conditions:
             */

            /*1. initiating options*/
            //initiation 1: get straight to the point and request
            Action initiationDirect = new Action(new Conversation.MovesQueueItem("sense_request", new object[2] {
                q, verb
            }));

            //initation 2: first ask if its ok to make a request, then make the request (nests another request inside this request)
            //more polite, more long-winded, less direct
            Action[] initiatingActionArray;

            //if (not already a nested request) AND (random chance that increases with politeness)
            if ((this.parent.GetType() != typeof(AdjacencyPairPrefab_request)) && (conversationalParamaters.r.Next(4, 10) <= q.politeness))//becomes linearly more likely the higher the politeness is. minimum politeness 4
            {
                //make the adjacency pair then insert in action
                Verb askAQuestion = new Verb(q.initiatingSpeaker, "ask");
                askAQuestion.setMonoTransitive("", "a question");
                //put that into a moveItem
                Conversation.MovesQueueItem m = new Conversation.MovesQueueItem("sense_permission", new object[2] {
                    1, askAQuestion
                });

                //make that verb into an action which will consist of requesting to make a request, and it being either granted or denied

                Action initiationNestedRequest =
                    new Action(
                        new AdjacencyPair("request", this, conversationalParamaters,
                                          new Action[1] {
                    new Action(m)
                },                                           //initiating move
                                          new Action[2] {    //responding moves
                    new Action(new Conversation.MovesQueueItem("sense_request_grantRequest", new object[2] {
                        q, Preferredness.preferred
                    })),
                    new Action(new Conversation.MovesQueueItem("sense_request_denyRequest", new object[2] {
                        q, Preferredness.dispreferred
                    }))
                }
                                          )
                        );

                //put actions in the array
                initiatingActionArray = new Action[] { initiationDirect, initiationNestedRequest };
            }    //end making the second option

            else //only one initiating action
            {
                initiatingActionArray = new Action[] { initiationDirect };
            }

            /*
             * END MAKING INITIATING OPTIONS
             *
             * START MAKING THE RESPONDING OPTIONS
             *
             */

            /*prefered response: grant request*/
            Action preferredResponse = new Action(new Conversation.MovesQueueItem("sense_request_grantRequest", new object[] { q, Preferredness.preferred }));

            preferredResponse.preferredness = Preferredness.preferred;

            /*disprefered response: deny request*/
            Action dispreferredResponse = new Action(new Conversation.MovesQueueItem("sense_request_denyRequest", new object[] { q, Preferredness.dispreferred }));

            preferredResponse.preferredness = Preferredness.dispreferred;

            //now put all the responding actions in an array
            Action[] respondingActionArray = { preferredResponse, dispreferredResponse };

            /*
             * END MAKING RESPONDING OPTIONS
             *
             * PUSH ALL TO BASE
             *
             */

            //send these presets to the base
            base.init("request",
                      parent,
                      conversationalParamaters,
                      initiatingActionArray,
                      respondingActionArray
                      );
        }
Ejemplo n.º 26
0
 private VerbBase CreateVerbBase(Verb verb, string value, object attributes)
 {
     return new VerbBase(verb)
     {
         Value = value,
         Attributes = CreateAttributeDictionary(attributes)
     };
 }
Ejemplo n.º 27
0
    public String sendRequest(String url, Verb v, String mime, String body)
    {

    }
Ejemplo n.º 28
0
        private Job TryGetAttackNearbyEnemyJob(Pawn pawn)
        {
            if (pawn.story != null && pawn.story.WorkTagIsDisabled(WorkTags.Violent))
            {
                return(null);
            }
            bool  flag = pawn.equipment.Primary == null || pawn.equipment.Primary.def.IsMeleeWeapon;
            float num  = 8f;

            if (!flag)
            {
                num = Mathf.Clamp(pawn.equipment.PrimaryEq.PrimaryVerb.verbProps.range * 0.66f, 2f, 20f);
            }
            float maxDist = num;
            Thing thing   = AttackTargetFinder.BestAttackTarget(pawn, TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedLOSToNonPawns | TargetScanFlags.NeedReachable | TargetScanFlags.NeedThreat, null, 0f, maxDist, default(IntVec3), 3.40282347E+38f, false);
            // TODO evaluate if this is necessary?
            Pawn o = thing as Pawn;

            if (o != null)
            {
                if
                (o.Downed || o.health.InPainShock)
                {
                    return(null);
                }
            }

            if (thing == null)
            {
                return(null);
            }
            if (flag || thing.Position.AdjacentTo8Way(pawn.Position))
            {
                return(new Job(JobDefOf.AttackMelee, thing));
            }

            // Check for reload before attacking
            Verb verb = pawn.TryGetAttackVerb();

            if (pawn.equipment.PrimaryEq != null && verb != null && verb == pawn.equipment.PrimaryEq.PrimaryVerb)
            {
                if (pawn.equipment.Primary != null)
                {
                    CompAmmoUser compAmmo = pawn.equipment.Primary.TryGetComp <CompAmmoUser>();
                    if (compAmmo != null)
                    {
                        if (!compAmmo.hasMagazine)
                        {
                            if (compAmmo.useAmmo && !compAmmo.hasAmmo)
                            {
                                return(new Job(JobDefOf.AttackMelee, thing));
                            }
                        }
                        else if (compAmmo.curMagCount <= 0)
                        {
                            Job job = new Job(CR_JobDefOf.ReloadWeapon, pawn, pawn.equipment.Primary);
                            if (job != null)
                            {
                                return(job);
                            }
                        }
                    }
                }
            }

            return(new Job(JobDefOf.AttackStatic, thing));
        }
Ejemplo n.º 29
0
 public static string Label(this Verb verb, AdditionalVerbProps props = null)
 {
     return(VerbLabel(verb, props).CapitalizeFirst());
 }
Ejemplo n.º 30
0
        public override Verb ReflectionHandler(Verb newVerb)
        {
            CompAbilityUserMagic holder = GetPawn.GetComp <CompAbilityUserMagic>();
            bool canReflect             = this.Props.canReflect && holder.IsMagicUser;
            Verb result;

            if (canReflect)
            {
                this.lastAccuracyRoll = this.ReflectionAccuracy();
                VerbProperties verbProperties = new VerbProperties
                {
                    hasStandardCommand = newVerb.verbProps.hasStandardCommand,
                    defaultProjectile  = newVerb.verbProps.defaultProjectile,
                    range               = newVerb.verbProps.range,
                    muzzleFlashScale    = newVerb.verbProps.muzzleFlashScale,
                    warmupTime          = 0f,
                    defaultCooldownTime = 0f,
                    soundCast           = this.Props.deflectSound
                };
                switch (this.lastAccuracyRoll)
                {
                case CompDeflector.CompDeflector.AccuracyRoll.CritialFailure:
                {
                    verbProperties.accuracyLong   = 999f;
                    verbProperties.accuracyMedium = 999f;
                    verbProperties.accuracyShort  = 999f;
                    this.lastShotReflected        = true;
                    break;
                }

                case CompDeflector.CompDeflector.AccuracyRoll.Failure:
                    verbProperties.forcedMissRadius = 50f;
                    verbProperties.accuracyLong     = 0f;
                    verbProperties.accuracyMedium   = 0f;
                    verbProperties.accuracyShort    = 0f;
                    this.lastShotReflected          = false;
                    break;

                case CompDeflector.CompDeflector.AccuracyRoll.Success:
                    verbProperties.accuracyLong   = 999f;
                    verbProperties.accuracyMedium = 999f;
                    verbProperties.accuracyShort  = 999f;
                    this.lastShotReflected        = true;
                    break;

                case CompDeflector.CompDeflector.AccuracyRoll.CriticalSuccess:
                {
                    verbProperties.accuracyLong   = 999f;
                    verbProperties.accuracyMedium = 999f;
                    verbProperties.accuracyShort  = 999f;
                    this.lastShotReflected        = true;
                    break;
                }
                }
                newVerb.verbProps = verbProperties;
                result            = newVerb;
            }
            else
            {
                result = newVerb;
            }
            return(result);
            //return base.ReflectionHandler(newVerb);
        }
        public override IEnumerable <FloatMenuOption> GetFloatMenuOptions(Pawn selPawn)
        {
            // do nothing if not of colony
            if (selPawn.Faction != Faction.OfPlayer)
            {
                yield break;
            }

            // base float menus
            foreach (FloatMenuOption fmo in base.GetFloatMenuOptions(selPawn))
            {
                yield return(fmo);
            }

            // do shooting menu
            // ================

            // Check Reachability
            if (!selPawn.CanReserve(this, 1))
            {
                yield return(new FloatMenuOption("CannotUseReserved".Translate(), null));

                yield break;
            }
            if (!selPawn.CanReach(this, PathEndMode.InteractionCell, Danger.Deadly))
            {
                yield return(new FloatMenuOption("CannotUseNoPath".Translate(), null));

                yield break;
            }

            // Check weapon status
            Verb attackVerb = null;

            if (selPawn != null)
            {
                attackVerb = selPawn.TryGetAttackVerb(false);
            }

            if (attackVerb != null && attackVerb.verbProps != null && !attackVerb.verbProps.MeleeRange)
            {
                Thing       chair;
                JoyGiverDef joyGiverDef = this.GetJoyGiverDef();
                IntVec3     standCell   = Utility_PositionFinder.TryFindWatchBuildingPosition(selPawn, this, this.def.building.watchBuildingStandDistanceRange, joyGiverDef.desireSit, out chair);

                Action action_PracticeShooting = delegate
                {
                    selPawn.drafter.Drafted = false;

                    Job job = new Job(this.GetJobDef(), this, standCell, chair);

                    if (job != null)
                    {
                        selPawn.jobs.TryTakeOrderedJob(job);
                    }
                };

                if (standCell != IntVec3.Invalid)
                {
                    yield return(new FloatMenuOption("TrainingFacility_PracticeShooting".Translate(), action_PracticeShooting));
                }
            }
            else
            {
                yield return(new FloatMenuOption("TrainingFacility_RangedWeaponRequired".Translate(), null));
            }
        }
Ejemplo n.º 32
0
        private static bool HasRangedAttack(IAttackTargetSearcher t)
        {
            Verb currentEffectiveVerb = t.CurrentEffectiveVerb;

            return(currentEffectiveVerb != null && !currentEffectiveVerb.verbProps.IsMeleeAttack);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Determines the armor penetration value of a given dinfo. Attempts to extract the tool/verb from the damage info.
        /// </summary>
        /// <param name="dinfo">DamageInfo to determine penetration for</param>
        /// <returns>Armor penetration value for attack used, 0 if it can't be determined</returns>
        private static float GetPenetrationValue(DamageInfo dinfo)
        {
            if (dinfo.Def.isExplosive)
            {
                return(dinfo.Amount * 0.1f); // Explosions have 10% of their damage as penetration
            }

            if (dinfo.Weapon != null)
            {
                // Case 1: projectile attack (Weapon.projectile indicates that Weapon IS a projectile)
                ProjectilePropertiesCE projectileProps = dinfo.Weapon.projectile as ProjectilePropertiesCE;
                if (projectileProps != null)
                {
                    return(projectileProps.armorPenetration);
                }

                // Case 2: melee attack
                Pawn instigatorPawn = dinfo.Instigator as Pawn;
                if (instigatorPawn != null)
                {
                    // Case 2.1: .. of an equiped melee weapon
                    if (dinfo.Weapon.IsMeleeWeapon)
                    {
                        ThingWithComps equipment = instigatorPawn.equipment?.Primary;

                        if (equipment == null || equipment.def != dinfo.Weapon)
                        {
                            Log.Error("CE tried getting armor penetration from melee weapon " + dinfo.Weapon.defName + " but instigator " + dinfo.Instigator.ToString() + " equipment (" + String.Join(",", instigatorPawn.equipment.AllEquipmentListForReading.Select(x => x.LabelCap).ToArray()) + ") does not match.");
                            return(0);
                        }
                        var penetrationMult = equipment.GetStatValue(CE_StatDefOf.MeleePenetrationFactor);
                        var tool            = equipment.def.tools?.OfType <ToolCE>().GetUsedTool(dinfo);

                        if (tool != null)
                        {
                            return(tool.armorPenetration * penetrationMult);
                        }
                    }

                    // Case 2.2: .. of a ranged weapon
                    if (dinfo.Weapon.IsRangedWeapon)
                    {
                        var tool = dinfo.Weapon.tools?.OfType <ToolCE>().GetUsedTool(dinfo);

                        if (tool != null)
                        {
                            return(tool.armorPenetration);
                        }
                    }

                    // Case 2.3: .. of the pawn
                    if (instigatorPawn.def == dinfo.Weapon)
                    {
                        // meleeVerbs: all verbs considered "melee worthy"
                        Verb availableVerb = instigatorPawn.meleeVerbs.TryGetMeleeVerb();

                        // Case 2.3.1: .. of a weaponized hediff (power claw, scyther blade)
                        HediffCompProperties_VerbGiver compProps = dinfo.WeaponLinkedHediff?.CompPropsFor(typeof(HediffComp_VerbGiver)) as HediffCompProperties_VerbGiver;
                        if (compProps != null)
                        {
                            var tool = compProps.tools?.OfType <ToolCE>().GetUsedTool(dinfo);

                            if (tool != null)
                            {
                                return(tool.armorPenetration);
                            }

                            VerbPropertiesCE verbProps = compProps.verbs?.FirstOrDefault(v => v is VerbPropertiesCE) as VerbPropertiesCE;

                            var verbs = compProps.verbs;

                            if (verbs.Count() > 1)
                            {
                                Log.ErrorOnce("CE :: HediffCompProperties_VerbGiver for " + dinfo.WeaponLinkedHediff + " has multiple VerbPropertiesCE (" + String.Join(",", compProps.verbs.Select(x => x.label).ToArray()) + "). [While evaluating DamageInfo " + dinfo.ToString() + "]", dinfo.WeaponLinkedHediff.GetHashCode() + 128937921);
                            }

                            if (verbProps != null)
                            {
                                Log.ErrorOnce("CE :: HediffCompProperties_VerbGiver from DamageInfo " + dinfo.ToString() + " has VerbPropertiesCE (" + String.Join(",", compProps.verbs.Select(x => x.label).ToArray()) + "), but these are preferably moved to <tools> for B18", dinfo.WeaponLinkedHediff.GetHashCode() + 128937921);

                                return(verbProps.meleeArmorPenetration);
                            }
                        }

                        // AllVerbs: bodyparts of the pawn
                        // Case 2.4: .. of a toolCE/verbPropsCE naturally on the body (hands/fist, head)
                        if (instigatorPawn.verbTracker != null &&
                            !instigatorPawn.verbTracker.AllVerbs.NullOrEmpty())
                        {
                            var verbs = instigatorPawn.verbTracker.AllVerbs
                                        .Where(v => {
                                var toolCE  = v.tool as ToolCE;
                                var propsCE = v.verbProps as VerbPropertiesCE;
                                // Case 2.4.1: .. of a tool restricted by gender
                                return(v.LinkedBodyPartsGroup == dinfo.WeaponBodyPartGroup &&
                                       ((toolCE != null && (toolCE.restrictedGender == Gender.None || toolCE.restrictedGender == instigatorPawn.gender) ||
                                         propsCE != null)));
                            });

                            if (verbs.Count() > 1)
                            {
                                Log.ErrorOnce("CE :: Race " + instigatorPawn.def + " has multiple ToolCE/VerbPropertiesCE (" + String.Join(",", instigatorPawn.verbTracker.AllVerbs.Select(x => x.ToString()).ToArray()) + ") with linkedBodyPartsGroup=" + dinfo.WeaponBodyPartGroup.ToString() + " which can not be distunguished between. Consider using different linkedBodyPartsGroups. [While evaluating DamageInfo " + dinfo.ToString() + "]", instigatorPawn.def.GetHashCode() + 128937921);
                            }

                            if (!verbs.Any())
                            {
                                Log.ErrorOnce("CE :: Pawn " + instigatorPawn.ToString() + " for BodyPartGroup " + dinfo.WeaponBodyPartGroup.ToString() + " could not find matching ToolCE/Verb_MeleeAttackCE (in AllVerbs: " + String.Join(",", instigatorPawn.verbTracker.AllVerbs.Select(x => x.ToString()).ToArray()) + ") [While evaluating DamageInfo " + dinfo.ToString() + "]", instigatorPawn.def.GetHashCode() + 128937921);
                                return(0);
                            }

                            var firstVerb = verbs.First();

                            if (firstVerb.tool is ToolCE)
                            {
                                return((firstVerb.tool as ToolCE).armorPenetration);
                            }

                            if (firstVerb.verbProps is VerbPropertiesCE)
                            {
                                return((firstVerb.verbProps as VerbPropertiesCE).meleeArmorPenetration);
                            }
                        }
                    }
                }
            }
#if DEBUG
            Log.Warning("CE could not determine armor penetration, defaulting");
#endif
            return(9999);    // Really high default value so vanilla damage sources such as GiveInjuriesToKill always penetrate
        }
Ejemplo n.º 34
0
 private static bool CanShootAtFromCurrentPosition(IAttackTarget target, IAttackTargetSearcher searcher, Verb verb)
 {
     return(verb != null && verb.CanHitTargetFrom(searcher.Thing.Position, target.Thing));
 }
Ejemplo n.º 35
0
        private static IAttackTarget GetRandomShootingTargetByScore(List <IAttackTarget> targets, IAttackTargetSearcher searcher, Verb verb)
        {
            Pair <IAttackTarget, float> pair;

            if (ARA_AttackTargetFinder.GetAvailableShootingTargetsByScore(targets, searcher, verb).TryRandomElementByWeight((Pair <IAttackTarget, float> x) => x.Second, out pair))
            {
                return(pair.First);
            }
            return(null);
        }
Ejemplo n.º 36
0
        private static List <Pair <IAttackTarget, float> > GetAvailableShootingTargetsByScore(List <IAttackTarget> rawTargets, IAttackTargetSearcher searcher, Verb verb)
        {
            ARA_AttackTargetFinder.availableShootingTargets.Clear();
            if (rawTargets.Count == 0)
            {
                return(ARA_AttackTargetFinder.availableShootingTargets);
            }
            ARA_AttackTargetFinder.tmpTargetScores.Clear();
            ARA_AttackTargetFinder.tmpCanShootAtTarget.Clear();
            float         num          = 0f;
            IAttackTarget attackTarget = null;

            for (int i = 0; i < rawTargets.Count; i++)
            {
                ARA_AttackTargetFinder.tmpTargetScores.Add(-3.40282347E+38f);
                ARA_AttackTargetFinder.tmpCanShootAtTarget.Add(false);
                if (rawTargets[i] != searcher)
                {
                    bool flag = ARA_AttackTargetFinder.CanShootAtFromCurrentPosition(rawTargets[i], searcher, verb);
                    ARA_AttackTargetFinder.tmpCanShootAtTarget[i] = flag;
                    if (flag)
                    {
                        float shootingTargetScore = ARA_AttackTargetFinder.GetShootingTargetScore(rawTargets[i], searcher, verb);
                        ARA_AttackTargetFinder.tmpTargetScores[i] = shootingTargetScore;
                        if (attackTarget == null || shootingTargetScore > num)
                        {
                            attackTarget = rawTargets[i];
                            num          = shootingTargetScore;
                        }
                    }
                }
            }
            if (num < 1f)
            {
                if (attackTarget != null)
                {
                    ARA_AttackTargetFinder.availableShootingTargets.Add(new Pair <IAttackTarget, float>(attackTarget, 1f));
                }
            }
            else
            {
                float num2 = num - 30f;
                for (int j = 0; j < rawTargets.Count; j++)
                {
                    if (rawTargets[j] != searcher)
                    {
                        if (ARA_AttackTargetFinder.tmpCanShootAtTarget[j])
                        {
                            float num3 = ARA_AttackTargetFinder.tmpTargetScores[j];
                            if (num3 >= num2)
                            {
                                float second = Mathf.InverseLerp(num - 30f, num, num3);
                                ARA_AttackTargetFinder.availableShootingTargets.Add(new Pair <IAttackTarget, float>(rawTargets[j], second));
                            }
                        }
                    }
                }
            }
            return(ARA_AttackTargetFinder.availableShootingTargets);
        }
		protected static IRouteContext CreateContext(string appPath, Verb httpMethod)
		{
			return new RouteContext(new StubRequest(httpMethod.ToString()), null, appPath, new Hashtable());
		}	
Ejemplo n.º 38
0
        public static IAttackTarget BestAttackTarget(IAttackTargetSearcher searcher, TargetScanFlags flags, Predicate <Thing> validator = null, float minDist = 0f, float maxDist = 9999f, IntVec3 locus = default(IntVec3), float maxTravelRadiusFromLocus = 3.40282347E+38f, bool canBash = false)
        {
            Thing searcherThing = searcher.Thing;
            Pawn  searcherPawn  = searcher as Pawn;
            Verb  verb          = searcher.CurrentEffectiveVerb;

            if (verb == null)
            {
                //Log.Error("BestAttackTarget with " + searcher + " who has no attack verb.");
                return(null);
            }
            bool  onlyTargetMachines = verb != null && verb.IsEMP();
            float minDistanceSquared = minDist * minDist;
            float num = maxTravelRadiusFromLocus + verb.verbProps.range;
            float maxLocusDistSquared         = num * num;
            Func <IntVec3, bool> losValidator = null;

            if ((byte)(flags & TargetScanFlags.LOSBlockableByGas) != 0)
            {
                losValidator = delegate(IntVec3 vec3)
                {
                    Gas gas = vec3.GetGas(searcherThing.Map);
                    return(gas == null || !gas.def.gas.blockTurretTracking);
                };
            }
            Predicate <IAttackTarget> innerValidator = delegate(IAttackTarget t)
            {
                Thing thing = t.Thing;
                if (t == searcher)
                {
                    return(false);
                }
                if (minDistanceSquared > 0f && (float)(searcherThing.Position - thing.Position).LengthHorizontalSquared < minDistanceSquared)
                {
                    return(false);
                }
                if (maxTravelRadiusFromLocus < 9999f && (float)(thing.Position - locus).LengthHorizontalSquared > maxLocusDistSquared)
                {
                    return(false);
                }
                if (!searcherThing.HostileTo(thing))
                {
                    return(false);
                }
                if (validator != null && !validator(thing))
                {
                    return(false);
                }
                if ((byte)(flags & TargetScanFlags.NeedLOSToAll) != 0 && !searcherThing.CanSee(thing, losValidator))
                {
                    if (t is Pawn)
                    {
                        if ((byte)(flags & TargetScanFlags.NeedLOSToPawns) != 0)
                        {
                            return(false);
                        }
                    }
                    else if ((byte)(flags & TargetScanFlags.NeedLOSToNonPawns) != 0)
                    {
                        return(false);
                    }
                }
                if ((byte)(flags & TargetScanFlags.NeedThreat) != 0 && t.ThreatDisabled(searcher))
                {
                    return(false);
                }
                Pawn pawn = t as Pawn;
                if (onlyTargetMachines && pawn != null && pawn.RaceProps.IsFlesh)
                {
                    return(false);
                }
                if ((byte)(flags & TargetScanFlags.NeedNonBurning) != 0 && thing.IsBurning())
                {
                    return(false);
                }
                if (searcherThing.def.race != null && searcherThing.def.race.intelligence >= Intelligence.Humanlike)
                {
                    CompExplosive compExplosive = thing.TryGetComp <CompExplosive>();
                    if (compExplosive != null && compExplosive.wickStarted)
                    {
                        return(false);
                    }
                }
                if (thing.def.size.x == 1 && thing.def.size.z == 1)
                {
                    if (thing.Position.Fogged(thing.Map))
                    {
                        return(false);
                    }
                }
                else
                {
                    bool flag2 = false;
                    CellRect.CellRectIterator iterator = thing.OccupiedRect().GetIterator();
                    while (!iterator.Done())
                    {
                        if (!iterator.Current.Fogged(thing.Map))
                        {
                            flag2 = true;
                            break;
                        }
                        iterator.MoveNext();
                    }
                    if (!flag2)
                    {
                        return(false);
                    }
                }
                return(true);
            };

            if (ARA_AttackTargetFinder.HasRangedAttack(searcher))
            {
                //Log.Warning("Finder: Range detected. Verb is " + verb);
                //Log.Warning("Finder: Pawn " + searcherPawn.Faction);
                ARA_AttackTargetFinder.tmpTargets.Clear();

                //This needs to be fixed. Can't use searcherThing. Doing this the hard way.
                //Set request for all attackable.
                ThingRequest        thingReq  = ThingRequest.ForGroup(ThingRequestGroup.AttackTarget);
                IEnumerable <Thing> searchSet = searcherThing.Map.listerThings.ThingsMatching(thingReq);

                foreach (IAttackTarget iTarget in searchSet)
                {
                    ARA_AttackTargetFinder.tmpTargets.Add(iTarget);
                }

                if ((byte)(flags & TargetScanFlags.NeedReachable) != 0)
                {
                    Predicate <IAttackTarget> oldValidator = innerValidator;
                    innerValidator = ((IAttackTarget t) => oldValidator(t) && ARA_AttackTargetFinder.CanReach(searcherThing, t.Thing, canBash));
                }
                bool flag = false;
                if (searcherThing.Faction != Faction.OfPlayer)
                {
                    //Log.Warning("Finder: Target available : " + ARA_AttackTargetFinder.tmpTargets.Count);
                    for (int i = 0; i < ARA_AttackTargetFinder.tmpTargets.Count; i++)
                    {
                        IAttackTarget attackTarget = ARA_AttackTargetFinder.tmpTargets[i];
                        if (attackTarget.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) && innerValidator(attackTarget) && ARA_AttackTargetFinder.CanShootAtFromCurrentPosition(attackTarget, searcher, verb))
                        {
                            //Log.Warning("Finder: flag is true");
                            flag = true;
                            break;
                        }
                    }
                }

                IAttackTarget result;
                if (flag)
                {
                    //Log.Warning("Finder: FlagTrue result");
                    ARA_AttackTargetFinder.tmpTargets.RemoveAll((IAttackTarget x) => !x.Thing.Position.InHorDistOf(searcherThing.Position, maxDist) || !innerValidator(x));
                    //Log.Warning("Finder: Target Avaliable : " + ARA_AttackTargetFinder.tmpTargets.Count);
                    result = ARA_AttackTargetFinder.GetRandomShootingTargetByScore(ARA_AttackTargetFinder.tmpTargets, searcher, verb);
                }
                else
                {
                    Predicate <Thing> validator2;
                    if ((byte)(flags & TargetScanFlags.NeedReachableIfCantHitFromMyPos) != 0 && (byte)(flags & TargetScanFlags.NeedReachable) == 0)
                    {
                        //Log.Warning("Finder: Needs reachable");
                        validator2 = ((Thing t) => innerValidator((IAttackTarget)t) && (ARA_AttackTargetFinder.CanReach(searcherThing, t, canBash) || ARA_AttackTargetFinder.CanShootAtFromCurrentPosition((IAttackTarget)t, searcher, verb)));
                    }
                    else
                    {
                        //Log.Warning("Finder: Running normal validator");
                        validator2 = ((Thing t) => innerValidator((IAttackTarget)t));
                    }
                    result = (IAttackTarget)GenClosest.ClosestThing_Global(searcherThing.Position, ARA_AttackTargetFinder.tmpTargets, maxDist, validator2, null);
                }
                ARA_AttackTargetFinder.tmpTargets.Clear();
                //Log.Warning("Trying to return result " + result);
                return(result);
            }
            //Log.Warning("Returning Null");
            return(null);
        }
Ejemplo n.º 39
0
    static void ProcessVerb()
    {
        switch (RawArgs[PassIndex].ToLower())
        {
        case "-get-command":
        case "-gc":
            Console.WriteLine(CtxVerb.Command);
            break;

        case "-set-command":
        case "-sc":
            CtxVerb.Command = ReadParameter();
            break;

        case "-get-hidden":
        case "-gh":
            Console.WriteLine(CtxVerb.IsExtended ? "True" : "False");
            break;

        case "-set-hidden":
        case "-sh":
            string p = ReadParameter().ToLower();
            if (p == "true" || p == "t")
            {
                CtxVerb.IsExtended = true;
            }
            else if (p == "false" || p == "f")
            {
                CtxVerb.IsExtended = false;
            }
            else
            {
                throw new SyntaxError();
            }
            break;

        case "-type":
        case "-t":
            CtxType = new Type(ReadParameter());
            CtxVerb = null;
            break;

        case "-get-icon":
        case "-gi":
            Console.WriteLine(CtxVerb.Icon);
            break;

        case "-set-icon":
        case "-si":
            CtxVerb.Icon = ReadParameter();
            break;

        case "-get-name":
        case "-gn":
            Console.WriteLine(CtxVerb.Title);
            break;

        case "-set-name":
        case "-sn":
            CtxVerb.Title = ReadParameter();
            break;

        case "-get-program":
        case "-gp":
            Console.WriteLine(CtxVerb.Program);
            break;

        case "-set-program":
        case "-sp":
            CtxVerb.Command = "\"" + ReadParameter() + "\" \"%1\"";
            break;

        case "-verb":
        case "-v":
            CtxVerb = CtxType.Verbs[ReadParameter()];
            break;

        default:
            CtxVerb = CtxType.Verbs[RawArgs[PassIndex]];
            break;
        }
    }
Ejemplo n.º 40
0
        private static float GetShootingTargetScore(IAttackTarget target, IAttackTargetSearcher searcher, Verb verb)
        {
            float num = 60f;

            num -= Mathf.Min((target.Thing.Position - searcher.Thing.Position).LengthHorizontal, 40f);
            if (target.TargetCurrentlyAimingAt == searcher.Thing)
            {
                num += 10f;
            }
            if (searcher.LastAttackedTarget == target.Thing && Find.TickManager.TicksGame - searcher.LastAttackTargetTick <= 300)
            {
                num += 40f;
            }
            num -= CoverUtility.CalculateOverallBlockChance(target.Thing.Position, searcher.Thing.Position, searcher.Thing.Map) * 10f;
            Pawn pawn = target as Pawn;

            if (pawn != null && pawn.RaceProps.Animal && pawn.Faction != null && !pawn.IsFighting())
            {
                num -= 50f;
            }
            return(num + ARA_AttackTargetFinder.FriendlyFireShootingTargetScoreOffset(target, searcher, verb));
        }
Ejemplo n.º 41
0
        private TwiMLBuilderElement CreateBuilderElement(Verb verb, string value, object attributes, params Tuple<Verb, string, object>[] children)
        {
            List<VerbBase> childList = new List<VerbBase>();
            if (children != null)
                childList = children.Select(x => CreateVerbBase(x.Item1, x.Item2, x.Item3)).ToList();

            return new TwiMLBuilderElement()
            {
                Verb = CreateVerbBase(verb, value, attributes),
                Children = childList
            };
        }
Ejemplo n.º 42
0
        public float calcPawnSightRange(IntVec3 position, bool forTargeting, bool shouldMove)
        {
            if (pawn == null)
            {
                Log.Error("calcPawnSightRange performed on non pawn thing");
                return(0);
            }

#if InternalProfile
            ProfilingUtils.startProfiling("CompFieldOfViewWatcher.calcPawnSightRange");
#endif
            float sightRange = 0f;

            initMap();

            bool sleeping = !isMechanoid && pawn.CurJob != null && pawn.jobs.curDriver.asleep;

            if (!shouldMove && !sleeping && (pawnPather == null || !pawnPather.Moving))
            {
                Verb attackVerb = null;
                if (pawn.CurJob != null)
                {
                    JobDef jobDef = pawn.CurJob.def;
                    if (jobDef == JobDefOf.ManTurret)
                    {
                        Building_Turret mannedTurret = pawn.CurJob.targetA.Thing as Building_Turret;
                        if (mannedTurret != null)
                        {
                            attackVerb = mannedTurret.AttackVerb;
                        }
                    }
                    else if (jobDef == JobDefOf.AttackStatic || jobDef == JobDefOf.AttackMelee || jobDef == JobDefOf.Wait_Combat || jobDef == JobDefOf.Hunt)
                    {
                        if (pawn.equipment != null)
                        {
                            ThingWithComps primary = pawn.equipment.Primary;
                            if (primary != null && primary.def.IsRangedWeapon)
                            {
                                attackVerb = primary.GetComp <CompEquippable>().PrimaryVerb;
                            }
                        }
                    }
                }

                if (attackVerb != null && attackVerb.verbProps.range > baseViewRange && attackVerb.verbProps.requireLineOfSight && attackVerb.EquipmentSource.def.IsRangedWeapon)
                {
                    float attackVerbRange = attackVerb.verbProps.range;
                    if (baseViewRange < attackVerbRange)
                    {
                        int ticksStanding = Find.TickManager.TicksGame - lastMovementTick;

                        float statValue     = pawn.GetStatValue(StatDefOf.AimingDelayFactor, true);
                        int   ticksToSearch = (attackVerb.verbProps.warmupTime * statValue).SecondsToTicks() * Mathf.RoundToInt((attackVerbRange - baseViewRange) / 2);

                        if (ticksStanding >= ticksToSearch)
                        {
                            sightRange = attackVerbRange * capacities.GetLevel(PawnCapacityDefOf.Sight);
                        }
                        else
                        {
                            int incValue = Mathf.RoundToInt((attackVerbRange - baseViewRange) * ((float)ticksStanding / ticksToSearch));

                            sightRange = (baseViewRange + incValue) * capacities.GetLevel(PawnCapacityDefOf.Sight);
                        }
                    }
                }
            }

            if (sightRange == 0f)
            {
                sightRange = baseViewRange * capacities.GetLevel(PawnCapacityDefOf.Sight);
            }

            if (!forTargeting && sleeping)
            {
                // Sleeping: sight reduced to 20% (if not for targeting).
                sightRange *= 0.2f;
            }
            // TODO: Apply moving penality?

            /*else if (!calcOnlyBase && pawnPather.Moving) {
             *      // When moving, sight reduced to 90%s.
             *      sightRange *= 0.9f;
             * }
             */

            // Check if standing on an affect view object.
            List <CompAffectVision> compsAffectVision = mapCompSeenFog.compAffectVisionGrid[(position.z * mapSizeX) + position.x];
            int compsCount = compsAffectVision.Count;
            for (int i = 0; i < compsCount; i++)
            {
                sightRange *= compsAffectVision[i].Props.fovMultiplier;
            }

            // Additional dark and weather debuff.
            if (!isMechanoid)
            {
                float currGlow = glowGrid.GameGlowAt(position);
                if (currGlow != 1f)
                {
                    float darkModifier = 0.6f;
                    // Each bionic eye reduce the dark debuff by 20.
                    int hediffsCount = hediffs.Count;
                    for (int i = 0; i < hediffsCount; i++)
                    {
                        if (hediffs[i].def == HediffDefOf.BionicEye)
                        {
                            darkModifier += 0.2f;
                        }
                    }

                    // Apply only if to debuff.
                    if (darkModifier < 1f)
                    {
                        // Adjusted to glow (100% full light - 60% dark).
                        sightRange *= Mathf.Lerp(darkModifier, 1f, currGlow);
                    }
                }

                if (!roofGrid.Roofed(position.x, position.z))
                {
                    float weatherFactor = weatherManager.CurWeatherAccuracyMultiplier;
                    if (weatherFactor != 1f)
                    {
                        // Weather factor is applied by half.
                        sightRange *= Mathf.Lerp(0.5f, 1f, weatherFactor);
                    }
                }
            }

            // Mininum sight.
            if (sightRange < 1f)
            {
                return(1);
            }

#if InternalProfile
            ProfilingUtils.stopProfiling("CompFieldOfViewWatcher.calcPawnSightRange");
#endif
            return(sightRange);
        }
Ejemplo n.º 43
0
 public VerbEntry(Verb verb, Pawn pawn, Thing equipment = null)
 {
     this.verb = verb;
     this.cachedSelectionWeight = verb.verbProps.AdjustedMeleeSelectionWeight(verb, pawn, equipment);
 }
Ejemplo n.º 44
0
            public static Stream WebInvoke(Uri uri, Verb verb, Stream input, WebMessageFormat requestFormat, bool hasOutput)
            {
                var request = WebRequest.Create(uri);
                switch (verb)
                {
                    case Verb.Get:
                        request.Method = "GET";
                        break;
                    case Verb.Post:
                        request.Method = "POST";
                        break;
                    case Verb.Put:
                        request.Method = "PUT";
                        break;
                    case Verb.Delete:
                        request.Method = "DELETE";
                        break;
                    default:
                        throw new NotSupportedException();
                }

                if (input != null)
                {
                    input.Seek(0L, SeekOrigin.Begin);

                    switch (requestFormat)
                    {
                        case WebMessageFormat.Xml:
                            request.ContentType = "application/xml";
                            break;

                        case WebMessageFormat.Json:
                            request.ContentType = "application/json";
                            break;
                    }

                    request.ContentLength = input.Length;

                    using (var requestStream = request.GetRequestStream())
                    {
                        var bytes = new byte[1024];
                        var read = 1;
                        while (read > 0)
                        {
                            read = input.Read(bytes, 0, bytes.Length);
                            requestStream.Write(bytes, 0, read);
                        }
                    }
                }

                try
                {
                    using (var response = request.GetResponse())
                    {
                        if (!hasOutput)
                            return null;
                        var length = (int) response.ContentLength;
                        var copy = (length > 0) ? new MemoryStream(length) : new MemoryStream();
                        response.GetResponseStream().CopyTo(copy);
                        copy.Seek(0L, SeekOrigin.Begin);
                        return copy;
                    }
                }
                catch (WebException ex)
                {
                    var message = string.Format("The remote server returned an unexpected response: {0}", ex.Message);
                    throw new CommunicationException(message, ex);
                }
            }
Ejemplo n.º 45
0
 public Command(Verb verb,int time)
 {
     Verb = verb;
     Time = time;
 }
Ejemplo n.º 46
0
 private static string VerbLabel(Verb verb, AdditionalVerbProps props = null)
 {
     return(FirstNonEmptyString(props?.visualLabel, verb.verbProps.label,
                                (verb as Verb_LaunchProjectile)?.Projectile.LabelCap, verb.caster?.def?.label));
 }
Ejemplo n.º 47
0
 public static String sendRequest(String url, Verb v, String mime, String body)
 {
     return getPage(url);
 }
 // Token: 0x06000032 RID: 50 RVA: 0x00003C9C File Offset: 0x00001E9C
 public override bool AllowVerbCast(Verb v)
 {
     return(true);
 }
		/// <summary>
		/// Checks it the <paramref name="testMethod"/> is accessible from the <paramref name="allowedMethods"/>.
		/// </summary>
		/// <param name="allowedMethods">THe verbs, http methods, that are allowed.</param>
		/// <param name="testMethod">The verb, http method, that is being testing for access.</param>
		/// <returns><c>true</c> if the <paramref name="testMethod"/> is an allowed method in the <paramref name="allowedMethods"/> otherwise <c>false</c></returns>
		public static bool ForHttpMethod(Verb allowedMethods, Verb testMethod)
		{
			return (allowedMethods & testMethod) == testMethod;
		}
Ejemplo n.º 50
0
        protected void GetNextVerb(Verb verb = null)
        {
            if (Util.Verben == null || Util.Verben.Count == 0)
            {
                Device.StartTimer(TimeSpan.FromSeconds(2), () =>
                {
                    DisplayAlert("Hallo", "Deine Verben Wörterbuch ist leer. Vielleicht dein Handy ist nicht verbindung.", "OK");
                    return(false);
                });
            }
            else
            {
                if (NumbersKnown.Count == Util.Verben.Count)
                {
                    NumbersKnown = new List <int>();
                }

                var index = 0;

                if (verb == null)
                {
                    index = new Random().Next(0, Util.Verben.Count);

                    while (NumbersKnown.Contains(index))
                    {
                        index = new Random().Next(0, Util.Verben.Count);
                    }

                    NumbersKnown.Add(index);
                    CurrentVerb = Util.Verben[index];
                }
                else
                {
                    CurrentVerb = verb;
                    index       = Util.Verben.IndexOf(verb);
                }

                lblWort.Text    = CurrentVerb.Name;
                lblArt.Text     = CurrentVerb.Art;
                lblPerfekt.Text = CurrentVerb.Perfekt;

                grdKonjugation.Children.Clear();
                var lblIndikativPrasens = new Label
                {
                    Text     = "Indikativ Präsens",
                    FontSize = 18,
                    HorizontalTextAlignment = TextAlignment.Center,
                    TextColor      = Color.FromHex("#003994"),
                    FontAttributes = FontAttributes.Bold
                };

                grdKonjugation.Children.Add(lblIndikativPrasens, 0, 0);
                Grid.SetColumnSpan(lblIndikativPrasens, 6);

                var lblIndikativPrateritum = new Label
                {
                    Text     = "Indikativ Präteritum",
                    FontSize = 18,
                    HorizontalTextAlignment = TextAlignment.Center,
                    TextColor      = Color.FromHex("#003994"),
                    FontAttributes = FontAttributes.Bold
                };


                OrganizierenKonjugation(CurrentVerb.Prasens, true);

                grdKonjugation.Children.Add(lblIndikativPrateritum, 0, 7);
                Grid.SetColumnSpan(lblIndikativPrateritum, 6);

                OrganizierenKonjugation(CurrentVerb.Prateritum, false);

                var index2 = new Random().Next(0, Util.Verben.Count);
                var index3 = new Random().Next(0, Util.Verben.Count);
                while (index2 == index)
                {
                    index2 = new Random().Next(0, Util.Verben.Count);
                }
                while (index3 == index || index3 == index2)
                {
                    index3 = new Random().Next(0, Util.Verben.Count);
                }

                var indexs = new List <int>()
                {
                    index, index2, index3
                };

                var indexOptionOne = new Random().Next(0, indexs.Count);
                lblOptionOne.Text = Util.Verben[indexs[indexOptionOne]].Ubersetzung;

                var indexOptionTwo = new Random().Next(0, indexs.Count);
                while (indexOptionTwo == indexOptionOne)
                {
                    indexOptionTwo = new Random().Next(0, indexs.Count);
                }
                lblOptionTwo.Text = Util.Verben[indexs[indexOptionTwo]].Ubersetzung;

                var indexOptionThree = new Random().Next(0, indexs.Count);
                while (indexOptionThree == indexOptionOne || indexOptionThree == indexOptionTwo)
                {
                    indexOptionThree = new Random().Next(0, indexs.Count);
                }
                lblOptionThree.Text = Util.Verben[indexs[indexOptionThree]].Ubersetzung;
            }
        }
Ejemplo n.º 51
0
 internal static IEnumerable<int> DiscoverCrudStatusCodeNumbers(this MethodInfo method, Verb verb, Type controllerType = null)
 {
     return method.DiscoverCrudStatusCodes(verb, controllerType).Select(httpStatusCode => (int)httpStatusCode).Distinct();
 }
Ejemplo n.º 52
0
		public ApplyPrototype(Verb verb, params IFuturePrototype[] prototypeParams)
		{
			this.verb = verb;
			this.prototypeParams = prototypeParams;
		}
Ejemplo n.º 53
0
        private static float FriendlyFireShootingTargetScoreOffset(IAttackTarget target, IAttackTargetSearcher searcher, Verb verb)
        {
            if (verb.verbProps.ai_AvoidFriendlyFireRadius <= 0f)
            {
                return(0f);
            }
            Map     map      = target.Thing.Map;
            IntVec3 position = target.Thing.Position;
            int     num      = GenRadial.NumCellsInRadius(verb.verbProps.ai_AvoidFriendlyFireRadius);
            float   num2     = 0f;

            for (int i = 0; i < num; i++)
            {
                IntVec3 intVec = position + GenRadial.RadialPattern[i];
                if (intVec.InBounds(map))
                {
                    bool         flag      = true;
                    List <Thing> thingList = intVec.GetThingList(map);
                    for (int j = 0; j < thingList.Count; j++)
                    {
                        if (thingList[j] is IAttackTarget && thingList[j] != target)
                        {
                            if (flag)
                            {
                                if (!GenSight.LineOfSight(position, intVec, map, true, null, 0, 0))
                                {
                                    break;
                                }
                                flag = false;
                            }
                            float num3;
                            if (thingList[j] == searcher)
                            {
                                num3 = 40f;
                            }
                            else if (thingList[j] is Pawn)
                            {
                                num3 = ((!thingList[j].def.race.Animal) ? 18f : 7f);
                            }
                            else
                            {
                                num3 = 10f;
                            }
                            if (searcher.Thing.HostileTo(thingList[j]))
                            {
                                num2 += num3 * 0.6f;
                            }
                            else
                            {
                                num2 -= num3;
                            }
                        }
                    }
                }
            }
            return(Mathf.Min(num2, 0f));
        }
Ejemplo n.º 54
0
        public static IEnumerable <Gizmo> GetGizmosForVerb(this Verb verb, ManagedVerb man = null)
        {
            var props = man?.Props;

            Thing ownerThing = null;

            switch (verb.DirectOwner)
            {
            case ThingWithComps twc when twc.TryGetComp <Comp_VerbGiver>() is Comp_VerbGiver giver:
                ownerThing = twc;

                props = giver.PropsFor(verb);
                break;

            case Thing thing:
                ownerThing = thing;
                break;

            case Comp_VerbGiver comp:
                ownerThing = comp.parent;
                props      = comp.PropsFor(verb);
                break;

            case CompEquippable eq:
                ownerThing = eq.parent;
                break;

            case HediffComp_ExtendedVerbGiver hediffGiver:
                props = hediffGiver.PropsFor(verb);
                break;
            }

            Command gizmo;
            var     command = new Command_VerbTarget {
                verb = verb
            };

            gizmo = command;


            if (ownerThing != null)
            {
                gizmo.defaultDesc = FirstNonEmptyString(props?.description, ownerThing.def.LabelCap + ": " +
                                                        ownerThing
                                                        .def?.description?
                                                        .Truncate(500, __truncateCache)?
                                                        .CapitalizeFirst());
                gizmo.icon = verb.Icon(props, ownerThing, false);
            }
            else if (verb.DirectOwner is HediffComp_VerbGiver hediffGiver)
            {
                var hediff = hediffGiver.parent;
                gizmo.defaultDesc = FirstNonEmptyString(props?.description, hediff.def.LabelCap + ": " +
                                                        hediff.def.description
                                                        .Truncate(500, __truncateCache)
                                                        .CapitalizeFirst());
                gizmo.icon = verb.Icon(props, null, false);
            }

            gizmo.tutorTag     = "VerbTarget";
            gizmo.defaultLabel = verb.Label(props);

            if (verb.Caster.Faction != Faction.OfPlayer)
            {
                gizmo.Disable("CannotOrderNonControlled".Translate());
            }
            else if (verb.CasterIsPawn)
            {
                if (verb.CasterPawn.WorkTagIsDisabled(WorkTags.Violent))
                {
                    gizmo.Disable("IsIncapableOfViolence".Translate(verb.CasterPawn.LabelShort,
                                                                    verb.CasterPawn));
                }
                else if (verb.CasterPawn.drafter != null && !verb.CasterPawn.drafter.Drafted)
                {
                    gizmo.Disable("IsNotDrafted".Translate(verb.CasterPawn.LabelShort,
                                                           verb.CasterPawn));
                }
                else if (verb.CasterPawn.InMentalState)
                {
                    gizmo.Disable("CannotOrderNonControlled".Translate());
                }
            }

            yield return(gizmo);


            if (props != null && props.canBeToggled && man != null && verb.caster.Faction == Faction.OfPlayer &&
                props.separateToggle || verb.CasterIsPawn && verb.CasterPawn.RaceProps.Animal)
            {
                yield return(new Command_ToggleVerbUsage(man));
            }
        }
		/// <summary>
		/// Checks if the <paramref name="httpMethod"/> is accessible.
		/// </summary>
		/// <param name="httpMethod">The Http Method to check.</param>
		/// <returns><c>true</c> if <paramref name="httpMethod"/> is allowed, otherwise <c>false.</c></returns>
		public bool ForHttpMethod(Verb httpMethod)
		{
			return ForHttpMethod(Verb, httpMethod);
		}
Ejemplo n.º 56
0
        public static bool TryFindCastPosition(CastPositionRequest newReq, out IntVec3 dest)
        {
            req       = newReq;
            casterLoc = req.caster.Position;
            targetLoc = req.target.Position;
            verb      = req.verb;
            avoidGrid = newReq.caster.GetAvoidGrid(onlyIfLordAllows: false);
            if (verb == null)
            {
                Log.Error(req.caster + " tried to find casting position without a verb.");
                dest = IntVec3.Invalid;
                return(false);
            }
            if (req.maxRegions > 0)
            {
                Region region = casterLoc.GetRegion(req.caster.Map);
                if (region == null)
                {
                    Log.Error("TryFindCastPosition requiring region traversal but root region is null.");
                    dest = IntVec3.Invalid;
                    return(false);
                }
                inRadiusMark = Rand.Int;
                RegionTraverser.MarkRegionsBFS(region, null, newReq.maxRegions, inRadiusMark);
                if (req.maxRangeFromLocus > 0.01f)
                {
                    Region locusReg = req.locus.GetRegion(req.caster.Map);
                    if (locusReg == null)
                    {
                        Log.Error("locus " + req.locus + " has no region");
                        dest = IntVec3.Invalid;
                        return(false);
                    }
                    if (locusReg.mark != inRadiusMark)
                    {
                        inRadiusMark = Rand.Int;
                        RegionTraverser.BreadthFirstTraverse(region, null, delegate(Region r)
                        {
                            r.mark = inRadiusMark;
                            req.maxRegions++;
                            return(r == locusReg);
                        });
                    }
                }
            }
            CellRect cellRect = CellRect.WholeMap(req.caster.Map);

            if (req.maxRangeFromCaster > 0.01f)
            {
                int      num       = Mathf.CeilToInt(req.maxRangeFromCaster);
                CellRect otherRect = new CellRect(casterLoc.x - num, casterLoc.z - num, num * 2 + 1, num * 2 + 1);
                cellRect.ClipInsideRect(otherRect);
            }
            int      num2       = Mathf.CeilToInt(req.maxRangeFromTarget);
            CellRect otherRect2 = new CellRect(targetLoc.x - num2, targetLoc.z - num2, num2 * 2 + 1, num2 * 2 + 1);

            cellRect.ClipInsideRect(otherRect2);
            if (req.maxRangeFromLocus > 0.01f)
            {
                int      num3       = Mathf.CeilToInt(req.maxRangeFromLocus);
                CellRect otherRect3 = new CellRect(targetLoc.x - num3, targetLoc.z - num3, num3 * 2 + 1, num3 * 2 + 1);
                cellRect.ClipInsideRect(otherRect3);
            }
            bestSpot     = IntVec3.Invalid;
            bestSpotPref = 0.001f;
            maxRangeFromCasterSquared = req.maxRangeFromCaster * req.maxRangeFromCaster;
            maxRangeFromTargetSquared = req.maxRangeFromTarget * req.maxRangeFromTarget;
            maxRangeFromLocusSquared  = req.maxRangeFromLocus * req.maxRangeFromLocus;
            rangeFromTarget           = (req.caster.Position - req.target.Position).LengthHorizontal;
            rangeFromTargetSquared    = (float)(req.caster.Position - req.target.Position).LengthHorizontalSquared;
            optimalRangeSquared       = verb.verbProps.range * 0.8f * (verb.verbProps.range * 0.8f);
            EvaluateCell(req.caster.Position);
            if ((double)bestSpotPref >= 1.0)
            {
                dest = req.caster.Position;
                return(true);
            }
            float    slope    = -1f / CellLine.Between(req.target.Position, req.caster.Position).Slope;
            CellLine cellLine = new CellLine(req.target.Position, slope);
            bool     flag     = cellLine.CellIsAbove(req.caster.Position);

            CellRect.CellRectIterator iterator = cellRect.GetIterator();
            while (!iterator.Done())
            {
                IntVec3 current = iterator.Current;
                if (cellLine.CellIsAbove(current) == flag && cellRect.Contains(current))
                {
                    EvaluateCell(current);
                }
                iterator.MoveNext();
            }
            if (bestSpot.IsValid && bestSpotPref > 0.33f)
            {
                dest = bestSpot;
                return(true);
            }
            CellRect.CellRectIterator iterator2 = cellRect.GetIterator();
            while (!iterator2.Done())
            {
                IntVec3 current2 = iterator2.Current;
                if (cellLine.CellIsAbove(current2) != flag && cellRect.Contains(current2))
                {
                    EvaluateCell(current2);
                }
                iterator2.MoveNext();
            }
            if (bestSpot.IsValid)
            {
                dest = bestSpot;
                return(true);
            }
            dest = casterLoc;
            return(false);
        }
		/// <summary>
		/// Constructs a AccessibleThroughAttribute with 
		/// the specified <paramref name="verb"/>.
		/// </summary>
		/// <param name="verb">The <see cref="Verb"/> to allow for this action.</param>
		public AccessibleThroughAttribute(Verb verb)
		{
			this.verb = verb;
		}
Ejemplo n.º 58
0
 public List <VerbEntry> GetUpdatedAvailableVerbsList(bool terrainTools)
 {
     Pawn_MeleeVerbs.meleeVerbs.Clear();
     if (!terrainTools)
     {
         List <Verb> allVerbs = this.pawn.verbTracker.AllVerbs;
         for (int i = 0; i < allVerbs.Count; i++)
         {
             if (allVerbs[i].IsStillUsableBy(this.pawn))
             {
                 Pawn_MeleeVerbs.meleeVerbs.Add(new VerbEntry(allVerbs[i], this.pawn));
             }
         }
         if (this.pawn.equipment != null)
         {
             List <ThingWithComps> allEquipmentListForReading = this.pawn.equipment.AllEquipmentListForReading;
             for (int j = 0; j < allEquipmentListForReading.Count; j++)
             {
                 ThingWithComps thingWithComps = allEquipmentListForReading[j];
                 CompEquippable comp           = thingWithComps.GetComp <CompEquippable>();
                 if (comp != null)
                 {
                     List <Verb> allVerbs2 = comp.AllVerbs;
                     if (allVerbs2 != null)
                     {
                         for (int k = 0; k < allVerbs2.Count; k++)
                         {
                             if (allVerbs2[k].IsStillUsableBy(this.pawn))
                             {
                                 Pawn_MeleeVerbs.meleeVerbs.Add(new VerbEntry(allVerbs2[k], this.pawn));
                             }
                         }
                     }
                 }
             }
         }
         if (this.pawn.apparel != null)
         {
             List <Apparel> wornApparel = this.pawn.apparel.WornApparel;
             for (int l = 0; l < wornApparel.Count; l++)
             {
                 Apparel        apparel = wornApparel[l];
                 CompEquippable comp2   = apparel.GetComp <CompEquippable>();
                 if (comp2 != null)
                 {
                     List <Verb> allVerbs3 = comp2.AllVerbs;
                     if (allVerbs3 != null)
                     {
                         for (int m = 0; m < allVerbs3.Count; m++)
                         {
                             if (allVerbs3[m].IsStillUsableBy(this.pawn))
                             {
                                 Pawn_MeleeVerbs.meleeVerbs.Add(new VerbEntry(allVerbs3[m], this.pawn));
                             }
                         }
                     }
                 }
             }
         }
         foreach (Verb verb in this.pawn.health.hediffSet.GetHediffsVerbs())
         {
             if (verb.IsStillUsableBy(this.pawn))
             {
                 Pawn_MeleeVerbs.meleeVerbs.Add(new VerbEntry(verb, this.pawn));
             }
         }
     }
     else if (this.pawn.Spawned)
     {
         TerrainDef terrain = this.pawn.Position.GetTerrain(this.pawn.Map);
         if (this.terrainVerbs == null || this.terrainVerbs.def != terrain)
         {
             this.terrainVerbs = Pawn_MeleeVerbs_TerrainSource.Create(this, terrain);
         }
         List <Verb> allVerbs4 = this.terrainVerbs.tracker.AllVerbs;
         for (int n = 0; n < allVerbs4.Count; n++)
         {
             Verb verb2 = allVerbs4[n];
             if (verb2.IsStillUsableBy(this.pawn))
             {
                 Pawn_MeleeVerbs.meleeVerbs.Add(new VerbEntry(verb2, this.pawn));
             }
         }
     }
     return(Pawn_MeleeVerbs.meleeVerbs);
 }
Ejemplo n.º 59
0
        private bool FindGrammar(InputResult result, Verb verb, IEnumerable<string> grammars)
        {
            foreach (var possibleGrammar in grammars)
            {
                var matchedGrammar = verb.Grammars.FirstOrDefault(x => x.Format == possibleGrammar);

                if (matchedGrammar != null)
                {
                    result.Grammar = matchedGrammar;
                    return true;
                }
            }

            return false;
        }
Ejemplo n.º 60
0
 private void WriteVerb(Verb verb) => _socketStream.WriteByte((byte)verb);