/// <summary>
        /// 部屋に入ったとき
        /// </summary>
        void EnterRoom()
        {
            Debug.Log("enter room");

            if (!_player)
            {
                _player = FindObjectOfType <PlayerCore>();
            }

            _currentRoomView = _player.transform.GetComponentInParent <RoomView>();
            _playerPosition  = _currentRoomView.Room.Coordinate;

            //プレイヤーのいた部屋を移動
            if (_prevStayRoom.X != -1)
            {
                _mapData[_prevStayRoom.Y * 2, _prevStayRoom.X * 2] &= ~(int)MinimapObject.Players;
            }

            _mapData[_playerPosition.Y * 2, _playerPosition.X * 2] |= (int)MinimapObject.Floor;
            _mapData[_playerPosition.Y * 2, _playerPosition.X * 2] |= (int)MinimapObject.Players;

            _prevStayRoom = _playerPosition;

            OnMapChanged?.Invoke(_mapData);
        }
Exemple #2
0
        private void SetMap(Map newMap)
        {
            Player.SetMap(newMap);

            _currentMap = newMap;
            OnMapChanged?.Invoke(newMap);
        }
Exemple #3
0
 public void Restart()
 {
     if (saveController != null)
     {
         saveController.DeleteSave(CurrentLevel.ID);
     }
     GenUtil.Replay(CurrentLevel, map, leftReserve, upReserve);
     movesCount = 0;
     OnMove?.Invoke(0);
     OnMapChanged?.Invoke(0, targetCellsCount);
     victory = false;
 }
Exemple #4
0
        public void KeyPressedHandler(object sender, KeyPressedEventArgs e)
        {
            HidePath();
            var newPosition = cursorPosition;

            if (e.KeyInfo.Key == ConsoleKey.LeftArrow && cursorPosition.X > 0)
            {
                newPosition.X--;
            }

            if (e.KeyInfo.Key == ConsoleKey.RightArrow && cursorPosition.X < mapSize.Width - 1)
            {
                newPosition.X++;
            }

            if (e.KeyInfo.Key == ConsoleKey.UpArrow && cursorPosition.Y > 0)
            {
                newPosition.Y--;
            }

            if (e.KeyInfo.Key == ConsoleKey.DownArrow && cursorPosition.Y < mapSize.Height - 1)
            {
                newPosition.Y++;
            }

            if (cursorPosition != newPosition)
            {
                OnCursorChanged?.Invoke(this, new PropertyChangedEventArgs <Point>(cursorPosition, newPosition));
                cursorPosition = newPosition;
                canvas1.InvalidateVisual();
            }

            if (e.KeyInfo.Key == ConsoleKey.Spacebar)
            {
                if (MazeMap[cursorPosition.Y, cursorPosition.X] != (int)CurrentMapItem)
                {
                    OnMapChanged?.Invoke(this, new MazeMapItemEventArgs(cursorPosition, CurrentMapItem));
                    MazeMap[cursorPosition.Y, cursorPosition.X] = (int)CurrentMapItem;
                    canvas1.InvalidateVisual();
                }
            }

            if (e.KeyInfo.Key == ConsoleKey.Delete)
            {
                if (MazeMap[cursorPosition.Y, cursorPosition.X] != (int)MapItem.Empty)
                {
                    OnMapChanged?.Invoke(this, new MazeMapItemEventArgs(cursorPosition, CurrentMapItem));
                    MazeMap[cursorPosition.Y, cursorPosition.X] = (int)MapItem.Empty;
                    canvas1.InvalidateVisual();
                }
            }
        }
Exemple #5
0
    public static void AddLane(Curve3DSampler l,
                               out List <Lane> added, out List <Lane> deleted)
    {
        // Variable has not been actually calculated until "ToList()" is called
        var lane_intersections = from lane in allLanes
                                 let intersections = lane.IntersectWith(l)
                                                     where intersections.Count > 0
                                                     select(lane, intersections);

        if (lane_intersections.ToList().Count > 0)
        {
            Debug.Log("From " + allLanes.Count + " found # intersections: " + lane_intersections.ToList()[0].intersections.Count);
        }

        added   = new List <Lane>();
        deleted = new List <Lane>();
        List <float> l_intersect_params = new List <float>();

        // replacements
        foreach (var lane_intersection in lane_intersections.ToList())
        {
            Lane           old_lane;
            List <Vector3> intersection;
            (old_lane, intersection) = lane_intersection;
            List <float>          intersection_params = intersection.ConvertAll(input => old_lane.xz_curve.ParamOf(Algebra.toVector2(input)).Value);
            List <Curve3DSampler> splitted            = old_lane.MultiCut(intersection_params, old_lane.xz_curve.Length);
            //remove old lanes & destroy objects.
            old_lane.SetGameobjVisible(false);
            allLanes.Remove(old_lane);
            deleted.Add(old_lane);

            //create replacements
            var replaced_lanes = splitted.ConvertAll(sampler => new Lane(sampler));
            added.AddRange(replaced_lanes);

            //store intersection points on l
            intersection.ForEach(input =>
                                 l_intersect_params.Add(l.xz_curve.ParamOf(Algebra.toVector2(input)).Value));
        }

        // create new lane
        List <Curve3DSampler> l_splitted = l.MultiCut(l_intersect_params, l.xz_curve.Length);
        var new_lanes = l_splitted.ConvertAll(sampler => new Lane(sampler));

        added.AddRange(new_lanes);
        Debug.Log(new_lanes.Count + "newly added");

        // Update record
        allLanes.AddRange(added);

        OnMapChanged?.Invoke(null, allLanes);
    }
Exemple #6
0
    void onStoneOnCell(Cell c)
    {
        IEnumerable <IStoneTargetCell> res2 = map.OfType <IStoneTargetCell>().Where(x => x.IsFilled);

        IStoneTargetCell[] res21 = res2.ToArray();
        currentCellsCount = res21.Length;

        if (currentCellsCount == targetCellsCount)
        {
            Victory();
        }

        OnMapChanged?.Invoke(currentCellsCount, targetCellsCount);
    }
 private void WebSocket_OnMessage(object sender, MessageEventArgs e)
 {
     byte[] data = e.RawData;
     if (!e.IsBinary || data.Length == 0)
     {
         return;
     }
     if (data[0] == (byte)Opcode.PixelUpdate)
     {
         logger.LogDebug($"WebSocket_OnMessage(): got pixel update {DataToString(data)}");
         MapChangedEventArgs args = new MapChangedEventArgs
         {
             DateTime = DateTime.Now,
             Chunk    = (data[1], data[2]),
             Changes  = new List <MapChange>()
         };
         for (int i = 3; i < data.Length; i += 4)
         {
             byte[] offsetBytes = new byte[] { data[i + 2], data[i + 1], data[i], 0 };
             args.Changes.Add(new MapChange
             {
                 Color  = data[i + 3],
                 Offset = BitConverter.ToUInt32(offsetBytes, 0)
             });
         }
         OnMapChanged?.Invoke(this, args);
     }
     else if (data[0] == (byte)Opcode.PixelReturn)
     {
         byte returnCode = data[1];
         Array.Reverse(data, 2, 6);
         PixelReturnData received = new PixelReturnData
         {
             ReturnCode      = (ReturnCode)returnCode,
             Wait            = BitConverter.ToUInt32(data, 4),
             CoolDownSeconds = BitConverter.ToInt16(data, 2)
         };
         pixelReturnData.Enqueue(received);
         pixelReturnResetEvent.Set();
     }
     else if (!listeningMode && data[0] == (byte)Opcode.Cooldown)
     {
         Array.Reverse(data, 1, 4);
         uint cooldown = BitConverter.ToUInt32(data, 1);
         if (cooldown > 0U)
         {
             logger.LogInfo($"Current cooldown is {TimeSpan.FromMilliseconds(cooldown):mm\\:ss\\.f}");
         }
     }
 }
Exemple #8
0
    public int GetTargetCellsCount()
    {
        int c = 0;

        IEnumerable <IStoneTargetCell> res = map.OfType <IStoneTargetCell>();

        IStoneTargetCell[] res1 = res.ToArray();
        c = res1.Length;
        targetCellsCount = c;

        IEnumerable <IStoneTargetCell> res2 = res.Where(x => x.IsFilled);

        IStoneTargetCell[] res21 = res2.ToArray();

        currentCellsCount = res21.Length;
        OnMapChanged?.Invoke(res21.Length, c);

        return(c);
    }
        /// <summary>
        /// 部屋をクリアしたとき
        /// </summary>
        void ClearRoom()
        {
            var aisles = _currentRoomView.Room.ConnectingAisles;

            var mapPosition = new Point(_playerPosition.X * 2, _playerPosition.Y * 2);

            //廊下を出す
            foreach (var item in aisles)
            {
                switch (item.Key)
                {
                case AdjacentSides.North:
                    _mapData[mapPosition.Y - 1, mapPosition.X] |= (int)MinimapObject.Floor;
                    break;

                case AdjacentSides.East:
                    _mapData[mapPosition.Y, mapPosition.X + 1] |= (int)MinimapObject.Floor;
                    break;

                case AdjacentSides.South:
                    _mapData[mapPosition.Y + 1, mapPosition.X] |= (int)MinimapObject.Floor;
                    break;

                case AdjacentSides.West:
                    _mapData[mapPosition.Y, mapPosition.X - 1] |= (int)MinimapObject.Floor;
                    break;
                }
            }

            //階段があれば出す
            if (_currentRoomView.Room.RoomAttribute == Room.RoomAttributes.Stair)
            {
                _mapData[mapPosition.Y, mapPosition.X] |= (int)MinimapObject.Stair;
            }

            OnMapChanged?.Invoke(_mapData);
        }
        // Start is called before the first frame update
        void Start()
        {
            var settings = Resources.Load <MazeFloorSettings>(MazeFloorSettingsPath);

            //0と偶数に部屋データ、それ以外に通路データを入れる
            _mapData = new int[settings.Height * 2 - 1, settings.Width * 2 - 1];

            //フロア破壊時マップを初期化
            _messageReceiver.Receive <Katano.MazeSignal.FloorDestruct>()
            .Subscribe((_) => Initialize())
            .AddTo(this);

            //フロアに入ったとき
            _messageReceiver.Receive <Katano.MazeSignal.FloorStarted>()
            .Subscribe((_) => {
                EnterRoom();
                ClearRoom();
            })
            .AddTo(this);

            //部屋に入ったとき
            _messageReceiver.Receive <RoomSignal.RoomStarted>()
            .Subscribe((_) => EnterRoom())
            .AddTo(this);

            //部屋をクリアしたとき
            _messageReceiver.Receive <RoomSignal.RoomCleared>()
            .Subscribe((_) => ClearRoom())
            .AddTo(this);

            Initialize();
            OnStarted?.Invoke();
            OnMapChanged?.Invoke(_mapData);

            Debug.Log("started system");
        }
        public override IEnumerator Localize()
        {
            ARCameraImageBytes image = null;
            bool isHD = HWARHelper.TryGetCameraImageBytes(out image);

            if (image != null && image.IsAvailable)
            {
                stats.localizationAttemptCount++;
                Vector3    camPos = m_Cam.transform.position;
                Quaternion camRot = m_Cam.transform.rotation;
                byte[]     pixels;
                Vector4    intrinsics = isHD ? HWARHelper.GetIntrinsics() : HWARHelper.GetIntrinsics(image.Width, image.Height);
                HWARHelper.GetPlaneData(out pixels, image);

                image.Dispose();

                Vector3    pos = Vector3.zero;
                Quaternion rot = Quaternion.identity;

                float startTime = Time.realtimeSinceStartup;

                Task <int> t = Task.Run(() =>
                {
                    return(Immersal.Core.LocalizeImage(out pos, out rot, image.Width, image.Height, ref intrinsics, pixels));
                });

                while (!t.IsCompleted)
                {
                    yield return(null);
                }

                int mapId = t.Result;

                if (mapId > 0 && ARSpace.mapIdToOffset.ContainsKey(mapId))
                {
                    if (mapId != lastLocalizedMapId)
                    {
                        if (m_ResetOnMapChange)
                        {
                            foreach (KeyValuePair <Transform, SpaceContainer> item in ARSpace.transformToSpace)
                            {
                                item.Value.filter.ResetFiltering();
                            }
                        }

                        lastLocalizedMapId = mapId;

                        OnMapChanged?.Invoke(mapId);
                    }

                    HWARHelper.GetRotation(ref rot);
                    MapOffset mo          = ARSpace.mapIdToOffset[mapId];
                    float     elapsedTime = Time.realtimeSinceStartup - startTime;
                    Debug.Log(string.Format("Relocalised in {0} seconds", elapsedTime));
                    stats.localizationSuccessCount++;

                    Matrix4x4 offsetNoScale = Matrix4x4.TRS(mo.position, mo.rotation, Vector3.one);
                    Vector3   scaledPos     = new Vector3
                                              (
                        pos.x * mo.scale.x,
                        pos.y * mo.scale.y,
                        pos.z * mo.scale.z
                                              );
                    Matrix4x4 cloudSpace   = offsetNoScale * Matrix4x4.TRS(scaledPos, rot, Vector3.one);
                    Matrix4x4 trackerSpace = Matrix4x4.TRS(camPos, camRot, Vector3.one);
                    Matrix4x4 m            = trackerSpace * (cloudSpace.inverse);
                    mo.space.filter.RefinePose(m);

                    LocalizerPose localizerPose;
                    GetLocalizerPose(out localizerPose, mapId, pos, rot, m.inverse);
                    OnPoseFound?.Invoke(localizerPose);
                }
            }

            yield return(StartCoroutine(base.Localize()));
        }
Exemple #12
0
        // The LoadMap function takes an URL and loads the map into GizmoSDK native db
        public bool LoadMap(string mapURL)
        {
            NodeLock.WaitLockEdit(); // We assume we do all editing from main thread and to allow render we assume we edit in edit mode

            try                      // We are now locked in edit
            {
                if (!ResetMap())
                {
                    return(false);
                }

                var node = DbManager.LoadDB(mapURL);

                if (node == null || !node.IsValid())
                {
                    Message.Send(ID, MessageLevel.WARNING, $"Failed to load map {mapURL}");
                    return(false);
                }

                MapUrl = mapURL;

                MapControl.SystemMap.NodeURL    = mapURL;
                MapControl.SystemMap.CurrentMap = node;

                _native_scene.AddNode(MapControl.SystemMap.CurrentMap);

                _native_scene.Debug();

                _root = new GameObject("root");

                GameObject scene = Traverse(MapControl.SystemMap.CurrentMap, null);

                if (scene != null)
                {
                    scene.transform.SetParent(_root.transform, false);
                }

                // As GizmoSDK has a flipped Z axis going out of the screen we need a top transform to flip Z
                _root.transform.localScale = new Vector3(1, 1, -1);


                //// Add example object under ROI --------------------------------------------------------------

                //MapPos mapPos;

                //GetMapPosition(new LatPos(1.0084718541, 0.24984267815, 300), out mapPos, GroundClampType.GROUND, true);

                //_test = GameObject.CreatePrimitive(PrimitiveType.Sphere);

                //_test.transform.parent = FindFirstGameObjectTransform(mapPos.roiNode);
                //_test.transform.localPosition = mapPos.position.ToVector3();
                //_test.transform.localScale = new Vector3(10, 10, 10);

                if (SceneManagerCamera != null)
                {
                    SceneManagerCamera.MapChanged();
                }

                OnMapChanged?.Invoke(node);
            }
            finally
            {
                NodeLock.UnLock();
            }

            return(true);
        }
Exemple #13
0
 public static void RestoreLanes(List <Lane> toberestored)
 {
     toberestored.ForEach(lane => { lane.SetGameobjVisible(true); allLanes.Add(lane); });
     OnMapChanged?.Invoke(null, allLanes);
 }
Exemple #14
0
 public static void DeleteLanes(List <Lane> tobedeleted)
 {
     tobedeleted.ForEach(lane => { lane.SetGameobjVisible(false); allLanes.Remove(lane); });
     OnMapChanged?.Invoke(null, allLanes);
 }
Exemple #15
0
        public override async void Localize()
        {
#if PLATFORM_LUMIN
            XRCameraImage image;
#else
            XRCpuImage image;
#endif
            ARCameraManager cameraManager   = m_Sdk.cameraManager;
            var             cameraSubsystem = cameraManager.subsystem;

#if PLATFORM_LUMIN
            if (cameraSubsystem != null && cameraSubsystem.TryGetLatestImage(out image))
#else
            if (cameraSubsystem != null && cameraSubsystem.TryAcquireLatestCpuImage(out image))
#endif
            {
                stats.localizationAttemptCount++;
                Vector4    intrinsics;
                Vector3    camPos = m_Cam.transform.position;
                Quaternion camRot = m_Cam.transform.rotation;
                ARHelper.GetIntrinsics(out intrinsics);
                ARHelper.GetPlaneDataFast(ref m_PixelBuffer, image);

                if (m_PixelBuffer != IntPtr.Zero)
                {
                    Vector3    pos = Vector3.zero;
                    Quaternion rot = Quaternion.identity;

                    float startTime = Time.realtimeSinceStartup;

                    Task <int> t = Task.Run(() =>
                    {
                        return(Immersal.Core.LocalizeImage(out pos, out rot, image.width, image.height, ref intrinsics, m_PixelBuffer));
                    });

                    await t;

                    int   mapHandle   = t.Result;
                    float elapsedTime = Time.realtimeSinceStartup - startTime;

                    if (mapHandle >= 0 && ARSpace.mapHandleToOffset.ContainsKey(mapHandle))
                    {
                        Debug.Log(string.Format("Relocalized in {0} seconds", elapsedTime));
                        stats.localizationSuccessCount++;

                        if (mapHandle != lastLocalizedMapHandle)
                        {
                            if (resetOnMapChange)
                            {
                                Reset();
                            }

                            lastLocalizedMapHandle = mapHandle;

                            OnMapChanged?.Invoke(mapHandle);
                        }

                        ARHelper.GetRotation(ref rot);
                        MapOffset mo = ARSpace.mapHandleToMap.ContainsKey(mapHandle) ? ARSpace.mapHandleToOffset[mapHandle] : null;

                        if (mo == null)
                        {
                            return;
                        }

                        Matrix4x4 offsetNoScale = Matrix4x4.TRS(mo.position, mo.rotation, Vector3.one);
                        Vector3   scaledPos     = new Vector3
                                                  (
                            pos.x * mo.scale.x,
                            pos.y * mo.scale.y,
                            pos.z * mo.scale.z
                                                  );
                        Matrix4x4 cloudSpace   = offsetNoScale * Matrix4x4.TRS(scaledPos, rot, Vector3.one);
                        Matrix4x4 trackerSpace = Matrix4x4.TRS(camPos, camRot, Vector3.one);
                        Matrix4x4 m            = trackerSpace * (cloudSpace.inverse);

                        if (useFiltering)
                        {
                            mo.space.filter.RefinePose(m);
                        }
                        else
                        {
                            ARSpace.UpdateSpace(mo.space, m.GetColumn(3), m.rotation);
                        }

                        LocalizerPose localizerPose;
                        GetLocalizerPose(out localizerPose, mapHandle, pos, rot, m.inverse);
                        OnPoseFound?.Invoke(localizerPose);

                        if (ARSpace.mapHandleToMap.ContainsKey(mapHandle))
                        {
                            ARMap map = ARSpace.mapHandleToMap[mapHandle];
                            map.NotifySuccessfulLocalization(mapHandle);
                        }
                    }
                    else
                    {
                        Debug.Log(string.Format("Localization attempt failed after {0} seconds", elapsedTime));
                    }
                }

                image.Dispose();
            }

            base.Localize();
        }
Exemple #16
0
        public override async void LocalizeServer(SDKMapId[] mapIds)
        {
#if PLATFORM_LUMIN
            XRCameraImage image;
#else
            XRCpuImage image;
#endif
            ARCameraManager cameraManager   = m_Sdk.cameraManager;
            var             cameraSubsystem = cameraManager.subsystem;

#if PLATFORM_LUMIN
            if (cameraSubsystem.TryGetLatestImage(out image))
#else
            if (cameraSubsystem.TryAcquireLatestCpuImage(out image))
#endif
            {
                stats.localizationAttemptCount++;

                JobLocalizeServerAsync j = new JobLocalizeServerAsync();

                byte[]     pixels;
                Camera     cam    = Camera.main;
                Vector3    camPos = cam.transform.position;
                Quaternion camRot = cam.transform.rotation;
                Vector4    intrinsics;
                int        channels = 1;
                int        width    = image.width;
                int        height   = image.height;

                ARHelper.GetIntrinsics(out intrinsics);
                ARHelper.GetPlaneData(out pixels, image);

                float startTime = Time.realtimeSinceStartup;

                Task <(byte[], icvCaptureInfo)> t = Task.Run(() =>
                {
                    byte[] capture      = new byte[channels * width * height + 1024];
                    icvCaptureInfo info = Immersal.Core.CaptureImage(capture, capture.Length, pixels, width, height, channels);
                    Array.Resize(ref capture, info.captureSize);
                    return(capture, info);
                });

                await t;

                j.image      = t.Result.Item1;
                j.position   = camPos;
                j.rotation   = camRot;
                j.intrinsics = intrinsics;
                j.mapIds     = mapIds;

                j.OnResult += async(SDKLocalizeResult result) =>
                {
                    float elapsedTime = Time.realtimeSinceStartup - startTime;

                    if (result.success)
                    {
                        Debug.Log("*************************** On-Server Localization Succeeded ***************************");
                        Debug.Log(string.Format("Relocalized in {0} seconds", elapsedTime));

                        int mapServerId = result.map;

                        if (mapServerId > 0 && ARSpace.mapHandleToOffset.ContainsKey(mapServerId))
                        {
                            if (mapServerId != lastLocalizedMapHandle)
                            {
                                if (resetOnMapChange)
                                {
                                    Reset();
                                }

                                lastLocalizedMapHandle = mapServerId;

                                OnMapChanged?.Invoke(mapServerId);
                            }

                            MapOffset mo = ARSpace.mapHandleToOffset[mapServerId];
                            stats.localizationSuccessCount++;

                            Matrix4x4 responseMatrix = Matrix4x4.identity;
                            responseMatrix.m00 = result.r00; responseMatrix.m01 = result.r01; responseMatrix.m02 = result.r02; responseMatrix.m03 = result.px;
                            responseMatrix.m10 = result.r10; responseMatrix.m11 = result.r11; responseMatrix.m12 = result.r12; responseMatrix.m13 = result.py;
                            responseMatrix.m20 = result.r20; responseMatrix.m21 = result.r21; responseMatrix.m22 = result.r22; responseMatrix.m23 = result.pz;

                            Vector3    pos = responseMatrix.GetColumn(3);
                            Quaternion rot = responseMatrix.rotation;
                            ARHelper.GetRotation(ref rot);

                            Matrix4x4 offsetNoScale = Matrix4x4.TRS(mo.position, mo.rotation, Vector3.one);
                            Vector3   scaledPos     = Vector3.Scale(pos, mo.scale);
                            Matrix4x4 cloudSpace    = offsetNoScale * Matrix4x4.TRS(scaledPos, rot, Vector3.one);
                            Matrix4x4 trackerSpace  = Matrix4x4.TRS(camPos, camRot, Vector3.one);
                            Matrix4x4 m             = trackerSpace * (cloudSpace.inverse);

                            if (useFiltering)
                            {
                                mo.space.filter.RefinePose(m);
                            }
                            else
                            {
                                ARSpace.UpdateSpace(mo.space, m.GetColumn(3), m.rotation);
                            }

                            JobEcefAsync je = new JobEcefAsync();
                            je.id        = mapServerId;
                            je.OnResult += (SDKEcefResult result2) =>
                            {
                                LocalizerPose localizerPose;
                                LocalizerBase.GetLocalizerPose(out localizerPose, mapServerId, pos, rot, m.inverse, result2.ecef);
                                OnPoseFound?.Invoke(localizerPose);
                            };

                            await je.RunJobAsync();

                            if (ARSpace.mapHandleToMap.ContainsKey(mapServerId))
                            {
                                ARMap map = ARSpace.mapHandleToMap[mapServerId];
                                map.NotifySuccessfulLocalization(mapServerId);
                            }
                        }
                        else
                        {
                            Debug.Log(string.Format("Localization attempt failed after {0} seconds", elapsedTime));
                        }
                    }
                    else
                    {
                        Debug.Log("*************************** On-Server Localization Failed ***************************");
                    }
                };

                await j.RunJobAsync();

                image.Dispose();
            }

            base.LocalizeServer(mapIds);
        }