Mentions légales du service

Skip to content
Snippets Groups Projects
Commit d16e9023 authored by MONSEIGNE Thibaut's avatar MONSEIGNE Thibaut
Browse files

:recycle: Refactoring

parent 7e365f79
No related branches found
No related tags found
No related merge requests found
Showing
with 2358 additions and 2478 deletions
using UnityEngine; using UnityEngine;
public class CubeRotation : MonoBehaviour { namespace LSL4Unity.Demos
{
public class CubeRotation : MonoBehaviour
{
private float _yawSpeed = 1.0f;
private float _pitchSpeed = 1.0f;
private float _rollSpeed = 1.0f;
private float yawSpeed = 1f; private void Update()
private float pitchSpeed = 1f; {
private float rollSpeed = 1f; if (Input.GetKey("a")) { _yawSpeed += 1; }
if (Input.GetKey("d") && _yawSpeed > 0) { _yawSpeed -= 1; }
void Update () { if (Input.GetKey("w")) { _pitchSpeed += 1; }
if (Input.GetKey("s") && _pitchSpeed > 0) { _pitchSpeed -= 1; }
if (Input.GetKey("a")) if (Input.GetKey("e")) { _rollSpeed += 1; }
yawSpeed += 1; if (Input.GetKey("q") && _rollSpeed > 0) { _rollSpeed -= 1; }
if (Input.GetKey("d") && yawSpeed > 0)
yawSpeed -= 1;
if (Input.GetKey("w")) transform.rotation *= Quaternion.Euler(_yawSpeed * Time.deltaTime, _pitchSpeed * Time.deltaTime, _rollSpeed * Time.deltaTime);
pitchSpeed += 1; }
if (Input.GetKey("s") && pitchSpeed > 0)
pitchSpeed -= 1;
if (Input.GetKey("e"))
rollSpeed += 1;
if (Input.GetKey("q") && rollSpeed > 0)
rollSpeed -= 1;
transform.rotation *= Quaternion.Euler(yawSpeed * Time.deltaTime, pitchSpeed * Time.deltaTime, rollSpeed * Time.deltaTime);
} }
} }
using UnityEngine; using LSL4Unity.Scripts;
using LSL; using UnityEngine;
using Assets.LSL4Unity.Scripts;
using Assets.LSL4Unity.Scripts.Common;
namespace Assets.LSL4Unity.Demo namespace LSL4Unity.Demos
{ {
/// <summary> /// <summary>
/// An reusable example of an outlet which provides the orientation of an entity to LSL /// An reusable example of an outlet which provides the orientation of an entity to LSL
/// </summary> /// </summary>
public class LSLTransformDemoOutlet : MonoBehaviour public class LSLTransformDemoOutlet : MonoBehaviour
{ {
private const string unique_source_id = "D256CFBDBA3145978CFA641403219531"; private const string UNIQUE_SOURCE_ID = "D256CFBDBA3145978CFA641403219531";
private liblsl.StreamOutlet outlet; private liblsl.StreamOutlet _outlet;
private liblsl.StreamInfo streamInfo; private liblsl.StreamInfo _streamInfo;
public liblsl.StreamInfo GetStreamInfo() public liblsl.StreamInfo GetStreamInfo() { return _streamInfo; }
{
return streamInfo; /// <summary> Use a array to reduce allocation costs. </summary>
} private float[] _currentSample;
/// <summary>
/// Use a array to reduce allocation costs private double _dataRate;
/// </summary>
private float[] currentSample; public double GetDataRate() { return _dataRate; }
public bool HasConsumer() { return _outlet != null && _outlet.have_consumers(); }
private double dataRate;
public string StreamName = "BeMoBI.Unity.Orientation.<Add_a_entity_id_here>";
public double GetDataRate() public string StreamType = "Unity.Quaternion";
{ public int ChannelCount = 4;
return dataRate;
} public MomentForSampling Sampling;
public bool HasConsumer() public Transform SampleSource;
{
if(outlet != null) private void Start()
return outlet.have_consumers(); {
// initialize the array once
return false; _currentSample = new float[ChannelCount];
}
_dataRate = LSLUtils.GetSamplingRateFor(Sampling);
public string StreamName = "BeMoBI.Unity.Orientation.<Add_a_entity_id_here>";
public string StreamType = "Unity.Quaternion"; _streamInfo = new liblsl.StreamInfo(StreamName, StreamType, ChannelCount, _dataRate, liblsl.channel_format_t.cf_float32, UNIQUE_SOURCE_ID);
public int ChannelCount = 4;
_outlet = new liblsl.StreamOutlet(_streamInfo);
public MomentForSampling sampling; }
public Transform sampleSource; private void PushSample()
{
void Start() if (_outlet == null) { return; }
{ var rotation = SampleSource.rotation;
// initialize the array once
currentSample = new float[ChannelCount]; // reuse the array for each sample to reduce allocation costs
_currentSample[0] = rotation.x;
dataRate = LSLUtils.GetSamplingRateFor(sampling); _currentSample[1] = rotation.y;
_currentSample[2] = rotation.z;
streamInfo = new liblsl.StreamInfo(StreamName, StreamType, ChannelCount, dataRate, liblsl.channel_format_t.cf_float32, unique_source_id); _currentSample[3] = rotation.w;
outlet = new liblsl.StreamOutlet(streamInfo); _outlet.push_sample(_currentSample, liblsl.local_clock());
} }
private void pushSample() private void FixedUpdate()
{ {
if (outlet == null) if (Sampling == MomentForSampling.FixedUpdate) { PushSample(); }
return; }
var rotation = sampleSource.rotation;
private void Update()
// reuse the array for each sample to reduce allocation costs {
currentSample[0] = rotation.x; if (Sampling == MomentForSampling.Update) { PushSample(); }
currentSample[1] = rotation.y; }
currentSample[2] = rotation.z;
currentSample[3] = rotation.w; private void LateUpdate()
{
outlet.push_sample(currentSample, liblsl.local_clock()); if (Sampling == MomentForSampling.LateUpdate) { PushSample(); }
} }
}
void FixedUpdate() }
{
if (sampling == MomentForSampling.FixedUpdate)
pushSample();
}
void Update()
{
if (sampling == MomentForSampling.Update)
pushSample();
}
void LateUpdate()
{
if (sampling == MomentForSampling.LateUpdate)
pushSample();
}
}
}
\ No newline at end of file
using UnityEngine; using System.Collections;
using System.Collections; using LSL4Unity.Scripts;
using UnityEngine;
using UnityEngine.Assertions; using UnityEngine.Assertions;
using System;
// Don't forget the Namespace import // Don't forget the Namespace import
using Assets.LSL4Unity.Scripts;
public class RandomMarker : MonoBehaviour { namespace LSL4Unity.Demos
{
public class RandomMarker : MonoBehaviour
{
public LSLMarkerStream MarkerStream;
public LSLMarkerStream markerStream; private void Start()
{
void Start () { Assert.IsNotNull(MarkerStream, "You forgot to assign the reference to a marker stream implementation!");
Assert.IsNotNull(markerStream, "You forgot to assign the reference to a marker stream implementation!"); if (MarkerStream != null) { StartCoroutine(WriteContinouslyMarkerEachSecond()); }
}
if (markerStream != null) private IEnumerator WriteContinouslyMarkerEachSecond()
StartCoroutine(WriteContinouslyMarkerEachSecond());
}
IEnumerator WriteContinouslyMarkerEachSecond()
{
while (true)
{ {
// an example for demonstrating the usage of marker stream while (true)
var currentMarker = GetARandomMarker(); {
markerStream.Write(currentMarker); // an example for demonstrating the usage of marker stream
yield return new WaitForSecondsRealtime(1f); var currentMarker = GetARandomMarker();
MarkerStream.Write(currentMarker);
yield return new WaitForSecondsRealtime(1f);
}
} }
}
private string GetARandomMarker() private static string GetARandomMarker() { return Random.value > 0.5 ? "A" : "B"; }
{
return UnityEngine.Random.value > 0.5 ? "A" : "B";
} }
} }
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
using System.Collections;
using Assets.LSL4Unity.Scripts;
namespace Assets.LSL4Unity.Demo namespace LSL4Unity.Demos
{ {
public class StreamInfo : MonoBehaviour public class StreamInfo : MonoBehaviour
{ {
public LSLTransformDemoOutlet outlet; public LSLTransformDemoOutlet Outlet;
public Text StreamNameLabel; public Text StreamNameLabel;
public Text StreamTypeLabel;
public Text StreamTypeLabel; public Text DataRate;
public Text HasConsumerLabel;
public Text DataRate;
// Use this for initialization
public Text HasConsumerLabel; private void Start()
{
// Use this for initialization StreamNameLabel.text = Outlet.StreamName;
void Start() StreamTypeLabel.text = Outlet.StreamType;
{ DataRate.text = $"Data Rate: {Outlet.GetDataRate()}";
StreamNameLabel.text = outlet.StreamName; HasConsumerLabel.text = "Has no consumers";
StreamTypeLabel.text = outlet.StreamType; }
DataRate.text = string.Format("Data Rate: {0}", outlet.GetDataRate());
HasConsumerLabel.text = "Has no consumers"; // Update is called once per frame
} private void Update()
{
// Update is called once per frame if (Outlet.HasConsumer())
void Update() {
{ HasConsumerLabel.text = "Has consumers";
if (outlet.HasConsumer()) { HasConsumerLabel.color = Color.green;
HasConsumerLabel.text = "Has consumers"; }
HasConsumerLabel.color = Color.green; else
} {
else { HasConsumerLabel.text = "No Consumers";
HasConsumerLabel.color = Color.black;
HasConsumerLabel.text = "No Consumers"; }
HasConsumerLabel.color = Color.black; }
} }
} }
}
}
\ No newline at end of file
using UnityEngine; using System;
using UnityEditor.Callbacks;
using UnityEditor;
using System.IO; using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
namespace Assets.LSL4Unity.EditorExtensions namespace LSL4Unity.Editor
{ {
public class BuildHooks
public class BuildHooks { {
private const string LIB_LSL_NAME = "liblsl";
const string LIB_LSL_NAME = "liblsl"; private const string PLUGIN_DIR = "Plugins";
const string PLUGIN_DIR = "Plugins";
[PostProcessBuildAttribute(1)]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
var buildName = Path.GetFileNameWithoutExtension(pathToBuiltProject);
var buildHostDirectory = pathToBuiltProject.Replace(Path.GetFileName(pathToBuiltProject), ""); [PostProcessBuild(1)]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
var buildName = Path.GetFileNameWithoutExtension(pathToBuiltProject);
var dataDirectoryName = buildName + "_Data"; var buildHostDirectory = pathToBuiltProject.Replace(Path.GetFileName(pathToBuiltProject), "");
var pathToDataDirectory = Path.Combine(buildHostDirectory, dataDirectoryName); var dataDirectoryName = buildName + "_Data";
var pluginDirectory = Path.Combine(pathToDataDirectory, PLUGIN_DIR); var pathToDataDirectory = Path.Combine(buildHostDirectory, dataDirectoryName);
if (target == BuildTarget.StandaloneWindows) var pluginDirectory = Path.Combine(pathToDataDirectory, PLUGIN_DIR);
{
RenameLibFile(pluginDirectory, LSLEditorIntegration.lib32Name, LSLEditorIntegration.lib64Name, LSLEditorIntegration.DLL_ENDING);
}
else if(target == BuildTarget.StandaloneWindows64)
{
RenameLibFile(pluginDirectory, LSLEditorIntegration.lib64Name, LSLEditorIntegration.lib32Name, LSLEditorIntegration.DLL_ENDING);
}
if (target == BuildTarget.StandaloneLinux) switch (target)
{ {
RenameLibFile(pluginDirectory, LSLEditorIntegration.lib32Name, LSLEditorIntegration.lib64Name, LSLEditorIntegration.SO_ENDING); case BuildTarget.StandaloneWindows:
} RenameLibFile(pluginDirectory, LSLEditorIntegration.LIB32_NAME, LSLEditorIntegration.LIB64_NAME, LSLEditorIntegration.DLL_ENDING);
else if (target == BuildTarget.StandaloneLinux64) break;
{ case BuildTarget.StandaloneWindows64:
RenameLibFile(pluginDirectory, LSLEditorIntegration.lib64Name, LSLEditorIntegration.lib32Name, LSLEditorIntegration.SO_ENDING); RenameLibFile(pluginDirectory, LSLEditorIntegration.LIB64_NAME, LSLEditorIntegration.LIB32_NAME, LSLEditorIntegration.DLL_ENDING);
} break;
case BuildTarget.StandaloneLinux64:
RenameLibFile(pluginDirectory, LSLEditorIntegration.LIB64_NAME, LSLEditorIntegration.LIB32_NAME, LSLEditorIntegration.SO_ENDING);
break;
case BuildTarget.StandaloneOSX:
RenameLibFile(pluginDirectory, LSLEditorIntegration.LIB64_NAME, LSLEditorIntegration.LIB32_NAME, LSLEditorIntegration.BUNDLE_ENDING);
break;
}
}
if (target == BuildTarget.StandaloneOSXIntel) private static void RenameLibFile(string pluginDirectory, string sourceName, string nameOfObsoleteFile, string fileEnding)
{ {
RenameLibFile(pluginDirectory, LSLEditorIntegration.lib32Name, LSLEditorIntegration.lib64Name, LSLEditorIntegration.BUNDLE_ENDING); var obsoleteFile = Path.Combine(pluginDirectory, nameOfObsoleteFile + fileEnding);
}
else if (target == BuildTarget.StandaloneOSXIntel64)
{
RenameLibFile(pluginDirectory, LSLEditorIntegration.lib64Name, LSLEditorIntegration.lib32Name, LSLEditorIntegration.BUNDLE_ENDING);
}
}
private static void RenameLibFile(string pluginDirectory , string sourceName, string nameOfObsoleteFile, string fileEnding) Debug.Log("[LSL BUILD Hook] Delete obsolete file: " + obsoleteFile);
{
var obsoleteFile = Path.Combine(pluginDirectory, nameOfObsoleteFile + fileEnding);
Debug.Log("[LSL BUILD Hook] Delete obsolete file: " + obsoleteFile); File.Delete(obsoleteFile);
File.Delete(obsoleteFile); var sourceFile = Path.Combine(pluginDirectory, sourceName + fileEnding);
var sourceFile = Path.Combine(pluginDirectory, sourceName + fileEnding); var targetFile = Path.Combine(pluginDirectory, LIB_LSL_NAME + fileEnding);
var targetFile = Path.Combine(pluginDirectory, LIB_LSL_NAME + fileEnding); Debug.Log($"[LSL BUILD Hook] Renaming: {sourceFile} to {targetFile}");
Debug.Log(string.Format("[LSL BUILD Hook] Renaming: {0} to {1}", sourceFile, targetFile));
File.Move(sourceFile, targetFile); File.Move(sourceFile, targetFile);
} }
} }
} }
\ No newline at end of file
using UnityEngine; using System.IO;
using UnityEditor;
using System.IO;
using System.Linq; using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.Assertions; using UnityEngine.Assertions;
namespace Assets.LSL4Unity.EditorExtensions namespace LSL4Unity.Editor
{ {
public class LSLEditorIntegration public class LSLEditorIntegration
{ {
public static readonly string wikiURL = "https://github.com/xfleckx/LSL4Unity/wiki"; public const string LIB64_NAME = "liblsl64";
public static readonly string lib64Name = "liblsl64"; public const string LIB32_NAME = "liblsl32";
public static readonly string lib32Name = "liblsl32"; public const string DLL_ENDING = ".dll";
public const string SO_ENDING = ".so";
public const string DLL_ENDING = ".dll"; public const string BUNDLE_ENDING = ".bundle";
public const string SO_ENDING = ".so";
public const string BUNDLE_ENDING = ".bundle"; private const string WIKI_URL = "https://github.com/xfleckx/LSL4Unity/wiki";
private const string WRAPPER_FILENAME = "LSL.cs";
static readonly string wrapperFileName = "LSL.cs"; private const string ASSET_SUB_FOLDER = "LSL4Unity";
static readonly string assetSubFolder = "LSL4Unity"; private const string LIB_FOLDER = "Plugins";
static readonly string libFolder = "Plugins";
[MenuItem("LSL/Show Streams")]
[MenuItem("LSL/Show Streams")] private static void OpenLSLWindow()
static void OpenLSLWindow() {
{ var window = EditorWindow.GetWindow<LSLShowStreamsWindow>(true);
var window = EditorWindow.GetWindow<LSLShowStreamsWindow>(true); window.Init();
window.ShowUtility();
window.Init(); }
window.ShowUtility(); [MenuItem("LSL/Show Streams", true)]
} private static bool ValidateOpenLSLWindow()
{
[MenuItem("LSL/Show Streams", true)] string assetDirectory = Application.dataPath;
static bool ValidateOpenLSLWindow()
{ var results = Directory.GetDirectories(assetDirectory, ASSET_SUB_FOLDER, SearchOption.AllDirectories);
string assetDirectory = Application.dataPath;
Assert.IsTrue(results.Any(),
bool lib64Available = false; "Expecting a directory named: '" + ASSET_SUB_FOLDER + "' containing the content inlcuding this script! Did you renamed it?");
bool lib32Available = false;
bool apiAvailable = false; var root = results.Single();
bool lib32Available = File.Exists(Path.Combine(root, Path.Combine(LIB_FOLDER, LIB32_NAME + DLL_ENDING)));
var results = Directory.GetDirectories(assetDirectory, assetSubFolder, SearchOption.AllDirectories); bool lib64Available = File.Exists(Path.Combine(root, Path.Combine(LIB_FOLDER, LIB64_NAME + DLL_ENDING)));
Assert.IsTrue(results.Any(), "Expecting a directory named: '" + assetSubFolder + "' containing the content inlcuding this script! Did you renamed it?"); lib32Available &= File.Exists(Path.Combine(root, Path.Combine(LIB_FOLDER, LIB32_NAME + SO_ENDING)));
lib64Available &= File.Exists(Path.Combine(root, Path.Combine(LIB_FOLDER, LIB64_NAME + SO_ENDING)));
var root = results.Single(); lib32Available &= File.Exists(Path.Combine(root, Path.Combine(LIB_FOLDER, LIB32_NAME + BUNDLE_ENDING)));
lib64Available &= File.Exists(Path.Combine(root, Path.Combine(LIB_FOLDER, LIB64_NAME + BUNDLE_ENDING)));
lib32Available = File.Exists(Path.Combine(root, Path.Combine(libFolder, lib32Name + DLL_ENDING)));
lib64Available = File.Exists(Path.Combine(root, Path.Combine(libFolder, lib64Name + DLL_ENDING))); bool apiAvailable = File.Exists(Path.Combine(root, WRAPPER_FILENAME));
lib32Available &= File.Exists(Path.Combine(root, Path.Combine(libFolder, lib32Name + SO_ENDING))); if ((lib64Available || lib32Available) && apiAvailable) { return true; }
lib64Available &= File.Exists(Path.Combine(root, Path.Combine(libFolder, lib64Name + SO_ENDING)));
Debug.LogError("LabStreamingLayer libraries not available! See " + WIKI_URL + " for installation instructions");
lib32Available &= File.Exists(Path.Combine(root, Path.Combine(libFolder, lib32Name + BUNDLE_ENDING))); return false;
lib64Available &= File.Exists(Path.Combine(root, Path.Combine(libFolder, lib64Name + BUNDLE_ENDING))); }
}
apiAvailable = File.Exists(Path.Combine(root, wrapperFileName)); }
if ((lib64Available || lib32Available) && apiAvailable)
return true;
Debug.LogError("LabStreamingLayer libraries not available! See " + wikiURL + " for installation instructions");
return false;
}
}
}
\ No newline at end of file
using UnityEngine; using System.Collections.Generic;
using UnityEditor; using UnityEditor;
using LSL; using UnityEngine;
using System.Collections.Generic;
namespace Assets.LSL4Unity.EditorExtensions namespace LSL4Unity.Editor
{ {
public class LSLShowStreamsWindow : EditorWindow public class LSLShowStreamsWindow : EditorWindow
{ {
public double WaitOnResolveStreams = 2; //public double WaitOnResolveStreams = 2;
private const string noStreamsFound = "No streams found!"; private const string NO_STREAMS_FOUND = "No streams found!";
private const string clickLookUpFirst = "Click lookup first"; private const string N_STREAMS_FOUND = " Streams found";
private const string nStreamsFound = " Streams found";
//private const string CLICK_LOOK_UP_FIRST = "Click lookup first";
private List<string> listNamesOfStreams = new List<string>();
private readonly List<string> _listNamesOfStreams = new List<string>();
private Vector2 scrollVector;
private string streamLookUpResult; private Vector2 _scrollVector;
private string _streamLookUpResult;
private liblsl.ContinuousResolver resolver;
private string lslVersionInfos; private liblsl.ContinuousResolver _resolver;
private string _lslVersionInfos;
public void Init()
{ public void Init()
resolver = new liblsl.ContinuousResolver(); {
_resolver = new liblsl.ContinuousResolver();
var libVersion = liblsl.library_version();
var protocolVersion = liblsl.protocol_version(); var libVersion = liblsl.library_version();
var protocolVersion = liblsl.protocol_version();
var lib_major = libVersion / 100;
var lib_minor = libVersion % 100; var libMajor = libVersion / 100;
var prot_major = protocolVersion / 100; var libMinor = libVersion % 100;
var prot_minor = protocolVersion % 100; var protMajor = protocolVersion / 100;
var protMinor = protocolVersion % 100;
lslVersionInfos = string.Format("You are using LSL library: {0}.{1} implementing protocol version: {2}.{3}", lib_major, lib_minor, prot_major, prot_minor);
_lslVersionInfos = $"You are using LSL library: {libMajor}.{libMinor} implementing protocol version: {protMajor}.{protMinor}";
this.titleContent = new GUIContent("LSL Utility");
} titleContent = new GUIContent("LSL Utility");
}
liblsl.StreamInfo[] streamInfos = null;
private liblsl.StreamInfo[] _streamInfos = null;
void OnGUI()
{ private void OnGUI()
if (resolver == null) {
Init(); if (_resolver == null) { Init(); }
UpdateStreams(); UpdateStreams();
EditorGUILayout.BeginVertical(); EditorGUILayout.BeginVertical();
EditorGUILayout.Space();
EditorGUILayout.Space(); EditorGUILayout.LabelField(_lslVersionInfos, EditorStyles.miniLabel);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(lslVersionInfos, EditorStyles.miniLabel); EditorGUILayout.LabelField(_streamLookUpResult, EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal(); EditorGUILayout.Space();
EditorGUILayout.Separator();
EditorGUILayout.LabelField(streamLookUpResult, EditorStyles.boldLabel);
_scrollVector = EditorGUILayout.BeginScrollView(_scrollVector, GUILayout.Width(EditorGUIUtility.currentViewWidth));
EditorGUILayout.EndHorizontal(); GUILayoutOption fieldWidth = GUILayout.Width(EditorGUIUtility.currentViewWidth / 4.3f);
EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal();
EditorGUILayout.Separator(); EditorGUILayout.Space();
EditorGUILayout.LabelField("Name", EditorStyles.boldLabel, fieldWidth);
scrollVector = EditorGUILayout.BeginScrollView(scrollVector, GUILayout.Width(EditorGUIUtility.currentViewWidth)); EditorGUILayout.LabelField("Type", EditorStyles.boldLabel, fieldWidth);
GUILayoutOption fieldWidth = GUILayout.Width(EditorGUIUtility.currentViewWidth / 4.3f); EditorGUILayout.LabelField("HostName", EditorStyles.boldLabel, fieldWidth);
EditorGUILayout.LabelField("Data Rate", EditorStyles.boldLabel, fieldWidth);
EditorGUILayout.BeginHorizontal(); EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.LabelField("Name", EditorStyles.boldLabel, fieldWidth); foreach (var item in _listNamesOfStreams)
EditorGUILayout.LabelField("Type", EditorStyles.boldLabel, fieldWidth); {
EditorGUILayout.LabelField("HostName", EditorStyles.boldLabel, fieldWidth); string[] s = item.Split(' ');
EditorGUILayout.LabelField("Data Rate", EditorStyles.boldLabel, fieldWidth);
EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(new GUIContent(s[0], s[0]), fieldWidth);
foreach (var item in listNamesOfStreams) EditorGUILayout.LabelField(new GUIContent(s[1], s[1]), fieldWidth);
{ EditorGUILayout.LabelField(new GUIContent(s[2], s[2]), fieldWidth);
string[] s = item.Split(' '); EditorGUILayout.LabelField(new GUIContent(s[3], s[3]), fieldWidth);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal(); }
EditorGUILayout.EndScrollView();
EditorGUILayout.LabelField(new GUIContent(s[0], s[0]), fieldWidth); EditorGUILayout.EndVertical();
EditorGUILayout.LabelField(new GUIContent(s[1], s[1]), fieldWidth); }
EditorGUILayout.LabelField(new GUIContent(s[2], s[2]), fieldWidth);
EditorGUILayout.LabelField(new GUIContent(s[3], s[3]), fieldWidth); private void UpdateStreams()
{
_listNamesOfStreams.Clear();
EditorGUILayout.EndHorizontal(); _streamInfos = _resolver.Results();
} if (_streamInfos.Length == 0) { _streamLookUpResult = NO_STREAMS_FOUND; }
EditorGUILayout.EndScrollView(); else
EditorGUILayout.EndVertical(); {
foreach (var item in _streamInfos) { _listNamesOfStreams.Add($"{item.Name()} {item.Type()} {item.Hostname()} {item.nominal_srate()}"); }
} _streamLookUpResult = _listNamesOfStreams.Count + N_STREAMS_FOUND;
}
private void UpdateStreams() }
{ }
listNamesOfStreams.Clear(); }
streamInfos = resolver.results();
if (streamInfos.Length == 0)
{
streamLookUpResult = noStreamsFound;
}
else
{
foreach (var item in streamInfos)
{
listNamesOfStreams.Add(string.Format("{0} {1} {2} {3}", item.name(), item.type(), item.hostname(), item.nominal_srate()));
}
streamLookUpResult = listNamesOfStreams.Count + nStreamsFound;
}
}
}
}
\ No newline at end of file
using UnityEngine; using System;
using LSL4Unity.Scripts;
using UnityEditor; using UnityEditor;
using System;
namespace Assets.LSL4Unity.EditorExtensions namespace LSL4Unity.Editor
{ {
[InitializeOnLoad] [InitializeOnLoad]
class ScriptOrderManagement internal class ScriptOrderManagement
{ {
static ScriptOrderManagement() static ScriptOrderManagement()
{ {
foreach (MonoScript monoScript in MonoImporter.GetAllRuntimeMonoScripts()) foreach (MonoScript monoScript in MonoImporter.GetAllRuntimeMonoScripts())
{ {
if (monoScript.GetClass() != null) if (monoScript.GetClass() != null)
{ {
foreach (var a in Attribute.GetCustomAttributes(monoScript.GetClass(), typeof(ScriptOrder))) foreach (var a in Attribute.GetCustomAttributes(monoScript.GetClass(), typeof(ScriptOrder)))
{ {
var currentOrder = MonoImporter.GetExecutionOrder(monoScript); var currentOrder = MonoImporter.GetExecutionOrder(monoScript);
var newOrder = ((ScriptOrder)a).order; var newOrder = ((ScriptOrder) a).Order;
if (currentOrder != newOrder) if (currentOrder != newOrder) { MonoImporter.SetExecutionOrder(monoScript, newOrder); }
MonoImporter.SetExecutionOrder(monoScript, newOrder); }
} }
} }
} }
} }
}
} }
using UnityEngine; using LSL4Unity.Scripts;
using UnityEditor; using UnityEditor;
using System.Collections;
using Assets.LSL4Unity.Scripts;
namespace LSL4Unity.Editor
namespace Assets.LSL4Unity.EditorExtensions
{ {
[CustomEditor(typeof(LSLTimeSync))] [CustomEditor(typeof(LSLTimeSync))]
public class TimeSyncEditor : Editor public class TimeSyncEditor : UnityEditor.Editor
{ {
public override void OnInspectorGUI() //public override void OnInspectorGUI() { base.OnInspectorGUI(); } // redundant
{ }
base.OnInspectorGUI();
}
}
} }
This diff is collapsed.
This diff is collapsed.
using LSL; using System;
using System;
using System.Linq; using System.Linq;
using LSL4Unity.Scripts.OV;
using UnityEngine; using UnityEngine;
using UnityEngine.Events;
namespace Assets.LSL4Unity.Scripts.AbstractInlets namespace LSL4Unity.Scripts
{ {
public abstract class ABaseInlet : MonoBehaviour public abstract class ABaseInlet : MonoBehaviour
{ {
public string StreamName; public string StreamName;
public string StreamType;
public string StreamType;
protected liblsl.StreamInlet Inlet;
protected liblsl.StreamInlet inlet;
protected int ExpectedChannels;
protected int expectedChannels;
protected Resolver Resolver;
protected Resolver resolver;
/// <summary> Call this method when your inlet implementation got created at runtime. </summary>
/// <summary> protected virtual void RegisterAndLookUpStream()
/// Call this method when your inlet implementation got created at runtime {
/// </summary> Resolver = FindObjectOfType<Resolver>();
protected virtual void registerAndLookUpStream()
{ //Resolver.OnStreamFound.AddListener(new UnityAction<LSLStreamInfoWrapper>(AStreamIsFound)); // Redundant to explicit delegate creation
resolver = FindObjectOfType<Resolver>(); //Resolver.OnStreamLost.AddListener(new UnityAction<LSLStreamInfoWrapper>(AStreamGotLost)); // Redundant to explicit delegate creation
Resolver.OnStreamFound.AddListener(AStreamIsFound);
resolver.onStreamFound.AddListener(new UnityAction<LSLStreamInfoWrapper>(AStreamIsFound)); Resolver.OnStreamLost.AddListener(AStreamGotLost);
resolver.onStreamLost.AddListener(new UnityAction<LSLStreamInfoWrapper>(AStreamGotLost)); if (Resolver.KnownStreams.Any(IsTheExpected))
{
if (resolver.knownStreams.Any(isTheExpected)) var stream = Resolver.KnownStreams.First(IsTheExpected);
{ AStreamIsFound(stream);
var stream = resolver.knownStreams.First(isTheExpected); }
AStreamIsFound(stream); }
}
} /// <summary> Callback method for the Resolver gets called each time the resolver found a stream. </summary>
/// <param name="stream"></param>
/// <summary> public virtual void AStreamIsFound(LSLStreamInfoWrapper stream)
/// Callback method for the Resolver gets called each time the resolver found a stream {
/// </summary> if (!IsTheExpected(stream)) { return; }
/// <param name="stream"></param>
public virtual void AStreamIsFound(LSLStreamInfoWrapper stream) Debug.Log($"LSL Stream {stream.Name} found for {name}");
{
if (!isTheExpected(stream)) Inlet = new liblsl.StreamInlet(stream.Item);
return; ExpectedChannels = stream.ChannelCount;
Debug.Log(string.Format("LSL Stream {0} found for {1}", stream.Name, name)); OnStreamAvailable();
}
inlet = new LSL.liblsl.StreamInlet(stream.Item);
expectedChannels = stream.ChannelCount; /// <summary>
/// Callback method for the Resolver gets called each time the resolver misses a stream within its cache
OnStreamAvailable(); /// </summary>
} /// <param name="stream"></param>
public virtual void AStreamGotLost(LSLStreamInfoWrapper stream)
/// <summary> {
/// Callback method for the Resolver gets called each time the resolver misses a stream within its cache if (!IsTheExpected(stream)) { return; }
/// </summary>
/// <param name="stream"></param> Debug.Log($"LSL Stream {stream.Name} Lost for {name}");
public virtual void AStreamGotLost(LSLStreamInfoWrapper stream)
{ OnStreamLost();
if (!isTheExpected(stream)) }
return;
protected virtual bool IsTheExpected(LSLStreamInfoWrapper stream)
Debug.Log(string.Format("LSL Stream {0} Lost for {1}", stream.Name, name)); {
bool predicate = StreamName.Equals(stream.Name);
OnStreamLost(); predicate &= StreamType.Equals(stream.Type);
}
return predicate;
protected virtual bool isTheExpected(LSLStreamInfoWrapper stream) }
{
bool predicate = StreamName.Equals(stream.Name); protected abstract void PullSamples();
predicate &= StreamType.Equals(stream.Type);
protected virtual void OnStreamAvailable()
return predicate; {
} // base implementation may not decide what happens when the stream gets available
throw new NotImplementedException("Please override this method in a derived class!");
protected abstract void pullSamples(); }
protected virtual void OnStreamAvailable() protected virtual void OnStreamLost()
{ {
// base implementation may not decide what happens when the stream gets available // base implementation may not decide what happens when the stream gets lost
throw new NotImplementedException("Please override this method in a derived class!"); throw new NotImplementedException("Please override this method in a derived class!");
} }
}
protected virtual void OnStreamLost()
{ public abstract class InletFloatSamples : ABaseInlet
// base implementation may not decide what happens when the stream gets lost {
throw new NotImplementedException("Please override this method in a derived class!"); protected abstract void Process(float[] sample, double time);
}
} protected float[] Sample;
public abstract class InletFloatSamples : ABaseInlet protected override void PullSamples()
{ {
protected abstract void Process(float[] newSample, double timeStamp); Sample = new float[ExpectedChannels];
protected float[] sample; try
{
protected override void pullSamples() double time = Inlet.pull_sample(Sample, 0.0f);
{
sample = new float[expectedChannels]; if (Math.Abs(time) > Constants.TOLERANCE)
{
try // do not miss the first one found
{ Process(Sample, time);
double lastTimeStamp = inlet.pull_sample(sample, 0.0f); // pull as long samples are available
while (Math.Abs(time = Inlet.pull_sample(Sample, 0.0f)) > Constants.TOLERANCE) { Process(Sample, time); }
if (lastTimeStamp != 0.0) }
{ }
// do not miss the first one found catch (ArgumentException aex)
Process(sample, lastTimeStamp); {
// pull as long samples are available Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this);
while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) enabled = false;
{ Debug.LogException(aex, this);
Process(sample, lastTimeStamp); }
} }
}
}
} public abstract class InletDoubleSamples : ABaseInlet
catch (ArgumentException aex) {
{ protected abstract void Process(double[] sample, double time);
Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this);
this.enabled = false; protected double[] Sample;
Debug.LogException(aex, this);
} protected override void PullSamples()
{
} Sample = new double[ExpectedChannels];
}
try
public abstract class InletDoubleSamples : ABaseInlet {
{ double lastTimeStamp = Inlet.pull_sample(Sample, 0.0f);
protected abstract void Process(double[] newSample, double timeStamp);
if (Math.Abs(lastTimeStamp) > Constants.TOLERANCE)
protected double[] sample; {
// do not miss the first one found
protected override void pullSamples() Process(Sample, lastTimeStamp);
{ // pull as long samples are available
sample = new double[expectedChannels]; while (Math.Abs(lastTimeStamp = Inlet.pull_sample(Sample, 0.0f)) > Constants.TOLERANCE) { Process(Sample, lastTimeStamp); }
}
try }
{ catch (ArgumentException aex)
double lastTimeStamp = inlet.pull_sample(sample, 0.0f); {
Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this);
if (lastTimeStamp != 0.0) enabled = false;
{ Debug.LogException(aex, this);
// do not miss the first one found }
Process(sample, lastTimeStamp); }
// pull as long samples are available }
while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0)
{ public abstract class InletIntSamples : ABaseInlet
Process(sample, lastTimeStamp); {
} protected abstract void Process(int[] sample, double time);
} protected int[] Sample;
}
catch (ArgumentException aex) protected override void PullSamples()
{ {
Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); Sample = new int[ExpectedChannels];
this.enabled = false;
Debug.LogException(aex, this); try
} {
double lastTimeStamp = Inlet.pull_sample(Sample, 0.0f);
}
} if (Math.Abs(lastTimeStamp) > Constants.TOLERANCE)
{
public abstract class InletIntSamples : ABaseInlet // do not miss the first one found
{ Process(Sample, lastTimeStamp);
protected abstract void Process(int[] newSample, double timeStamp); // pull as long samples are available
while (Math.Abs(lastTimeStamp = Inlet.pull_sample(Sample, 0.0f)) > Constants.TOLERANCE) { Process(Sample, lastTimeStamp); }
protected int[] sample; }
}
protected override void pullSamples() catch (ArgumentException aex)
{ {
sample = new int[expectedChannels]; Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this);
enabled = false;
try Debug.LogException(aex, this);
{ }
double lastTimeStamp = inlet.pull_sample(sample, 0.0f); }
}
if (lastTimeStamp != 0.0)
{ public abstract class InletCharSamples : ABaseInlet
// do not miss the first one found {
Process(sample, lastTimeStamp); protected abstract void Process(char[] sample, double time);
// pull as long samples are available
while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) protected char[] Sample;
{
Process(sample, lastTimeStamp); protected override void PullSamples()
} {
Sample = new char[ExpectedChannels];
}
} try
catch (ArgumentException aex) {
{ double lastTimeStamp = Inlet.pull_sample(Sample, 0.0f);
Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this);
this.enabled = false; if (Math.Abs(lastTimeStamp) > Constants.TOLERANCE)
Debug.LogException(aex, this); {
} // do not miss the first one found
Process(Sample, lastTimeStamp);
} // pull as long samples are available
} while (Math.Abs(lastTimeStamp = Inlet.pull_sample(Sample, 0.0f)) > Constants.TOLERANCE) { Process(Sample, lastTimeStamp); }
}
public abstract class InletCharSamples : ABaseInlet }
{ catch (ArgumentException aex)
protected abstract void Process(char[] newSample, double timeStamp); {
Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this);
protected char[] sample; enabled = false;
Debug.LogException(aex, this);
protected override void pullSamples() }
{ }
sample = new char[expectedChannels]; }
try public abstract class InletStringSamples : ABaseInlet
{ {
double lastTimeStamp = inlet.pull_sample(sample, 0.0f); protected abstract void Process(string[] sample, double time);
if (lastTimeStamp != 0.0) protected string[] Sample;
{
// do not miss the first one found protected override void PullSamples()
Process(sample, lastTimeStamp); {
// pull as long samples are available Sample = new string[ExpectedChannels];
while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0)
{ try
Process(sample, lastTimeStamp); {
} double lastTimeStamp = Inlet.pull_sample(Sample, 0.0f);
} if (Math.Abs(lastTimeStamp) > Constants.TOLERANCE)
} {
catch (ArgumentException aex) // do not miss the first one found
{ Process(Sample, lastTimeStamp);
Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); // pull as long samples are available
this.enabled = false; while (Math.Abs(lastTimeStamp = Inlet.pull_sample(Sample, 0.0f)) > Constants.TOLERANCE) { Process(Sample, lastTimeStamp); }
Debug.LogException(aex, this); }
} }
catch (ArgumentException aex)
} {
} Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this);
enabled = false;
public abstract class InletStringSamples : ABaseInlet Debug.LogException(aex, this);
{ }
protected abstract void Process(String[] newSample, double timeStamp); }
}
protected String[] sample;
public abstract class InletShortSamples : ABaseInlet
protected override void pullSamples() {
{ protected abstract void Process(short[] sample, double time);
sample = new String[expectedChannels];
protected short[] Sample;
try
{ protected override void PullSamples()
double lastTimeStamp = inlet.pull_sample(sample, 0.0f); {
Sample = new short[ExpectedChannels];
if (lastTimeStamp != 0.0)
{ try
// do not miss the first one found {
Process(sample, lastTimeStamp); double lastTimeStamp = Inlet.pull_sample(Sample, 0.0f);
// pull as long samples are available
while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0) if (Math.Abs(lastTimeStamp) > Constants.TOLERANCE)
{ {
Process(sample, lastTimeStamp); // do not miss the first one found
} Process(Sample, lastTimeStamp);
// pull as long samples are available
} while (Math.Abs(lastTimeStamp = Inlet.pull_sample(Sample, 0.0f)) > Constants.TOLERANCE) { Process(Sample, lastTimeStamp); }
} }
catch (ArgumentException aex) }
{ catch (ArgumentException aex)
Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this); {
this.enabled = false; Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this);
Debug.LogException(aex, this); enabled = false;
} Debug.LogException(aex, this);
}
} }
} }
public abstract class InletShortSamples : ABaseInlet
{
protected abstract void Process(short[] newSample, double timeStamp);
protected short[] sample;
protected override void pullSamples()
{
sample = new short[expectedChannels];
try
{
double lastTimeStamp = inlet.pull_sample(sample, 0.0f);
if (lastTimeStamp != 0.0)
{
// do not miss the first one found
Process(sample, lastTimeStamp);
// pull as long samples are available
while ((lastTimeStamp = inlet.pull_sample(sample, 0.0f)) != 0)
{
Process(sample, lastTimeStamp);
}
}
}
catch (ArgumentException aex)
{
Debug.LogError("An Error on pulling samples deactivating LSL inlet on...", this);
this.enabled = false;
Debug.LogException(aex, this);
}
}
}
} }
This diff is collapsed.
using UnityEngine; using UnityEngine;
using System;
using System.Linq;
using Assets.LSL4Unity.Scripts.AbstractInlets;
namespace Assets.LSL4Unity.Scripts.Examples namespace LSL4Unity.Scripts.Examples
{ {
/// <summary> /// <summary> Just an example implementation for a Inlet recieving float values. </summary>
/// Just an example implementation for a Inlet recieving float values public class ExampleFloatInlet : AFloatInlet
/// </summary> {
public class ExampleFloatInlet : AFloatInlet public float[] LastSample;
{
public string lastSample = String.Empty;
protected override void Process(float[] newSample, double timeStamp) protected override void Process(float[] sample, double time)
{ {
// just as an example, make a string out of all channel values of this sample LastSample = sample;
lastSample = string.Join(" ", newSample.Select(c => c.ToString()).ToArray()); Debug.Log($"Got {sample.Length} samples at {time}");
}
Debug.Log( }
string.Format("Got {0} samples at {1}", newSample.Length, timeStamp) }
);
}
}
}
\ No newline at end of file
fileFormatVersion: 2 fileFormatVersion: 2
guid: 1da38a6a9335e8e48af8b17d9c369265 guid: b6836ca493a8afc49b837bb81e426b67
MonoImporter: MonoImporter:
serializedVersion: 2 serializedVersion: 2
defaultReferences: [] defaultReferences: []
......
using Assets.LSL4Unity.Scripts.AbstractInlets; using UnityEngine;
using UnityEngine;
public class ScaleMapping : AFloatInlet namespace LSL4Unity.Scripts.Examples
{ {
public Transform targetTransform; public class ScaleMapping : AFloatInlet
{
public Transform TargetTransform;
public bool useX ; public bool UseX, UseY, UseZ;
public bool useY ;
public bool useZ ;
protected override void Process(float[] newSample, double timeStamp) protected override void Process(float[] sample, double time)
{ {
//Assuming that a sample contains at least 3 values for x,y,z //Assuming that a sample contains at least 3 values for x,y,z
float x = useX ? newSample[0] : 1; float x = UseX ? sample[0] : 1;
float y = useY ? newSample[1] : 1; float y = UseY ? sample[1] : 1;
float z = useZ ? newSample[2] : 1; float z = UseZ ? sample[2] : 1;
// we map the data to the scale factors
var targetScale = new Vector3(x, y, z);
// apply the rotation to the target transform // we map the data to the scale factors
targetTransform.localScale = targetScale; var targetScale = new Vector3(x, y, z);
}
// apply the rotation to the target transform
TargetTransform.localScale = targetScale;
}
}
} }
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment