예제 #1
0
    public void ButtonPress()
    {
        if (! Init())
            return;

        GameObject obj = EventSystem.current.currentSelectedGameObject;
        if (obj.name == "Title" && ! buttonCanvas.overlayShowing)
        {
#if DEVELOPMENT_BUILD && ! UNITY_EDITOR
            buttonCanvas.ShowQuestionOverlay(
                "THIS IS A DEVELOPMENT BUILD OF THE GAME.\n\nThis version of the game is for testing and evaluation purposes only. Please do not distribute.",
                "Proceed to game",
                null,
                delegate(string pressedButton)
                {
                    buttonCanvas.HideOverlay();
#endif
                    DeviceInput.RequestCameraPermission();
                    buttonCanvas.ShowBattery();
                    gameState.LoadScene("MapScene");
#if DEVELOPMENT_BUILD && ! UNITY_EDITOR
                }
            );
#endif
        }
    }
예제 #2
0
        public IActionResult TestConnectionS7([FromBody] DeviceInput input)
        {
            var result = new ResultApi();

            try
            {
                var client = new S7Client()
                {
                    PduSizeRequested = 960
                };
                client.ConnectTo(input.host, input.slot, input.rack);
                if (client.Connected)
                {
                    client.Disconnect();
                    result.result = true;
                }
                else
                {
                    result.result = false;
                }
            }
            catch (Exception e)
            {
                result.result  = false;
                result.message = e.Message;
            }

            return(Ok(result));
        }
예제 #3
0
        public void Map(RetroPadMapping mapping)
        {
            ClearMappings();
            if (mapping == null)
            {
                return;
            }

            foreach (var kvp in mapping.ButtonMappings)
            {
                DeviceInput deviceInput = kvp.Value;
                if (deviceInput.InputType == InputType.Button)
                {
                    ushort            button;
                    DirectionPadState directionPadState;
                    if (ushort.TryParse(deviceInput.Id, out button))
                    {
                        _buttonToButtonMappings.Add(kvp.Key, button);
                    }
                    else if (Enum.TryParse(deviceInput.Id, out directionPadState))
                    {
                        _directionPadToButtonMappings.Add(kvp.Key, directionPadState);
                    }
                }
                else if (deviceInput.InputType == InputType.Axis)
                {
                    ushort axis;
                    if (ushort.TryParse(deviceInput.Id, out axis))
                    {
                        _analogToButtonMappings.Add(kvp.Key, new HidAxis(axis, deviceInput.PositiveValues));
                    }
                }
            }

            foreach (var kvp in mapping.AnalogMappings)
            {
                DeviceInput deviceInput = kvp.Value;
                if (deviceInput.InputType == InputType.Button)
                {
                    ushort            button;
                    DirectionPadState directionPadState;
                    if (ushort.TryParse(deviceInput.Id, out button))
                    {
                        _buttonToAnalogMappings.Add(kvp.Key, button);
                    }
                    else if (Enum.TryParse(deviceInput.Id, out directionPadState))
                    {
                        _directionPadToAnalogMappings.Add(kvp.Key, directionPadState);
                    }
                }
                else if (deviceInput.InputType == InputType.Axis)
                {
                    ushort axis;
                    if (ushort.TryParse(deviceInput.Id, out axis))
                    {
                        _analogToAnalogMappings.Add(kvp.Key, new HidAxis(axis, deviceInput.PositiveValues));
                    }
                }
            }
        }
예제 #4
0
 public ThreadSupport(DeviceInput device, int ChannelCount, int TickCount)
 {
     this.device       = device;
     this.ChannelCount = ChannelCount;
     this.TickCount    = TickCount;
     inputdata         = new float[ChannelCount * TickCount];
 }
예제 #5
0
 public void Input(DeviceInput input)
 {
     if (OnRemotePressed != null)
     {
         OnRemotePressed(input);
     }
 }
예제 #6
0
    public bool ProcessMapSceneModuleIncrement(bool scenesAvailable)
    {
        // if not in edit mode and there are no active waypoints, we have reached the end of a module
        // and should increment the module number and reread the waypoints
        if (scenesAvailable)
        {
            hasIncrementedModuleNumber = false;
        }
        else if (!hasIncrementedModuleNumber)
        {
            hasIncrementedModuleNumber = true;
            AppendToAnalyticsString("_");
            SetFlag("Global%Module", GetFlagIntValue("Global%Module") + 1);
        }
        else
        {
            hasIncrementedModuleNumber = false;
            Debug.LogError("No activatable scenes for module " + GetFlagIntValue("Global%Module") + "!");

            // decrement the module number that we have erroneously incremented
            if (GetFlagIntValue("Global%Module") == GetFlagIntValue("Global%HighestModule"))
            {
                SetFlag("Global%HighestModule", GetFlagIntValue("Global%HighestModule") - 1);
            }
            SetFlag("Global%Module", GetFlagIntValue("Global%Module") - 1);
        }
        if (!hasIncrementedModuleNumber)
        {
            Debug.Log("Analytics: " + DeviceInput.HumanReadableEncoding(PlayerPrefs.GetString("AnalyticsCode")));
        }
        return(hasIncrementedModuleNumber);
    }
        private static IDeviceInput GetOrCreateDeviceInput(ICueDevice cueDevice)
        {
            IDeviceInput deviceInput;

            if (!_deviceInputMapping.TryGetValue(cueDevice, out deviceInput))
            {
                _deviceInputMapping.Add(cueDevice, (deviceInput = new DeviceInput(cueDevice)));
            }
            return(deviceInput);
        }
예제 #8
0
 private void MessageResponse(string pressedButton)
 {
     HideOverlay();
     if (pressedButton == "Exit game")
     {
         DeviceInput.ExitGame(this);
     }
     else if (pressedButton == "Take me to Settings")
     {
         DeviceInput.ShowDeviceSettings();
     }
 }
예제 #9
0
    public void Start()
    {
        diggingMode = DiggingMode.NotDigging;
        mouseMode   = InputEnabled.Disabled;

        computerInputMode = InputEnabled.Disabled;
        computerInput     = FindObjectOfType <ComputerInput>();
        computerInput.gameObject.SetActive(false);

        deviceInputMode = InputEnabled.Disabled;
        deviceInput     = FindObjectOfType <DeviceInput>();
        deviceInput.gameObject.SetActive(false);
    }
예제 #10
0
파일: PreBuild.cs 프로젝트: ericvids/magis
    public void OnPreprocessBuild(BuildReport report)
    {
        if (Autorun.buildNotReady || AssetDatabase.IsValidFolder("Assets/_DO NOT COMMIT RIGHT NOW - Unity is using the project"))
        {
            EditorUtility.DisplayDialog("MAGIS", "MAGIS has detected that you are attempting to perform a build while it is not in a ready state. This will lead to a corrupted build.\n\nDue to Unity missing the necessary callback, it is not possible for MAGIS to cancel the build. Please manually cancel it by pressing OK in this dialog and pressing Cancel in the progress window that appears.", "OK");
            return;
        }

        // do this before build

        // if we don't call this before creating the dummy folder, unity will be in a non-compiling state
        // and the dummy folder gets removed prematurely
        AssetDatabase.SaveAssets();

        // upon building, hide unnecessary resources
        AssetDatabase.CreateFolder("Assets", "_DO NOT COMMIT RIGHT NOW - Unity is using the project");

        // to ensure that the only markers included in the built package are that of the current game,
        // we move all other markers to a temporary folder
        if (!Autorun.singleGameProject && !AssetDatabase.IsValidFolder("Assets/StreamingAssetsBackup"))
        {
            Debug.Log("Backing up StreamingAssets that are not used for this project");
            AssetDatabase.MoveAsset("Assets/StreamingAssets", "Assets/StreamingAssetsBackup");
            AssetDatabase.CreateFolder("Assets", "StreamingAssets");
            AssetDatabase.CreateFolder("Assets/StreamingAssets", "Vuforia");
            AssetDatabase.MoveAsset("Assets/StreamingAssetsBackup/Vuforia/magis-default.dat",
                                    "Assets/StreamingAssets/Vuforia/magis-default.dat");
            AssetDatabase.MoveAsset("Assets/StreamingAssetsBackup/Vuforia/magis-default.xml",
                                    "Assets/StreamingAssets/Vuforia/magis-default.xml");
            AssetDatabase.MoveAsset("Assets/StreamingAssetsBackup/Vuforia/" + DeviceInput.GameName() + ".dat",
                                    "Assets/StreamingAssets/Vuforia/" + DeviceInput.GameName() + ".dat");
            AssetDatabase.MoveAsset("Assets/StreamingAssetsBackup/Vuforia/" + DeviceInput.GameName() + ".xml",
                                    "Assets/StreamingAssets/Vuforia/" + DeviceInput.GameName() + ".xml");
        }

#if MAGIS_NOGPS && !MAGIS_BLE
        BackupFile("Assets/AREngine/Plugins/iOS/Location.mm");
#endif

#if MAGIS_BLE
        ReplaceFile("Assets/Plugins/Android/AndroidManifest.xml", "Assets/AREngine/Plugins/Android/AndroidManifestBT.xml");
#else
        BackupFile("Assets/Plugins/Android/unityandroidbluetoothlelib.jar");
        BackupFile("Assets/Plugins/iOS/UnityBluetoothLE.mm");
#endif

        AssetDatabase.Refresh();
        Debug.Log("Writing " + report.summary.platform + " build to " + report.summary.outputPath);
    }
예제 #11
0
        public bool TryMap()
        {
            MappedInput selectedInput = SelectedInput;

            if (selectedInput != null)
            {
                DeviceInput input = _deviceMapper.GetPressedInput();
                if (input != null)
                {
                    selectedInput.Input = input;
                    _currentMapping.Map(selectedInput);
                    return(true);
                }
            }
            return(false);
        }
예제 #12
0
        public void AddControlInput(int controlIndex, string deviceName)
        {
            if (rebinding)
            {
                return;
            }
            //Debug.Log("Add new input for : " + controls[controlIndex].name + " of " + deviceName);

            InputDeviceType t = InputDeviceType.Keyboard;

            if (deviceName != "KeyboardMouse")
            {
                t = InputDeviceType.GamepadButton;
            }
            DeviceInput newInput = new DeviceInput(t);

            newInput.isCustom          = true;
            newInput.deviceName        = deviceName;
            newInput.commonMappingType = CommonGamepadInputs.NOBUTTON;            //don't remove this input when gamepads are unplugged/replugged

            if (t == InputDeviceType.Keyboard)
            {
                newInput.keyboardKeyCode = KeyCode.None;
            }

            if (t == InputDeviceType.GamepadButton)
            {
                newInput.gamepadButtonNumber = 18;
                newInput.displayName         = "B?";

                string[]   padNames     = Input.GetJoystickNames();
                List <int> allowedSlots = new List <int>();
                for (int i = 0; i < padNames.Length; i++)
                {
                    if (padNames[i].ToUpper() == deviceName.ToUpper())
                    {
                        allowedSlots.Add(i);
                    }
                }
                newInput.allowedSlots = allowedSlots.ToArray();
            }


            controls[controlIndex].inputs.Add(newInput);

            BuildRebindingPanels();
        }
예제 #13
0
        public IActionResult Delete([FromBody] DeviceInput name)
        {
            var result = new ResultApi();

            try
            {
                DeviceService.DeleteDevice(name);
                result.result = true;
            }
            catch (Exception e)
            {
                result.result  = false;
                result.message = e.Message;
            }

            return(Ok(result));
        }
예제 #14
0
        public void DeleteDevice(DeviceInput input)
        {
            var configFolder = GetConfigFolder();
            var fileName     = input.ContextName + ".json";
            var configPath   = Path.Combine(configFolder, fileName);

            var configString = File.ReadAllText(configPath);
            var config       = JsonSerializer.Deserialize <OtmContextConfig>(configString);

            var index = config.Devices.FindIndex(row => row.Id == input.Id);

            config.Devices.RemoveAt(index);

            var configJson = JsonSerializer.Serialize <OtmContextConfig>(config);

            File.WriteAllText(configPath, configJson);
        }
예제 #15
0
        private void Remote_OnRemotePressed(DeviceInput deviceInput)
        {
            switch (deviceInput)
            {
            case DeviceInput.UP: Remote.Instance().Log("音量增"); Remote.Instance().VolUp(); break;

            case DeviceInput.DOWN: Remote.Instance().Log("音量减"); Remote.Instance().VolDown(); break;

            case DeviceInput.LEFT: break;

            case DeviceInput.RIGHT: break;

            case DeviceInput.PREVIOUS: Remote.Instance().Log("上一个"); Remote.Instance().PlayPreviousmovie(); break;

            case DeviceInput.NEXT: Remote.Instance().Log("下一个"); Remote.Instance().PlayNextmovie(); break;
            }
        }
예제 #16
0
 public void ExitGame()
 {
     buttonCanvas.HideOverlay();
     buttonCanvas.ShowQuestionOverlay("Are you sure you want to exit?",
                                      "Exit game",
                                      "Continue playing",
                                      delegate(string pressedButton)
     {
         buttonCanvas.HideOverlay();
         if (pressedButton == "Exit game")
         {
             DeviceInput.ExitGame(buttonCanvas);
         }
         else
         {
             buttonCanvas.ShowOptionsOverlay(closeDelegate);
         }
     });
 }
예제 #17
0
    // Use this for initialization
    void Start()
    {
        //Screen.sleepTimeout = SleepTimeout.NeverSleep ;
        DeviceInput.Init();

        // setup smoothing class
        Smoothed.SetSmoothingStrength(Smooth);

        // sensor fusion needs gyroscope
        m_UseSensorFusion = DeviceInput.HasGyro;

        m_ToggleFlash.isOn        = m_FlashingFocus;
        m_ToggleSnap.isOn         = m_SnapIfAccurate;
        m_ToggleSensorFusion.isOn = m_UseSensorFusion;
        if (!DeviceInput.HasGyro)
        {
            m_ToggleSensorFusion.interactable = false;
        }

        // find parent
        m_PhotoTask = transform.parent.gameObject.GetComponent <PhotoTask> ();
        // setup label objects
        for (int i = 0; i < 4; i++)
        {
            // TaskPanel
            Panels[i]         = transform.Find(PanelTitles[i]).gameObject.GetComponent <TaskPanel> ();
            Panels[i].Heading = 90.0f * i;
            Panels[i].Pitch   = TaskPitch;
            Panels[i].Name    = PanelNames [i];
        }
        // setup frame
        // Panel_Frame
        Transform TrFrame = transform.Find("Panel_Frame");

        KompassFrame = TrFrame.gameObject;

        TrFrame.SetParent(transform.parent, false);

        m_StringTakePhoto = LocalizationSupport.GetString("TakePhotoPoint");
        m_StringHoldStill = LocalizationSupport.GetString("TakePhotoHoldStill");
        m_StringLandscape = LocalizationSupport.GetString("TakePhotoLandscape");
        m_StringFocus     = LocalizationSupport.GetString("TakePhotoFocus");
    }
예제 #18
0
        public bool Save(DeviceInput entity)
        {
            //List<Entity.BaseNoSqlEntity> lst = new List<Entity.BaseNoSqlEntity>();
            //entity.RowKey = entity.ID.ToString();
            //entity.PartitionKey = ApartmentConstants.PartitionKey;
            //entity.TableName = "Device";

            //lst.Add(entity);

            //Entity.Address address = entity.Address;
            //address.PartitionKey = ApartmentConstants.PartitionKey;
            //address.TableName = "Address";
            //address.RowKey = address.ID.ToString();


            //lst.Add(address);
            //return SaveBatch(lst);
            TableStorageService <BaseAzureTableStorage> StorageService = new TableStorageService <BaseAzureTableStorage>(DeviceInputDataConstants.TableName);

            StorageService.CreateTable();
            return(StorageService.Insert(entity));
        }
예제 #19
0
    static void Update()
    {
        if (CheckIfProjectSwitchNeeded())
        {
            return;
        }

        if (EditorApplication.isPlaying)
        {
            if (!AssetDatabase.IsValidFolder("Assets/_DO NOT COMMIT RIGHT NOW - Unity is using the project"))
            {
                if (buildNotReady)
                {
                    // do not allow running at an inconsistent state
                    Debug.LogError("Cannot play because MAGIS project is in an inconsistent state. Please fix any issues that weren't resolved by Autorun.CleanUp() and reload the project.");
                    EditorApplication.isPlaying = false;
                    return;
                }
                buildNotReady = true;

                // upon running, hide unnecessary resources
                AssetDatabase.CreateFolder("Assets", "_DO NOT COMMIT RIGHT NOW - Unity is using the project");
                AssetDatabase.Refresh();

                // force editor to play at 1x scale or lower
                Type         type       = typeof(EditorWindow).Assembly.GetType("UnityEditor.GameView");
                EditorWindow w          = EditorWindow.GetWindow(type);
                var          areaField  = type.GetField("m_ZoomArea", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                var          areaObj    = areaField.GetValue(w);
                var          scaleField = areaObj.GetType().GetField("m_Scale", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                Vector2      value      = (Vector2)scaleField.GetValue(areaObj);
                if (value.x > 1.0f)
                {
                    scaleField.SetValue(areaObj, new Vector2(1.0f, 1.0f));
                }

                loadedLevel = null;
                if (GameObject.FindWithTag("ARMarker") != null && GameObject.FindWithTag("AREngine") == null)
                {
                    // temporarily halt the loading of an AR editor level to load CommonScene
                    loadedLevel = SceneManager.GetActiveScene().name;
                    SceneManager.LoadScene("CommonScene");
                    DeviceInput.RequestCameraPermission();
                    Debug.Log("Starting ARScene");
                }
                else if (GameObject.Find("GameState") == null)
                {
                    // for other levels that come with arengine, always run from the beginning
                    if (SceneManager.GetActiveScene().name == "ARScene" ||
                        SceneManager.GetActiveScene().name == "ARSubscene" ||
                        SceneManager.GetActiveScene().name == "CommonScene" ||
                        SceneManager.GetActiveScene().name == "TitleScene" ||
                        SceneManager.GetActiveScene().name == "MapScene" ||
                        SceneManager.GetActiveScene().name == "")
                    {
                        SceneManager.LoadScene("CommonScene");
                        Debug.Log("Starting MAGIS from the title screen");
                    }
                }
            }
            else if (buildNotReady && loadedLevel != null)
            {
                // actually load the current editor level, and also load ARScene automatically if needed
                SceneManager.LoadScene(loadedLevel);
                SceneManager.LoadScene("ARScene", LoadSceneMode.Additive);
                loadedLevel = null;
            }
        }
        else if (!EditorApplication.isPlaying && !EditorApplication.isCompiling && !EditorApplication.isUpdating)
        {
            // automatically switch target to iOS or Android if the current target is Windows, macOS, etc.
            // (doing it here intentionally because we don't want to do it during Autorun constructor)
            if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.iOS &&
                EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
            {
                buildNotReady = true;
                if ((int)System.Environment.OSVersion.Platform == 4 || (int)System.Environment.OSVersion.Platform == 6)
                {
                    EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.iOS, BuildTarget.iOS);
                }
                else
                {
                    EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
                }
                return;
            }
            else
            {
                if (!EditorUserBuildSettings.GetBuildLocation(BuildTarget.iOS).EndsWith("ios_" + DeviceInput.GameName()))
                {
                    EditorUserBuildSettings.development = true;
                }
                EditorUserBuildSettings.buildAppBundle = !EditorUserBuildSettings.development;
                EditorUserBuildSettings.SetBuildLocation(BuildTarget.iOS, "ios_" + DeviceInput.GameName());
                if (EditorUserBuildSettings.buildAppBundle)
                {
                    EditorUserBuildSettings.SetBuildLocation(BuildTarget.Android, "aab_" + DeviceInput.GameName() + ".aab");
                }
                else
                {
                    EditorUserBuildSettings.SetBuildLocation(BuildTarget.Android, "apk_" + DeviceInput.GameName() + ".apk");
                }
            }

            // fix to remove empty .fbm folders that create spurious meta files
            // (doing it here intentionally because we don't want to do it during Autorun constructor)
            foreach (string asset in AssetDatabase.FindAssets(".fbm"))
            {
                string folder = AssetDatabase.GUIDToAssetPath(asset);
                if (AssetDatabase.IsValidFolder(folder))
                {
                    if (AssetDatabase.FindAssets("t:Object", new[] { folder }).Length == 0)
                    {
                        buildNotReady = true;
                        Debug.Log("Deleting empty folder " + folder);
                        AssetDatabase.DeleteAsset(folder);
                    }
                }
            }

            // fix to remove extraneous _TerrainAutoUpgrade
            // (doing it here intentionally because we don't want to do it during Autorun constructor)
            if (AssetDatabase.IsValidFolder("Assets/_TerrainAutoUpgrade"))
            {
                buildNotReady = true;
                Debug.Log("Deleting migration folder _TerrainAutoUpgrade");
                AssetDatabase.DeleteAsset("Assets/_TerrainAutoUpgrade");
            }

            CleanUp();
        }
        else
        {
            buildNotReady = true;
        }
    }
예제 #20
0
    static bool CheckIfProjectSwitchNeeded()
    {
        if (singleGameProject || EditorApplication.isPlaying || EditorApplication.isCompiling || EditorApplication.isUpdating)
        {
            // do not switch game projects if no ARGameList.txt is found or when Unity is busy doing stuff
            return(false);
        }

        if (restarting || !productNameToCloudProjectId.ContainsKey(Application.productName))
        {
            // do not waste time in Update() when we are in an invalid state
            return(true);
        }

        if (CloudProjectSettings.projectId != "" && productNameToCloudProjectId[Application.productName] != CloudProjectSettings.projectId)
        {
            if (!AssetDatabase.IsValidFolder("Assets/_DO NOT COMMIT RIGHT NOW - If Unity crashed, restart it now"))
            {
                EditorUtility.DisplayDialog("MAGIS", "The current MAGIS game has switched to '" + Application.productName + "'.\n\nRestart of Unity is required.\n\n" + "Current project id = " + CloudProjectSettings.projectId + "\nNew project id = " + productNameToCloudProjectId[Application.productName], "Restart Unity");
                EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
                AssetDatabase.SaveAssets();
                AssetDatabase.CreateFolder("Assets", "_DO NOT COMMIT RIGHT NOW - If Unity crashed, restart it now");
                AssetDatabase.Refresh();
                return(true);
            }

            restarting = true;

            StreamReader reader = new StreamReader("Assets/ARGames/ARGameList.txt");
            string[]     rows   = reader.ReadToEnd().Split('\n');
            reader.Close();
            for (int i = 0; i < rows.Length; i++)
            {
                if (rows[i].EndsWith("\r"))
                {
                    rows[i] = rows[i].Substring(0, rows[i].Length - 1);
                }
                string[] cols = rows[i].Split(',');
                if (cols[(int)ARGameList.PRODUCT_NAME] == Application.productName)
                {
                    reader = new StreamReader("ProjectSettings/ProjectSettings.asset");
                    rows   = reader.ReadToEnd().Split('\n');
                    reader.Close();

                    for (i = 0; i < rows.Length; i++)
                    {
                        if (rows[i].EndsWith("\r"))
                        {
                            rows[i] = rows[i].Substring(0, rows[i].Length - 1);
                        }

                        int    versionMajor    = System.DateTime.Now.Year - 2015; // Igpaw's first release was in 2015
                        int    versionMinor    = System.DateTime.Now.Month;
                        int    versionRevision = System.DateTime.Now.Day;
                        string versionString   = versionMajor + "." + versionMinor + "." + versionRevision;
                        int    versionCode     = versionMajor * 10000 + versionMinor * 100 + versionRevision;

                        if (rows[i].StartsWith("  bundleVersion: "))
                        {
                            rows[i] = "  bundleVersion: " + versionString;
                        }
                        if (rows[i].StartsWith("    iPhone: ") && rows[i].Length > 13 && rows[i][12] >= '0' && rows[i][12] <= '9' && rows[i][13] >= '0' && rows[i][13] <= '9')
                        {
                            rows[i] = "    iPhone: " + versionCode;
                        }
                        if (rows[i].StartsWith("  AndroidBundleVersionCode: "))
                        {
                            rows[i] = "  AndroidBundleVersionCode: " + versionCode;
                        }
                        if (rows[i].StartsWith("  productName: "))
                        {
                            rows[i] = "  productName: " + Quotify(cols[(int)ARGameList.PRODUCT_NAME]);
                        }
                        if (rows[i].StartsWith("    iPhone: ") && rows[i][12] >= 'a' && rows[i][12] <= 'z')
                        {
                            rows[i] = "    iPhone: " + cols[(int)ARGameList.IOS_ID];
                        }
                        if (rows[i].StartsWith("    Android: ") && rows[i][13] >= 'a' && rows[i][13] <= 'z')
                        {
                            rows[i] = "    Android: " + cols[(int)ARGameList.ANDROID_ID];
                        }
                        if (rows[i].StartsWith("  cloudProjectId: "))
                        {
                            rows[i] = "  cloudProjectId: " + cols[(int)ARGameList.CLOUD_PROJECT_ID];
                        }
                        if (rows[i].StartsWith("  projectName: "))
                        {
                            rows[i] = "  projectName: " + Quotify(cols[(int)ARGameList.CLOUD_PROJECT_NAME]);
                        }
                        if (rows[i].StartsWith("  AndroidKeystoreName: "))
                        {
                            if (cols[(int)ARGameList.ANDROID_KEYALIAS_NAME] == "")
                            {
                                rows[i] = "  AndroidKeystoreName: ";
                            }
                            else
                            {
                                rows[i] = "  AndroidKeystoreName: '{inproject}: " + DeviceInput.GameName() + ".keystore'";
                            }
                        }
                        if (rows[i].StartsWith("  AndroidKeyaliasName: "))
                        {
                            if (cols[(int)ARGameList.ANDROID_KEYALIAS_NAME] == "")
                            {
                                rows[i] = "  AndroidKeyaliasName: ";
                            }
                            else
                            {
                                rows[i] = "  AndroidKeyaliasName: " + Quotify(cols[(int)ARGameList.ANDROID_KEYALIAS_NAME]);
                            }
                        }
                        if (rows[i].StartsWith("  androidUseCustomKeystore: "))
                        {
                            if (cols[(int)ARGameList.ANDROID_KEYALIAS_NAME] == "")
                            {
                                rows[i] = "  androidUseCustomKeystore: 0";
                            }
                            else
                            {
                                rows[i] = "  androidUseCustomKeystore: 1";
                            }
                        }
                        if (rows[i].StartsWith("  androidSplashScreen: {fileID: 2800000, guid: "))
                        {
                            reader = new StreamReader("Assets/ARGames/" + DeviceInput.GameName() + "/Resources/LoadingScreen.png.meta");
                            string text = reader.ReadToEnd();
                            reader.Close();
                            string guid = text.Substring(text.IndexOf("guid: ") + 6, 32);
                            rows[i] = "  androidSplashScreen: {fileID: 2800000, guid: " + guid + ", type: 3}";
                        }
                        if (rows[i].StartsWith("      m_Icon: {fileID: 2800000, guid: "))
                        {
                            reader = new StreamReader("Assets/ARGames/" + DeviceInput.GameName() + "/Resources/AppIcon.png.meta");
                            string text = reader.ReadToEnd();
                            reader.Close();
                            string guid = text.Substring(text.IndexOf("guid: ") + 6, 32);
                            rows[i] = "      m_Icon: {fileID: 2800000, guid: " + guid + ", type: 3}";
                        }
                        if (rows[i].StartsWith("    4: VUFORIA_IOS_SETTINGS"))
                        {
                            rows[i] = "    4: VUFORIA_IOS_SETTINGS;MAGIS_" + DeviceInput.GameName() + (int.Parse(cols[(int)ARGameList.GPS_SUPPORT]) == 0 ? ";MAGIS_NOGPS" : "") + (int.Parse(cols[(int)ARGameList.BLE_SUPPORT]) == 0 ? "" : ";MAGIS_BLE");
                        }
                        if (rows[i].StartsWith("    7: VUFORIA_ANDROID_SETTINGS"))
                        {
                            rows[i] = "    7: VUFORIA_ANDROID_SETTINGS;MAGIS_" + DeviceInput.GameName() + (int.Parse(cols[(int)ARGameList.GPS_SUPPORT]) == 0 ? ";MAGIS_NOGPS" : "") + (int.Parse(cols[(int)ARGameList.BLE_SUPPORT]) == 0 ? "" : ";MAGIS_BLE");
                        }
                    }

                    while (rows[rows.Length - 1] == "")
                    {
                        Array.Resize(ref rows, rows.Length - 1);
                    }
                    StreamWriter writer = new StreamWriter("ProjectSettings/ProjectSettings.asset");
                    foreach (string row in rows)
                    {
                        writer.WriteLine(row);
                    }
                    writer.Close();

                    reader = new StreamReader("Assets/Resources/VuforiaConfiguration.asset");
                    rows   = reader.ReadToEnd().Split('\n');
                    reader.Close();

                    for (i = 0; i < rows.Length; i++)
                    {
                        if (rows[i].EndsWith("\r"))
                        {
                            rows[i] = rows[i].Substring(0, rows[i].Length - 1);
                        }

                        if (rows[i].StartsWith("    vuforiaLicenseKey: "))
                        {
                            rows[i] = "    vuforiaLicenseKey: " + cols[(int)ARGameList.VUFORIA_LICENSE_KEY];
                        }
                        else if (rows[i].StartsWith("    ufoLicenseKey: "))
                        {
                            rows[i] = "    ufoLicenseKey: ";
                        }
                        else if (rows[i].StartsWith("    deviceNameSetInEditor: "))
                        {
                            rows[i] = "    deviceNameSetInEditor: ";
                        }
                        else if (rows[i].StartsWith("    turnOffWebCam: "))
                        {
                            rows[i] = "    turnOffWebCam: 1";
                        }
                    }

                    while (rows[rows.Length - 1] == "")
                    {
                        Array.Resize(ref rows, rows.Length - 1);
                    }
                    writer = new StreamWriter("Assets/Resources/VuforiaConfiguration.asset");
                    foreach (string row in rows)
                    {
                        writer.WriteLine(row);
                    }
                    writer.Close();

                    writer = new StreamWriter("ProjectSettings/EditorBuildSettings.asset");
                    writer.WriteLine("%YAML 1.1");
                    writer.WriteLine("%TAG !u! tag:unity3d.com,2011:");
                    writer.WriteLine("--- !u!1045 &1");
                    writer.WriteLine("EditorBuildSettings:");
                    writer.WriteLine("  m_ObjectHideFlags: 0");
                    writer.WriteLine("  serializedVersion: 2");
                    writer.WriteLine("  m_Scenes:");
                    writer.WriteLine("  - enabled: 1");
                    writer.WriteLine("    path: Assets/AREngine/Scenes/CommonScene.unity");
                    writer.WriteLine("  - enabled: 1");
                    writer.WriteLine("    path: Assets/AREngine/Scenes/ARScene.unity");
                    writer.WriteLine("  - enabled: 1");
                    writer.WriteLine("    path: Assets/AREngine/Scenes/ARSubscene.unity");
                    writer.WriteLine("  - enabled: 1");
                    writer.WriteLine("    path: Assets/AREngine/Scenes/TitleScene.unity");
                    foreach (string scene in Directory.GetFiles("Assets/ARGames/" + DeviceInput.GameName() + "/Scenes"))
                    {
                        if (scene.EndsWith(".unity"))
                        {
                            writer.WriteLine("  - enabled: 1");
                            writer.WriteLine("    path: Assets/ARGames/" + DeviceInput.GameName() + "/Scenes/" + Path.GetFileName(scene));
                        }
                    }
                    writer.Close();

                    EditorApplication.OpenProject(Application.dataPath + "/..");
                    return(true);
                }
            }

            // if we get here, the project is not defined (but this should normally not happen!)
            EditorUtility.DisplayDialog("MAGIS", "The project name '" + Application.productName + "' is not defined in Assets/ARGames/ARGameList.txt.\n\nPlease add an entry for this project name and restart Unity.", "Close Unity");
            EditorApplication.Exit(1);
            return(true);
        }

        return(false);
    }
예제 #21
0
    private void Start()
    {
        gameState = GameObject.Find("GameState").GetComponent <GameStateBehaviour>();
        if (GameObject.FindWithTag("AREngine") != null)
        {
            engine = GameObject.FindWithTag("AREngine").GetComponent <AREngineBehaviour>();
        }

        GameObject.Find("Panel/AppDetails/AppIconMask/AppIcon").GetComponent <UnityEngine.UI.Image>().overrideSprite = Resources.Load <Sprite>("AppIcon");
        GameObject.Find("Panel/AppDetails/AppTitle").GetComponent <UnityEngine.UI.Text>().text   = Application.productName;
        GameObject.Find("Panel/AppDetails/AppVersion").GetComponent <UnityEngine.UI.Text>().text = "Version " + Application.version + "  <color=#000080>Credits...</color>  " + DeviceInput.HumanReadableEncoding(DeviceInput.deviceSerial);

        bool tutorialExists = false;

        if (Resources.Load <TextAsset>("Cards/Tutorial") != null)
        {
            tutorialExists = true;
        }
        else
        {
            for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
            {
                string scenePath = SceneUtility.GetScenePathByBuildIndex(i);
                scenePath = scenePath.Substring(scenePath.LastIndexOf("/") + 1);
                if (scenePath == "M0%Scene1.unity")
                {
                    tutorialExists = true;
                }
            }
        }

        if (engine != null)
        {
            if (gameState.sceneName == "M0%Scene1" && !gameState.GetFlag("M0%Scene1%End"))
            {
                GameObject.Find("Panel/ReturnToMap/Label").GetComponent <UnityEngine.UI.Text>().text = "Skip tutorial";
            }
            Destroy(GameObject.Find("Panel/ReplayTutorial"));
            Destroy(GameObject.Find("Panel/ReplayEnding"));
        }
        else if (!gameState.GetFlag("Global%GameEnd"))
        {
            if (tutorialExists)
            {
                GameObject.Find("Panel/ReturnToMap/Label").GetComponent <UnityEngine.UI.Text>().text = "Replay tutorial";
            }
            else
            {
                Destroy(GameObject.Find("Panel/ReturnToMap"));
            }
            Destroy(GameObject.Find("Panel/ReplayTutorial"));
            Destroy(GameObject.Find("Panel/ReplayEnding"));
        }
        else
        {
            if (tutorialExists)
            {
                Destroy(GameObject.Find("Panel/ReturnToMap"));
            }
            else
            {
                GameObject.Find("Panel/ReturnToMap/Label").GetComponent <UnityEngine.UI.Text>().text = "Replay ending";
                Destroy(GameObject.Find("Panel/ReplayTutorial"));
                Destroy(GameObject.Find("Panel/ReplayEnding"));
            }
        }

        GameObject.Find("Panel/LeftHandedMode").GetComponent <UnityEngine.UI.Toggle>().isOn = gameState.GetFlag("System%SwapButtonGroups");
        if (!DeviceInput.gyroPresent)
        {
            GameObject.Find("Panel/UseGyroscope").GetComponent <UnityEngine.UI.Toggle>().enabled   = false;
            GameObject.Find("Panel/UseGyroscope/Label").GetComponent <UnityEngine.UI.Text>().color = Color.gray;
            GameObject.Find("Panel/UseGyroscope/Text").GetComponent <UnityEngine.UI.Text>().text   = "Unable to detect gyroscope";
            GameObject.Find("Panel/UseGyroscope/Text").GetComponent <UnityEngine.UI.Text>().color  = Color.red;
        }
        GameObject.Find("Panel/UseGyroscope").GetComponent <UnityEngine.UI.Toggle>().isOn = gameState.GetFlag("System%UseGyroscope");
        if (!DeviceInput.compassPresent)
        {
            GameObject.Find("Panel/UseCompass").GetComponent <UnityEngine.UI.Toggle>().enabled   = false;
            GameObject.Find("Panel/UseCompass/Label").GetComponent <UnityEngine.UI.Text>().color = Color.gray;
            GameObject.Find("Panel/UseCompass/Text").GetComponent <UnityEngine.UI.Text>().text   = "Unable to detect compass";
            GameObject.Find("Panel/UseCompass/Text").GetComponent <UnityEngine.UI.Text>().color  = Color.red;
        }
        GameObject.Find("Panel/UseCompass").GetComponent <UnityEngine.UI.Toggle>().isOn = gameState.GetFlag("System%UseCompass");

#if !UNITY_ANDROID
        // compass only supported on android
        Destroy(GameObject.Find("Panel/UseCompass"));
#endif
    }
예제 #22
0
    static Autorun()
    {
        EditorApplication.update += Update;

        try
        {
            StreamReader reader = new StreamReader("Assets/ARGames/ARGameList.txt");
            string[]     rows   = reader.ReadToEnd().Split('\n');
            reader.Close();
            for (int i = 0; i < rows.Length; i++)
            {
                // add product name to cloud id lookup
                if (rows[i].EndsWith("\r"))
                {
                    rows[i] = rows[i].Substring(0, rows[i].Length - 1);
                }
                string[] cols = rows[i].Split(',');
                if (cols.Length > (int)ARGameList.CLOUD_PROJECT_ID)
                {
                    productNameToCloudProjectId[cols[(int)ARGameList.PRODUCT_NAME]] = cols[(int)ARGameList.CLOUD_PROJECT_ID];
                }
            }
        }
        catch (Exception)
        {
            singleGameProject = true;
        }

        foreach (KeyValuePair <string, string> entry in productNameToCloudProjectId)
        {
            // unhide resources folder of current game, hide resources folders of other games
            bool   currentGame = (Application.productName == entry.Key);
            string folderName  = Application.dataPath + "/ARGames/" + DeviceInput.NameToFolderName(entry.Key) + "/Resources";
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            if ((int)System.Environment.OSVersion.Platform == 4 || (int)System.Environment.OSVersion.Platform == 6)
            {
                process.StartInfo.FileName  = "chflags";
                process.StartInfo.Arguments = (currentGame ? "nohidden \"" : "hidden \"") + folderName + "\"";
            }
            else
            {
                process.StartInfo.FileName  = "attrib.exe";
                process.StartInfo.Arguments = (currentGame ? "-h \"" : "+h \"") + folderName.Replace('/', '\\') + "\"";
            }
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow  = true;
            process.Start();
            process.WaitForExit();
        }

        // force recompile when switching from a different game
        if (AssetDatabase.IsValidFolder("Assets/_DO NOT COMMIT RIGHT NOW - If Unity crashed, restart it now"))
        {
            AssetDatabase.DeleteAsset("Assets/_DO NOT COMMIT RIGHT NOW - If Unity crashed, restart it now");
            AssetDatabase.Refresh();

            foreach (string asset in AssetDatabase.FindAssets("t:Script"))
            {
                string path = AssetDatabase.GUIDToAssetPath(asset);
                if (path.StartsWith("Assets/") && path != "Assets/AREngine/Editor/Autorun.cs")
                {
                    AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
                }
            }
        }
        AssetDatabase.Refresh();

        CleanUp();
    }
예제 #23
0
 private void RightDeviceActive(SteamVR_TrackedObject obj)
 {
     DeviceActive(obj, rightIndex);
     RightHandInput = obj.GetComponent <DeviceInput>();
 }
예제 #24
0
        /// <summary>
        /// Starts input
        /// </summary>
        /// <param name="device">Device object</param>
        /// <param name="ProtocolClass">Class of device to operate with</param>
        /// <param name="DataType">Type of data to input</param>
        /// <param name="InputTask">Data processing task</param>
        /// <param name="ErrorMessage">Error</param>
        /// <returns>Returns true if device was succesfully started and stopped </returns>
        public static bool Launch(DeviceInput device,
                                  ProtocolClassID ProtocolClass,
                                  string PrefferedSerialNumber,
                                  InputDataType DataType,
                                  DeviceInputTask InputTask,
                                  ref string ErrorMessage)
        {
            if (Running == true)
            {
                return(false);
            }

            try
            {
                Running = true;
                if (device == null)
                {
                    ErrorMessage = "Device is null";
                    return(false);
                }


                #region Getting library versions
                //Getting HAL library Version information
                int Version = 0, Release = 0;
                device.GetHALVersion(ref Version, ref Release);
                Console.WriteLine("Mitsar.HAL version: {0}.{1}", Version, Release);
                Console.WriteLine();
                Console.WriteLine("Assemblies_____________");
                Console.WriteLine(GetAssemblyDescription("Mitsar.Essentials"));
                Console.WriteLine(GetAssemblyDescription("Mitsar.HAL"));
                Console.WriteLine();
                #endregion


                #region Getting available hardware and selecting device
                DeviceDescription SelectedDescription = null;

                //Detecting Hardware
                List <DeviceDescription> descriptions = new List <DeviceDescription>();

                Console.WriteLine("Enumerating devices for protocol " + ProtocolClass);
                device.Enumerate(HardwareClassID.EEG, ProtocolClass, ref descriptions);

                //Showing all discovered devices

                if (descriptions != null)
                {
                    Console.WriteLine("Devices found ______________");

                    foreach (DeviceDescription desc in descriptions)
                    {
                        Console.WriteLine(desc.ToString());
                        Console.WriteLine("Driver Name: " + desc.GetDeviceDriverName());
                        Console.WriteLine("Driver SerialNumber: " + desc.DriverSerialNumber);
                        Console.WriteLine("State: " + desc.State.ToString());
                        Console.WriteLine();
                    }
                }
                else
                {
                    ErrorMessage = "No devices found";
                    return(false);
                }

                Console.WriteLine("________________________");
                //Selecting device description
                if (descriptions.Count == 0)
                {
                    ErrorMessage = "Error: No devices found";
                    return(false);
                }
                else
                {
                    if (string.IsNullOrEmpty(PrefferedSerialNumber) == false)
                    {
                        Console.Write("Searching for device with serial number " + PrefferedSerialNumber + "...");

                        //Choosing EEG Device
                        foreach (DeviceDescription desc in descriptions)
                        {
                            if (desc.DriverSerialNumber == PrefferedSerialNumber)
                            {
                                SelectedDescription = desc;
                                break;
                            }
                        }

                        if (SelectedDescription != null)
                        {
                            Console.WriteLine(" found " + SelectedDescription.ToString());
                        }
                        else
                        {
                            Console.WriteLine(" not found");
                        }
                    }


                    if (SelectedDescription == null)
                    {
                        Console.Write("Searching for any device...");
                        //Choosing EEG Device
                        foreach (DeviceDescription desc in descriptions)
                        {
                            if (desc.HardwareClass == HardwareClassID.EEG)
                            {
                                SelectedDescription = desc;
                                break;
                            }
                        }

                        if (SelectedDescription != null)
                        {
                            Console.WriteLine(" found " + SelectedDescription.ToString());
                        }
                        else
                        {
                            Console.WriteLine(" not found");
                        }
                    }

                    if (SelectedDescription == null)
                    {
                        ErrorMessage = "Error: No devices found";
                        return(false);
                    }
                }
                #endregion


                #region Opening, Powering and detecting device version
                //Opening HAL
                Console.Write("Opening...");
                if (device.Open(SelectedDescription) == true)
                {
                    Console.WriteLine("OK");
                }
                else
                {
                    return(false);
                }


                //Powering HAL
                Console.Write("Powering...");
                if (device.PowerOn() == true)
                {
                    Console.WriteLine("OK");
                }
                else
                {
                    return(false);
                }


                //Identifying HAL
                Console.Write("Indentifing...");
                if (device.Identify() == true)
                {
                    Console.WriteLine("OK");
                }
                else
                {
                    return(false);
                }


                if (device.ActiveDeviceDescription.Resource.Version == 0)
                {
                    ErrorMessage = "Error: Unknown version " + device.ActiveDeviceDescription.Resource.ReservedVersion;
                    return(false);
                }

                Console.WriteLine();
                Console.WriteLine("Device vendor: " + device.ActiveDeviceDescription.Resource.Vendor);
                Console.WriteLine("Device version: " + device.ActiveDeviceDescription.Resource.Version);
                Console.WriteLine("Device serial number: " + device.ActiveDeviceDescription.Resource.SerialNumber);
                #endregion


                #region Loading and setting up calibration
                Console.Write("Getting calibration...");
                Resource_MultiChannel mresource       = device.ActiveDeviceDescription.Resource as Resource_MultiChannel;
                //If internal device calibration is supported
                if (mresource.IsROMSupported() == true)
                {//ROM supported - reading from ROM
                    byte[] buf = null;

                    //Reading calibration data from device's memory to buffer
                    if (device.ReadMemory(ref buf) == true)
                    {//if ROM read successfully - transfer to calibration
                        //Decoding buffer to calibtaion data
                        CalibrationProfileIOResult result = CalibrationProfile.ReadFromBuffer(ref device.ActiveDeviceDescription.Calibration, mresource, buf);
                        if (result == CalibrationProfileIOResult.OK) //Translate OK
                        {
                            //After successfull read version and serial must be assigned to CalibrationFile
                            device.ActiveDeviceDescription.Calibration.Parameters.Version          = device.ActiveDeviceDescription.Resource.Version;
                            device.ActiveDeviceDescription.Calibration.Parameters.FullSerialNumber = device.ActiveDeviceDescription.Resource.SerialNumber;
                            //Serial is not validated because received from already validated device resource
                            Console.WriteLine("OK");
                        }
                        else  //ROM translate or check sum error
                        {
                            device.ActiveDeviceDescription.Calibration.Clear();
                        }
                    }//ROM Access error
                    else
                    {
                        device.ActiveDeviceDescription.Calibration.Clear();
                    }
                }//if ROM supported
                else
                {
                    Console.WriteLine(" not supported");
                }

                Console.WriteLine("");
                //else calibration must be read from calibration file eeg.cal
                //CalibrationFile.Read(ref device.ActiveDeviceDescription.Calibration, "eeg.cal");
                #endregion


                #region Configuring device
                //Setting input mode to global input mode. EEG(data) or Impedance
                mresource.DataType = DataType;

                //Test signal mode disabled
                mresource.TestSignal = false;

                //Setting up referent operation mode
                //Getting list of supported referent types
                List <ReferentOperationMode> RefModeList = mresource.GetReferentOperationModeList(false);
                Console.Write("Supported referents: ");
                foreach (ReferentOperationMode refmode in RefModeList)
                {
                    Console.Write(refmode + " ");
                }
                Console.WriteLine();
                //Selecting first supported mode
                //mresource.EmitterFactory.RefMode = ReferentOperationMode.RefElectrode;
                //mresource.EmitterFactory.RefMode = ReferentOperationMode.Joined;
                //RefModeList[0];

                mresource.EmitterFactory.RefMode = RefModeList[0];

                mresource.EmitterFactory.ImpedanceChannelEnabled     = true;
                mresource.EmitterFactory.AccelerometerChannelEnabled = true;


                //Setting up sampling frequency
                //GEtting list of supported sampling frequencies
                List <double> FreqList                = mresource.GetSamplingFrequencyList(false);
                Console.Write("Supported frequencies: ");
                foreach (double freq in FreqList)
                {
                    Console.Write(freq + " ");
                }
                Console.WriteLine();

                //Selecting first frequency in list, generally nominal
                //int SamplingFrequency = (int)mresource.GetNominalSamplingFrequency();
                int SamplingFrequency = (int)FreqList[0];
                mresource.EmitterFactory.SamplingFrequency = SamplingFrequency;

                //Setting other data buffer parameters
                //Getting BYTES PER SAMPLE FROM FIRST ENCOUNTERED DATA CHANNEL
                mresource.DataBuffer.BytesPerTick = mresource.Interface_GetBytesPerSample(UID.NOP);

                mresource.DataBuffer.TicksMin  = 2;
                mresource.DataBuffer.TicksMax  = 100;
                mresource.DataBuffer.TicksSkip = 10;// 10;


                //Enable Front panel LED in Impedace Test mode
                mresource.FrontLedEnabled         = true;
                mresource.FrontLedThesholdEnabled = false;

                //Set edge value, can be changed in any time
                //All impedances above this value will be highligted
                //Only 5, 10, 20, 40 values are indicated
                mresource.FrontLedThesholdValue = 10;

                Console.WriteLine();
                #endregion


                #region Starting data input
                Console.Write("Starting...");
                if (device.Start() == true)
                {
                    Console.WriteLine("OK");
                }
                else
                {
                    return(false);
                }


                Console.WriteLine("Emitters__________________");
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("UID\tIndex\tAlign\tBPS\tHigh\tLow\tNotch\tUnitsPerSample");

                foreach (EmitterDescription emm in mresource.EmitterFactory)
                {
                    sb.Append(emm.UID.ToString());
                    sb.Append("\t");
                    sb.Append(emm.HardwareIndex.ToString());
                    sb.Append("\t");
                    sb.Append(emm.Align.ToString());
                    sb.Append("\t");
                    sb.Append(emm.BytesPerSample.ToString());
                    sb.Append("\t");
                    sb.Append(emm.HardHighPass.ToString());
                    sb.Append("\t");
                    sb.Append(emm.HardLowPass.ToString());
                    sb.Append("\t");
                    sb.Append(emm.HardNotch.ToString());
                    sb.Append("\t");
                    sb.Append(emm.UnitsPerSample.ToString());
                    sb.AppendLine("\t");
                }
                Console.WriteLine(sb.ToString());


                Console.WriteLine("Calibration_____________");
                //sb.Clear();
                foreach (EmitterDescription emm in mresource.EmitterFactory)
                {
                    sb.Append(emm.UID.ToString());
                    sb.Append("\t");

                    if (emm.CalEntryLink != null)
                    {
                        sb.Append(emm.CalEntryLink.ToString());
                        sb.Append("\t");
                    }
                    else
                    {
                        sb.Append(" no calibration");
                    }

                    sb.AppendLine("\t");
                }
                Console.WriteLine(sb.ToString());

                Console.WriteLine("Input parameters_____________");
                Console.WriteLine("Data Type: " + mresource.DataType.ToString());
                Console.WriteLine("Sampling Frequency: " + mresource.EmitterFactory.SamplingFrequency.ToString());

                Console.WriteLine("BytesPerTick: " + mresource.DataBuffer.BytesPerTick.ToString());
                Console.WriteLine("Minimum ticks to transmit: " + mresource.DataBuffer.TicksMin.ToString());
                Console.WriteLine("Maximum ticks to transmit: " + mresource.DataBuffer.TicksMax.ToString());

                Console.WriteLine("Internal number of channels: " + mresource.InputHardwareChannelCountInternal.ToString());
                Console.WriteLine("External number of channels: " + mresource.InputHardwareChannelCountExternal.ToString());
                Console.WriteLine();
                #endregion


                //Start Data asquisition task
                Console.WriteLine("Executing input task...");
                if (InputTask != null)
                {
                    InputTask();
                }


                bool DisplayImpedances = false;

                #region Displaying impedances
                if (DisplayImpedances)
                {
                    Console.WriteLine("----- EmitterFactory -----");
                    foreach (EmitterDescription em in mresource.EmitterFactory)
                    {
                        ///Console.WriteLine(em.UID + "\t RF=" + em.ImpedancePreliminaryValue + "\t R=" + em.ImpedanceResultValue);
                        Console.WriteLine(em.UID + "\t RValue=" + em.ImpedanceResultValue);//;;em.ImpedancePreliminaryValue + "\t R=" + em.ImpedanceResultValue);
                    }

                    Console.WriteLine("----- ImpedanceArray -----");
                    foreach (ImpedanceElement el in mresource.ImpedanceArray)
                    {
                        Console.WriteLine(el.LogicalUID +
                                          // " Name= " + el.Name +
                                          // " Active:" + el.Active +
                                          // " InMontage:" + el.PresentInMontage +
                                          //" REF:" + el.HardwareReferent +
                                          //  " LED:" + el.LedState + " (" + el.LedIndex + ")" +
                                          // " PVal:" + el.PreliminaryValue +
                                          "\t RValue:" + el.ResultValue);
                    }
                }
                #endregion


                #region Displaying power mode
                Console.WriteLine("Power mode: " + device.ActiveDeviceDescription.Resource.PowerMode);
                #endregion

                Console.WriteLine("Complete");
                return(true);
            }
            finally
            {
                //Memorizing error code
                HALErrorCode errorcode = device.HALError.Code;

                Running = false;

                #region Finalising device
                if (device != null)
                {
                    if (device.IsStarted)
                    {
                        Console.Write("Stopping...");
                        if (device.Stop() == true)
                        {
                            Console.WriteLine("OK");
                        }
                    }

                    if (device.IsPowered)
                    {
                        Console.Write("Powering off...");
                        if (device.PowerOff() == true)
                        {
                            Console.WriteLine("OK");
                        }
                    }

                    if (device.IsOpened)
                    {
                        Console.Write("Closing...");
                        if (device.Close() == true)
                        {
                            Console.WriteLine("OK");
                        }
                    }

                    if (errorcode != HALErrorCode.OK)
                    {
                        ErrorMessage = "Error: " + errorcode.ToString();
                    }
                }
                #endregion
            }
        }//Launch
예제 #25
0
 private static extern DVBError CDVBAVControl_SetADSwitch(IntPtr pData, DeviceInput input);
예제 #26
0
 public bool SaveModel(DeviceInput input)
 {
     // INoSqlDataAccess<Entity.DeviceInput> dataAccess = NoSqlBusinessModelFactory.CreateDeviceDataAccess();
     //dataAccess.Save(input);
     return(true);
 }
예제 #27
0
 private void LeftDeviceActive(SteamVR_TrackedObject obj)
 {
     DeviceActive(obj, leftIndex);
     LeftHandInput = obj.GetComponent <DeviceInput>();
 }
예제 #28
0
        public void Map(RetroPadMapping mapping)
        {
            if (mapping == null)
            {
                mapping = DefaultMapping;
            }
            ClearMappings();

            int percent = mapping.DeadZone;

            if (percent < 0)
            {
                _thumbDeadZone   = DEFAULT_THUMB_DEADZONE;
                _triggerDeadZone = DEFAULT_TRIGGER_DEADZONE;
            }
            else
            {
                short deadZone = percent < 100 ? (short)(short.MaxValue * 100 / percent) : short.MaxValue;
                _thumbDeadZone   = deadZone;
                _triggerDeadZone = deadZone;
            }

            foreach (var kvp in mapping.ButtonMappings)
            {
                DeviceInput deviceInput = kvp.Value;
                if (deviceInput.InputType == InputType.Button)
                {
                    GamepadButtonFlags button;
                    if (Enum.TryParse(deviceInput.Id, out button))
                    {
                        _buttonToButtonMappings[kvp.Key] = button;
                    }
                }
                else if (deviceInput.InputType == InputType.Axis)
                {
                    XInputAxisType analogInput;
                    if (Enum.TryParse(deviceInput.Id, out analogInput))
                    {
                        _analogToButtonMappings[kvp.Key] = new XInputAxis(analogInput, deviceInput.PositiveValues);
                    }
                }
            }

            foreach (var kvp in mapping.AnalogMappings)
            {
                DeviceInput deviceInput = kvp.Value;
                if (deviceInput.InputType == InputType.Button)
                {
                    GamepadButtonFlags button;
                    if (Enum.TryParse(deviceInput.Id, out button))
                    {
                        _buttonToAnalogMappings[kvp.Key] = button;
                    }
                }
                else if (deviceInput.InputType == InputType.Axis)
                {
                    XInputAxisType analogInput;
                    if (Enum.TryParse(deviceInput.Id, out analogInput))
                    {
                        _analogToAnalogMappings[kvp.Key] = new XInputAxis(analogInput, deviceInput.PositiveValues);
                    }
                }
            }
        }
예제 #29
0
    public void ButtonPress()
    {
        GameObject obj = EventSystem.current.currentSelectedGameObject;

        if (obj == null)
        {
            return;
        }
        string nextCard = obj.name;

        buttonCanvas.HideOverlay();
        try
        {
            TSVLookup tsv = new TSVLookup("Cards/" + cardName);
            foreach (string condition in tsv.Lookup(nextCard))
            {
                string flags = condition;
                if (condition.IndexOf('#') != -1)
                {
                    flags = condition.Substring(0, condition.IndexOf('#'));
                }

                if (gameState.EvaluateFlags(flags))
                {
                    string coords  = tsv.Lookup(nextCard, condition)[0];
                    string message = tsv.Lookup(nextCard, condition, coords)[0];

                    if (nextCard.Contains("%"))
                    {
                        // this card loads a level
                        gameState.SetFlag("Global%LeaveMapOption", int.Parse(message));
                        if (!gameState.GetFlag(nextCard + "%End"))
                        {
                            gameState.EncodeAnalyticsLeaveMap(int.Parse(message));
                        }
                        gameState.LoadARScene(nextCard);
                    }
                    else
                    {
                        // this card displays a dialogue and (potentially) resets to a module
                        message = message.Replace("\\n", "\n");
                        while (message.IndexOf('{') != -1)
                        {
                            int i = message.IndexOf('{');
                            int j = i + 1;
                            while (j < message.Length && message[j] != '}')
                            {
                                j++;
                            }
                            string variableName = message.Substring(i + 1, j - i - 1);
                            string variableValue;
                            if (variableName == "SERIAL")
                            {
                                variableValue = DeviceInput.HumanReadableEncoding(DeviceInput.deviceSerial);
                            }
                            else
                            {
                                variableValue = "" + gameState.GetFlagIntValue(variableName);
                            }
                            if (j != message.Length)
                            {
                                j++;
                            }
                            message = message.Substring(0, i) + variableValue + message.Substring(j);
                        }
                        buttonCanvas.ShowQuestionOverlay(
                            message,
                            nextCard[0] >= '0' && nextCard[0] <= '9' ? "Proceed" : "OK",
                            nextCard[0] >= '0' && nextCard[0] <= '9' ? "Don't Proceed" : null,
                            delegate(string pressedButton)
                        {
                            buttonCanvas.HideOverlay();
                            if (pressedButton == "Proceed")
                            {
                                gameState.AppendToAnalyticsString("_" + nextCard[0]);
                                gameState.ResetFlags(gameState.GetFlagsStartingWith("M"));
                                gameState.SetFlag("Global%Module", int.Parse(nextCard));
                                gameState.SetFlag("Global%ReplayModule", int.Parse(nextCard));
                                gameState.SetFlag("Global%GameEnd", true);
                            }
                            else
                            {
                                buttonCanvas.ShowCardOverlay(cardName, previousCardName);
                            }
                        }
                            );
                    }
                    return;
                }
            }
        }
        catch (NullReferenceException)
        {
        }
        catch (UnityException)
        {
        }

        if (nextCard == "Options")
        {
            buttonCanvas.ShowOptionsOverlay(delegate()
            {
                startTime = 0;
                buttonCanvas.ShowCardOverlay(cardName, previousCardName);
            });
        }
        else if (nextCard == "Exit")
        {
            buttonCanvas.ShowQuestionOverlay("Are you sure you want to exit?",
                                             "Exit game",
                                             "Continue playing",
                                             delegate(string pressedButton)
            {
                buttonCanvas.HideOverlay();
                if (pressedButton == "Exit game")
                {
                    DeviceInput.ExitGame(buttonCanvas);
                }
                else
                {
                    startTime = 0;
                    buttonCanvas.ShowCardOverlay(cardName, previousCardName);
                }
            });
        }
        else if (nextCard != "Close")
        {
            buttonCanvas.ShowCardOverlay(nextCard, cardName);
        }
    }
예제 #30
0
 private static extern DVBError CDVBAVControl_SetADSwitch( IntPtr pData, DeviceInput input );
예제 #31
0
    // Update is called once per frame
    public void UpdateTask()
    {
        float DeltaTime = Time.deltaTime;

        //m_Timer.Update(DeltaTime);
        DeviceInput.Update();
        Smoothed.SetTimeStep(DeltaTime);
        //ClearString();

        SOrientation AccMagOrientation = DeviceInput.AccMagOrientation;
        Quaternion   RotationChange    = DeviceInput.GetRotationChange(DeltaTime);

        SOrientation Orientation;

        if (DeviceInput.HasGyro)
        {
            m_SensorFusion.Update(AccMagOrientation, RotationChange, 0.9f);
        }
        m_SmoothedOrientation.Update(AccMagOrientation);

        if (m_UseSensorFusion)
        {
            Orientation = m_SensorFusion.Orientation;
        }
        else
        {
            Orientation = m_SmoothedOrientation.Orientation;
        }
        m_DebugText.PrintText(Orientation);
        m_DebugText.NewLine();
        float heading = Orientation.Yaw;
        float pitch   = Orientation.Pitch;
        float tilt    = Orientation.Roll;
        int   iFocus  = -1;

        for (int i = 0; i < 4; i++)
        {
            // TaskPanel
            float Dist = Panels[i].UpdateAngles(heading, pitch);
            if (!Panels[i].IsFinished())
            {
                if (m_Distance >= Dist && m_Distance >= Mathf.Abs(tilt))
                {
                    iFocus = i;
                    if (0.6f < Panels[i].GetFocusTime())
                    {
                        TakePicture(i);
                    }
                    else
                    {
                        Panels[i].SetStatus(TaskPanel.ETaskStatus.TS_Focus, m_FlashingFocus);
                    }
                }
                else
                {
                    Panels[i].SetStatus(TaskPanel.ETaskStatus.TS_Pending);
                }
            }
        }

        bool bAllFinished = IsAllFinished();

        if (bAllFinished)
        {
            m_bTakingPointPhoto = true;
        }


        if (m_bTakingPointPhoto)
        {
            m_CompassStrip.SetActive(false);
            m_ButtonTakePicture.SetActive(true);
        }
        else
        {
            m_CompassStrip.SetActive(true);
            m_ButtonTakePicture.SetActive(false);
        }



        if (bAllFinished || m_bTakingPointPhoto)
        {
            StatusText.text = m_StringTakePhoto;
        }
        else if (iFocus >= 0)
        {
            StatusText.text = m_StringHoldStill;//"Halten Sie das Handy kurz ruhig" ;
            if (iFocus >= 0 && m_SnapIfAccurate)
            {
                tilt = 0.0f;
                float SnappedHeading = Panels[iFocus].Heading;
                float SnappedPitch   = Panels[iFocus].Pitch;
                for (int i = 0; i < 4; i++)
                {
                    Panels[i].UpdateAngles(SnappedHeading, SnappedPitch);
                }
            }
        }
        else if (Mathf.Abs(tilt) > 20.0f)
        {
            StatusText.text = m_StringLandscape;//"Halte das Handy im Landschaftsmodus" ;
        }
        else
        {
            StatusText.text = m_StringFocus;//"Bringe die roten Quadrate in den Rahmen um Fotos nach Norden, Osten, Süden und Westen zu machen";
        }
        m_DebugText.PrintText("iFocus", iFocus);

        float RotZ = Div.getClamped(-2.0f * tilt, -35.0f, 35.0f);

        transform.localRotation = Quaternion.Euler(0.0f, 0.0f, RotZ);
    }