Esempio n. 1
0
 private void PursuitDetectableIfCharacter(IDetectable detectable)
 {
     if (detectable is MainCharacter)
     {
         stateMachine.CurrentState = new StateChase();
     }
 }
Esempio n. 2
0
    public void GeneralScan(DetectableTags detectableTags = 0)
    {
        // get all colliders within the vision radius
        int foundCollidersCount = Physics2D.OverlapCircleNonAlloc(_unit.MoveController.Body.position, _visionRange, _foundColliders, _targetLayers);

        for (int i = 0; i < foundCollidersCount; i++)
        {
            Collider2D  collider   = _foundColliders[i];
            IDetectable detectable = collider.GetComponent <IDetectable>();
            // ensure that this collider is a detectable
            if (detectable == null)
            {
                continue;
            }
            // ensure that this detectable matches at least one of the tags and can be seen
            bool containsDetectableTag = (detectable.DetectableTags & detectableTags) != 0;
            if (containsDetectableTag && Scan(detectable, _unit.MoveController.Body.transform, _visionRange, _visionLayers, _visionAngle))
            {
                // add/update the detected target entry
                if (!_detectedTargets.TryGetValue(detectable, out DetectedTarget entry))
                {
                    _detectedTargets.Add(detectable, new DetectedTarget()
                    {
                        Target         = detectable,
                        DetectionValue = 0f,
                    });
                }
                _detectedTargets[detectable].DetectedThisFrame = true;
            }
        }
        ProcessDetectedTargets();
    }
Esempio n. 3
0
        /// <summary>
        /// Checks if given detectable is in Field of View of the observer, takes angle and line of sight into account
        /// </summary>
        /// <param name="detectable"></param>
        /// <returns></returns>
        private bool CheckIfDetectableIsInFOV(IDetectable detectable)
        {
            // Positions
            Vector2 pos = transform.position;
            Vector2 detectableCentre = detectable.Position;

            // Vectors
            Vector2 difference = detectableCentre - pos;
            Vector2 direction  = difference.normalized;

            // Checks if centre of detectable is in view
            if (PointInView(pos, direction, difference.sqrMagnitude))
            {
                return(true);
            }

            // Chekcs if any point on the detectable's edge is view
            foreach (var p in detectable.GetEdgePoints(-direction))
            {
                Vector2 vectorToPoint = (p - pos);
                if (PointInView(pos, vectorToPoint.normalized, vectorToPoint.sqrMagnitude))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 4
0
        /// <summary>
        /// Adds an <see cref="IDetectable"/> and its associated normalized points.
        /// </summary>
        /// <param name="detectable">Detectable object</param>
        /// <param name="normPoints">Normalized points list</param>
        public void Add(IDetectable detectable, IList <Vector3> normPoints)
        {
            Item item = m_ItemPool.Count > 0 ? m_ItemPool.Pop() : new Item();

            item.Detectable = detectable;
            item.NormPoints.AddRange(normPoints);
            m_ItemsByTag[detectable.Tag].Add(item);
            m_Detectables.Add(detectable);
        }
Esempio n. 5
0
 public void Connect(IDetectable device)
 {
     for (int i = 0; i < devices.Length; i++)
     {
         if (devices[i] == null)
         {
             devices[i] = device;
             return;
         }
     }
 }
Esempio n. 6
0
        public ParallelSearchEngine(params ParametersPair[] arguments)
            : base(arguments.Select(item =>
        {
            IDetectable detectable = Context.Get <IDetectableManager>().CreateDetectableInstance <ISearchEngine>(item.TypeName);

            return(Context.Get <IDetectableManager>().CreateImplementationInstance <ISearchEngine>(detectable,
                                                                                                   item.Parameters.Cast <ParametersPair>().ToList(),

                                                                                                   detectable.InterfaceSettings));
        }).ToArray())
        {
        }
Esempio n. 7
0
    void SetDetectionType()
    {
        switch (dType)
        {
        case DetectionType.FaceThePlayer:
            player = transform.parent.GetComponent <FacePlayer>();
            break;

        case DetectionType.Interactable:
            player = transform.parent.GetComponent <InteractWithPlayer>();
            break;
        }
    }
        private void Add_Click(object sender, RoutedEventArgs e)
        {
            IDetectable defaultDetectable = Context.Get <IDetectableManager>()
                                            .Find <ISearchEngine>(Data.First().ProxyType)
                                            .First();

            Arguments.Add(new ParametersPair
            {
                TypeName   = defaultDetectable.GetType().AssemblyQualifiedName,
                Parameters = ParallelSearchEngineDetectableBase.GetSettingsList(Data.First().ProxyType).Cast <object>().ToList()
            });

            UpdateData();
        }
Esempio n. 9
0
 public T CreateImplementationInstance <T>(IDetectable detectable, List <ParametersPair> parametersList, List <object> interfacesList)
 {
     try
     {
         return(CreateImplementationInstanceInternal <T>(detectable, parametersList, interfacesList));
     }
     catch (TargetInvocationException exception)
     {
         throw exception.InnerException;
     }
     catch (MissingMethodException)
     {
         throw new ConfigurationErrorsException(Resources.OldConfigurationException);
     }
 }
Esempio n. 10
0
        /// <summary>
        /// Returns the <see cref="ObservableType"/>.
        /// Out value depends on <see cref="ObservableType"/>:
        /// - User: evaluates the specified <see cref="IDetectable"/>'s Observables[Index].
        /// - Distance: output = 0, encoder handles distance values.
        /// - One-Hot: output = 1.
        /// </summary>
        /// <param name="detectable"><see cref="IDetectable"/> to evaluate</param>
        /// <param name="value">Observed value (output)</param>
        /// <returns><see cref="ObservableType"/></returns>
        public ObservableType Evaluate(IDetectable detectable, out float value)
        {
            value = Type switch
            {
                // NOTE We always refer to the detectable's original observable
                // instance when invoking the getter method, using the observable's
                // index. This is why a copy of that observable doesn't contain a
                // getter itself. Copies are only used for organizing observables
                // for the encoding settings.
                ObservableType.User
                => detectable.Observables.GetObservable(Index).Value(),
                ObservableType.OneHot
                => 1,
                _ => 0
            };

            return(Type);
        }
Esempio n. 11
0
        public Application Create(TaskItem task, ProxySearchFeedback feedback)
        {
            Context.Set(new CancellationTokenSource());
            Context.Set <IHttpDownloaderContainer>(HttpDownloaderContainer);

            task.UpdateDetails(Resources.ReadingConfigurationOfSelectedSearch);

            IDetectable   searchEngineDetectable = DetectableManager.CreateDetectableInstance <ISearchEngine>(Settings.SelectedTabSettings.SearchEngineDetectableType);
            IDetectable   proxyCheckerDetectable = DetectableManager.CreateDetectableInstance <IProxyChecker>(Settings.SelectedTabSettings.ProxyCheckerDetectableType);
            IDetectable   geoIPDetectable        = DetectableManager.CreateDetectableInstance <IGeoIP>(Settings.GeoIPDetectableType);
            ISearchEngine searchEngine           = DetectableManager.CreateImplementationInstance <ISearchEngine>(searchEngineDetectable,
                                                                                                                  Settings.SelectedTabSettings.SearchEngineSettings,
                                                                                                                  searchEngineDetectable.InterfaceSettings);

            feedback.ExportAllowed = !(searchEngine is FolderSearchEngine);

            task.UpdateDetails(Resources.PreparingProxyProvider);

            IProxyProvider proxyProvider = new ProxyProvider(Context.Get <IBlackList>(), new ParseMethodsProvider(Settings.ParseDetails));

            task.UpdateDetails(Resources.PreparingProxyChecker);

            IProxyChecker proxyChecker = DetectableManager.CreateImplementationInstance <IProxyChecker>(proxyCheckerDetectable,
                                                                                                        Settings.SelectedTabSettings.ProxyCheckerSettings,
                                                                                                        proxyCheckerDetectable.InterfaceSettings);

            task.UpdateDetails(Resources.PreparingGeoIpService);

            IGeoIP geoIP = DetectableManager.CreateImplementationInstance <IGeoIP>(geoIPDetectable,
                                                                                   Settings.GeoIPSettings,
                                                                                   geoIPDetectable.InterfaceSettings);

            task.UpdateDetails(Resources.PreparingApplication);

            Application application = new Application(searchEngine, proxyChecker, HttpDownloaderContainer, geoIP, Context.Get <IRatingManager>(), proxyProvider, Context.Get <ITaskManager>());

            application.ProxyAlive += feedback.OnAliveProxy;
            application.OnError    += Context.Get <IErrorFeedback>().SetException;

            return(application);
        }
Esempio n. 12
0
        private static T CreateImplementationInstanceInternal <T>(IDetectable detectable, List <ParametersPair> parametersList, List <object> interfacesList)
        {
            Type           type          = detectable.Implementation;
            ParametersPair parameterPair = parametersList.SingleOrDefault(item => item.TypeName == detectable.GetType().AssemblyQualifiedName);

            if (parameterPair == null && !interfacesList.Any())
            {
                return((T)Activator.CreateInstance(type));
            }
            else
            {
                List <object> parameters = new List <object>();
                if (parameterPair != null)
                {
                    parameters.AddRange(parameterPair.Parameters);
                }

                parameters.AddRange(interfacesList);

                return((T)Activator.CreateInstance(type, parameters.ToArray()));
            }
        }
Esempio n. 13
0
    private static bool ScanCast(IDetectable detectable, Transform unitTransform, float visionRange, LayerMask visionLayers)
    {
        bool    found         = false;
        Vector2 unitPosition  = unitTransform.position;
        Vector2 otherPosition = detectable.Transform.position;
        float   distance      = Vector2.Distance(unitPosition, otherPosition);
        Vector2 direction     = otherPosition - unitPosition;

        RaycastHit2D[]  hit    = new RaycastHit2D[1];
        ContactFilter2D filter = new ContactFilter2D();

        filter.SetLayerMask(visionLayers);
        if (Physics2D.Raycast(unitPosition, direction.normalized, filter, hit, distance) > 0)
        {
            // if this is the hostile, set found to true
            if (hit[0].transform == detectable.Transform)
            {
                found = true;
            }
        }
        return(found);
    }
Esempio n. 14
0
    private static bool Scan(IDetectable detectable, Transform unitTransform, float visionRange, LayerMask visionLayers, float visionAngle = 360f)
    {
        bool    found         = false;
        Vector2 unitPosition  = unitTransform.position;
        Vector2 otherPosition = detectable.Transform.position;
        // ensure the target distance is within range
        float distance = Vector2.Distance(unitPosition, otherPosition);

        if (distance > visionRange)
        {
            return(found);
        }
        // ensure the target's direction is within the view cone
        Vector2 direction = otherPosition - unitPosition;
        float   angle     = Vector2.Angle(unitTransform.up, direction);

        if (angle > visionAngle)
        {
            return(found);
        }
        found = ScanCast(detectable, unitTransform, visionRange, visionLayers);
        return(found);
    }
Esempio n. 15
0
 /// <summary>
 /// Reply to a stimulus (type-dependent), supplying up to 4 objects as data.
 /// Can be used for transactions (e.g. I'd like to eat this much of your energy, how much did I actually get?)
 /// </summary>
 /// <param name="from"></param>
 /// <param name="param0"></param>
 /// <param name="param1"></param>
 /// <param name="param2"></param>
 /// <param name="param3"></param>
 public void Reply(IDetectable from, Object param0, Object param1, Object param2, Object param3)
 {
     IDetectable to = from;
     IsReply = true;
     From = from;
     Param0 = param0;
     Param1 = param1;
     Param2 = param2;
     Param3 = param3;
     to.ReceiveStimulus(this);
 }
 protected void Start()
 {
     detectable = transform.parent.GetComponent<MonoBehaviour>() as IDetectable;
 }
Esempio n. 17
0
        public override void Execute(StateManager states, SessionManager sm, Turn t)
        {
            bool mouseClick = Input.GetMouseButtonDown(0);

            if (prevCharacter != null)
            {
                prevCharacter.OnDeHighlight(states.playerHolder);
            }

            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, MAX_DISTANCE))
            {
                Node        node       = sm.gridManager.GetNode(hit.point);
                IDetectable detectable = hit.transform.GetComponent <IDetectable>();
                if (detectable != null)
                {
                    node = detectable.OnDetect();
                }

                if (node != null)
                {
                    if (node.character != null)
                    {
                        //you highlighted your own unit
                        if (node.character.owner == states.playerHolder)
                        {
                            node.character.OnHighlight(states.playerHolder);
                            prevCharacter = node.character;
                            sm.ClearPath(states);
                            sm.gameVariables.UpdateActionPoints(node.character.actionPoints);
                        }
                        else //you highlighted an enemy unit
                        {
                        }
                    }

                    if (states.CurrentCharacter != null && node.character == null)
                    {
                        if (mouseClick)
                        {
                            if (states.CurrentCharacter.currentPath != null || states.CurrentCharacter.currentPath.Count > 0)
                            {
                                states.SetState("moveOnPath");
                            }
                        }
                        else
                        {
                            PathDetection(states, sm, node);
                        }
                    }
                    else //No character selected
                    {
                        if (mouseClick)
                        {
                            if (node.character != null)
                            {
                                if (node.character.owner == states.playerHolder)
                                {
                                    node.character.OnSelect(states.playerHolder);
                                    states.prevNode = null;
                                    sm.ClearPath(states);

                                    sm.gameVariables.UpdateActionPoints(node.character.actionPoints);
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 18
0
        /// <summary> We've been sent a Stimulus that our basic Cell object doesn't understand.
        /// This overload responds to the "bioluminescence" stimulus
        /// Parameter 0 will be a ColorValue containing the bioluminescent cell's current anim colour
        /// <param name="stimulus">The stimulus information</param>
        /// <returns>Return true if the stimulus was handled</returns>
        public override bool ReceiveStimulus(Stimulus stim)
        {
            float direction = 0.5f;
            float intensity = 0f;

            if (stim.Type == "bioluminescence")
            {
                // Find out if the sender is within range of our hotspots
                SensorItem cone0 = owner.TestStimulusVisibility(0, range, stim);
                float dist = cone0.Distance();                                                      // dist will be roughly the same from both hotspots
                if (dist < range)                                                                   // if object is within range...
                {
                    // Find out how visible it is from each hotspot
                    SensorItem cone1 = owner.TestStimulusVisibility(1, range, stim);                // now we know we're in range, get the other hotspot's visibility
                    float angle0 = cone0.Angle();                                                   // Get angle from each hotspot
                    float angle1 = cone1.Angle();
                    if ((angle0 < halfAngle)||(angle1 < halfAngle))                                 // if within sight of at least one hotspot...
                    {
                        // Compare the light to our filter colour
                        ColorValue light = (ColorValue)stim.Param0;                                 // Stimulus param 0 will be the bioluminescent cell's current anim colour
                        float r1 = light.Red - r;                                                   // difference in RGB between filter and cell
                        float g1 = light.Green - g;
                        float b1 = light.Blue - b;
                        float match = 1f - (float)Math.Sqrt((r1 * r1 + g1 * g1 + b1 * b1) / 3f);   // least squares measure of similarity (1=identical)

                        // calc intensity and direction, if we match spectrally
                        if (match > 0.8f)                                                           // <=1/2 is a bad match, e.g. rgB doesn't match rGb but they're still a third similar!
                        {                                                                           // only give a direction response to a good match
                            // Scale signal according to distance downrange
                            intensity = cone0.Distance(range);

                            // compute direction
                            float a0 = 1f - angle0 / halfAngle;
                            float a1 = 1f - angle1 / halfAngle;
                            direction = (a1 - a0) / 2f + 0.5f;
                            if (focusDirection < 0f) focusDirection = 0f;
                            else if (focusDirection > 1f) focusDirection = 1f;
                        }

                        // If this stimulus comes from a different source to our present focus of attention
                        // ignore it unless it is stronger (in which case, shift attention to it)
                        if ((stim.From != focusObject)                                              // Is this object different from our present focus of attention
                            && (intensity < focusIntensity))                                        // and weaker?
                            return true;                                                            // ignore it

                        focusObject = stim.From;                                                    // Shift attention if necessary (if found stronger source)
                        focusIntensity = intensity;                                                 // record the new signal strength
                        focusDirection = direction;
                        lossOfSignal = LOSSOFSIGNALAFTER;                                           // and reset the loss-of-signal timers
                        fading = false;

                        // Calculate the signal entering each sensor
                        if (angle0 < halfAngle)                                                     // if the source is visible from sensor0
                            signal0 = intensity * (1f - angle0 / halfAngle);                        // scale signal by deviation from sensor's midline
                        if (angle1 < halfAngle)                                                     // otherwise leave as zero
                            signal1 = intensity * (1f - angle1 / halfAngle);                        // Repeat for sensor1

                        SetOutputs();                                                               // Write the two cell outputs

                        }
                }
                return true;
            }
            return false;
        }
Esempio n. 19
0
 public void OnPlayerVisible(IDetectable obj)
 {
     playerInSight = true;
     // Set the last global sighting is the players current position.
     lastPlayerSighting.position = player.transform.position;
 }
Esempio n. 20
0
        public Vector3 RelativePosition; // The position of the object relative to the hotspot's coordinate frame

        #endregion Fields

        #region Constructors

        public SensorItem(IDetectable obj, Vector3 relpos)
        {
            Object = obj;
            RelativePosition = relpos;
        }
Esempio n. 21
0
 private void OnDetectedObject(IDetectable detectable)
 {
 }
Esempio n. 22
0
 public void Connect(IDetectable device)
 {
     devices.Add(device);
 }
Esempio n. 23
0
 private void Start()
 {
     detectableObj = GetComponent <IDetectable>();
 }
Esempio n. 24
0
 public CircleCastHit CastTo(IDetectable obj)
 {
     return(obj.CircleCastHandle(this));
 }
Esempio n. 25
0
 public bool Unregister(IDetectable detectable, out IDetectable removedDetectable)
 {
     throwIfDetectionDeatilsInvalid(detectable);
     return registeredDetectables.TryRemove(detectable.Identification, out removedDetectable);
 }
Esempio n. 26
0
 public IDetectable Register(IDetectable detectable)
 {
     throwIfDetectionDeatilsInvalid(detectable);
     return registeredDetectables.AddOrUpdate(detectable.Identification, detectable, (k, v) => detectable);
 }
Esempio n. 27
0
 private static void throwIfDetectionDeatilsInvalid(IDetectable detectable)
 {
     if (detectable == null) throw new ArgumentNullException("deviceDetails");
     if (String.IsNullOrWhiteSpace(detectable.Identification)) throw new ArgumentNullException("DeviceId");
 }
Esempio n. 28
0
 /// <summary>
 /// Construct a stimulus for emission
 /// </summary>
 /// <param name="from">IDetectable object (e.g. Cell) emitting stimulus</param>
 /// <param name="loc">Location of the emitter (Cell or its effector hotspot)</param>
 /// <param name="range">Radius over which the stimulus can be sensed</param>
 /// <param name="type">String describing type of stimulus</param>
 /// <param name="param0">Type-dependent parameter</param>
 /// <param name="param1">Type-dependent parameter</param>
 /// <param name="param2">Type-dependent parameter</param>
 /// <param name="param3">Type-dependent parameter</param>
 public Stimulus(IDetectable from, Vector3 loc, float range, 
     string type, Object param0, Object param1, Object param2, Object param3)
 {
     From = from;
     TransmitterLocn = loc;
     TransmissionRange = range;
     Type = type;
     Param0 = param0;
     Param1 = param1;
     Param2 = param2;
     Param3 = param3;
 }
Esempio n. 29
0
        private bool CanSee(IDetectable detectable)
        {
            if (detectable == null)
            {
                throw new ArgumentNullException("character");
            }

            RaycastHit hit;
            float      angle = Vector3.Angle(detectable.gameObject.transform.position - transform.position, transform.forward);

            if (angle > _fieldOfView * 0.5f)
            {
                return(false);
            }

            bool  isVisible        = false;
            float distance         = Vector3.Distance(detectable.gameObject.transform.position, transform.position);
            float visibilityRating = detectable.Visibility * _visibilityCurve.Evaluate(distance);

            if (visibilityRating >= _minVisibilityForDetection)
            {
                foreach (var tag in _invisibleTags)
                {
                    if (detectable.gameObject.CompareTag(tag))
                    {
                        return(false);
                    }
                }

                isVisible = true;
            }

            if (isVisible)
            {
                Vector3 targetPosition = detectable.gameObject.GetComponent <Collider>().bounds.center;
                Physics.Raycast(new Ray(transform.position, targetPosition - transform.position), out hit, _sensoryRange, _detectionMask.value);

                if (hit.collider == null || hit.collider.GetComponent <IDetectable>() != detectable)
                {
#if UNITY_EDITOR
                    if (_verbose)
                    {
                        Debug.Log(GetHashCode() + "'s line of sight to " + detectable.gameObject.name + " is blocked by " + hit.collider.name);
                    }
#endif

                    isVisible = false;
                }

                if (hit.collider != null)
                {
#if UNITY_EDITOR
                    if (_verbose)
                    {
                        Debug.DrawRay(transform.position, hit.collider.transform.position - transform.position);
                    }
#endif
                }
            }

#if UNITY_EDITOR
            if (_verbose)
            {
                Debug.Log(GetHashCode() + " - " + detectable.Visibility + " / " + visibilityRating + " : " + isVisible);
            }
#endif

            return(isVisible);
        }
Esempio n. 30
0
        public List <IDetectable> Find <T>(IDetectable proxyTypeDetectable, params Type[] ignoredTypes)
        {
            IProxyType proxyTypeInstance = (IProxyType)Activator.CreateInstance(proxyTypeDetectable.Implementation);

            return(Find <T>(proxyTypeInstance.Type, ignoredTypes));
        }
Esempio n. 31
0
 /// <summary>
 /// If the hotspots have contacted a critter, store a ref to it, note its relative position and return true
 /// </summary>
 /// <returns></returns>
 private bool Caught()
 {
     SensorItem[] nearHot0 = owner.GetObjectsInRange(0, CONTACTDIST, true, false, false);                    // if hotspot0 is near a creature
     if (nearHot0.Length > 0)
     {
         SensorItem[] nearHot1 = owner.GetObjectsInRange(0, CONTACTDIST, true, false, false);                // and hotspot1 is also near it
         for (int i = 0; i < nearHot0.Length; i++)
         {
             for (int j = 0; j < nearHot1.Length; j++)
             {
                 if (nearHot0[i].Object == nearHot1[j].Object)
                 {
                     prey = nearHot0[i].Object;                                                              // grab it
                     return true;
                 }
             }
         }
     }
     prey = null;
     return false;
 }
Esempio n. 32
0
 /// <summary>
 /// Whether the <see cref="DetectionResult"/> contains
 /// a specific <see cref="IDetectable"/> object.
 /// </summary>
 /// <param name="detectable">Detectable object</param>
 /// <returns>True if <see cref="IDetectable"/> was found</returns>
 public bool Contains(IDetectable detectable)
 {
     return(m_Detectables.Contains(detectable));
 }
Esempio n. 33
0
 public void ScanForCurrentTarget(IDetectable detectable)
 {
     ProcessDetectedTargetEntry(CurrentDetectable);
 }
Esempio n. 34
0
 public void OnPlayerInvisible(IDetectable obj)
 {
     playerInSight = false;
 }
Esempio n. 35
0
 public void Connect(IDetectable app)
 {
     devices.Add(app);
 }
Esempio n. 36
0
 private void Awake()
 {
     DetectableBehaviour = new CloneDetected(gameObject);
     _mMoveForce         = 10;
 }