UnityでもRoslynで構文解析やコード評価したい

2020年7月

はじめに

RoslynはC#の構文解析やコード評価を行えるライブラリでC# 6以降のコンパイラでも使われています。Roslynを利用すると構文解析された結果を利用できるので文字列比較や正規表現と比べると解析漏れをなくせます。

RoslynのインストールはNuGetで使えますがUnityだと重複するdllがありそのままでは導入できません。それをUPMで簡単に導入する方法が分かったのでまとめてみました。

Unityでは以下のプロダクトでRoslynが使われています。

環境構築

Unity2018.3以上

  • Package Managerから Add package from git URL... できるバージョンでは com.unity.code-analysis を追加する
  • Package Managerから Add package from git URL... できないバージョンでは Packages/manifest.json"com.unity.code-analysis": "0.1.2-preview", を追加する

インストールできると以下のようにPackage Managerに追加されます。

image.png

インストールだけではDLLを参照できないのでRoslynを使いたいスクリプトフォルダにアセンブリ定義を作り、以下の設定を変更します。

  • 一般 > リファレンスをオーバーライドをチェック
  • アセンブリ参照に Microsoft.CodeAnalysis で始まるdllを追加
  • エディタ拡張で使うならプラットフォームの Editor のみをチェック、アプリ内で使うならデフォルトの 任意のプラットフォーム のままでOK

image.png

Roslynのサンプル

Scripting API SamplesGetting Started C# Syntax Analysisを参考にサンプルを実行してみます。それぞれcode欄に実行または解析するコード、result欄にその結果を表示しています。また実行できるUnityプロジェクトは https://github.com/shiena/UnityRoslynSample にありメニューの Tools > Roslyn Sample を選択するとウインドウが開きます。

Evaluate a C# expression

コードを実行します。

string code = "1 + 2";
var result = CSharpScript.EvaluateAsync(code);

image.png

Evaluate a C# expression (strongly-typed)

ジェネリクスで結果の型を指定してコードを実行します。

string code = "1 + 2";
var result = CSharpScript.EvaluateAsync<int>(code);

image.png

Parameterize a script

クラス定義したパラメータをコードに適用して実行します。

public class Globals
{
    public int X;
    public int Y;
}
string code = "X+Y";
var globals = new Globals {X = 1, Y = 2};
var result = CSharpScript.EvaluateAsync<int>(code, globals: globals);

image.png

Query Methods

コードを解析してMainメソッドの最初の引数を出力します。

string code =
            @"using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(""Hello, World!"");
        }
    }
}";
SyntaxTree tree = CSharpSyntaxTree.ParseText(code);
var root = (CompilationUnitSyntax) tree.GetRoot();
var firstMember = root.Members[0];
var helloWorldDeclaration = (NamespaceDeclarationSyntax) firstMember;
var programDeclaration = (ClassDeclarationSyntax) helloWorldDeclaration.Members[0];
var mainDeclaration = (MethodDeclarationSyntax) programDeclaration.Members[0];
var argsParameter = mainDeclaration.ParameterList.Parameters[0];
var firstParameters = from methodDeclaration in root.DescendantNodes()
                .OfType<MethodDeclarationSyntax>()
            where methodDeclaration.Identifier.ValueText == "Main"
            select methodDeclaration.ParameterList.Parameters.First();
var argsParameter2 = firstParameters.Single();

image.png

SyntaxWalkers

コードを解析してSystemまたはSystem.以外で始まるusingを出力します。

class UsingCollector : CSharpSyntaxWalker
{
    public readonly List<UsingDirectiveSyntax> Usings = new List<UsingDirectiveSyntax>();
    public override void VisitUsingDirective(UsingDirectiveSyntax node)
    {
        if (node.Name.ToString() != "System" &&
            !node.Name.ToString().StartsWith("System."))
        {
            this.Usings.Add(node);
        }
    }
}
string code =
            @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace TopLevel
{
    using Microsoft;
    using System.ComponentModel;
    namespace Child1
    {
        using Microsoft.Win32;
        using System.Runtime.InteropServices;
        class Foo { }
    }
    namespace Child2
    {
        using System.CodeDom;
        using Microsoft.CSharp;
        class Bar { }
    }
}";
SyntaxTree tree = CSharpSyntaxTree.ParseText(code);
var root = (CompilationUnitSyntax) tree.GetRoot();
var collector = new UsingCollector();
collector.Visit(root);

image.png

参考リンク

React Nativeのrun-androidはデバイスIDの有無で実行されるタスクが違う

2020年7月

はじめに

React Nativeのrun-androidコマンドはPCに接続したAndroid端末すべてにapkをインストールします。
一方で--deviceIdでデバイスIDを指定すると特定のAndroid端末だけにapkをインストールできます。
ですがデバイスID指定ありとなしでは実行されるGradleタスクに違いがあったので調べた結果をまとめました。

バージョン

  • @react-native-community/cli-platform-android: 4.9.0

実行されるタスクの調査方法

react-native コマンドの --verbose オプションを指定すると実行されるコマンドが分かるのでこれで確認します。

デバイスIDを指定しない場合

$ react-native run-android --verbose
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 1041 file(s) to forward-jetify. Using 8 workers...
info JS server already running.
info Installing the app...
debug Running command "cd android && gradlew.bat app:installDebug -PreactNativeDevServerPort=8081"

app:installDebugタスクが実行されています。これはアプリをビルドして全Android端末にapkをインストールします。

デバイスIDを指定する場合

$ react-native run-android --verbose --deviceId xxxxx
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 1391 file(s) to forward-jetify. Using 8 workers...
info JS server already running.
info Building the app...
debug Running command "gradlew.bat build -x lint"

buildタスクが実行されています。これはアプリのビルド、テスト、Javadocのビルドなどが実行されます。
更に--tasksオプションでタスクを指定しても反映されないのでビルド以外のタスクを除外できません。

apkビルドだけで特定の端末にインストールしたい

現状はオプションなどで変更できないので以下のどちらかしかなさそうです。

  • インストールしたくないAndroid端末の電源を切るかUSBケーブルを抜く
  • node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.jsbuildApk内の"build""assembleDebug"に書き換える

以下のPull Requestが取り込まれるとビルドコマンドが統一されてassembleDebugタスクに置き換わるので将来的には解消しそうです。

Gradleで任意のフォルダのプロジェクトを追加する

2020年7月

はじめに

React NativeのAndroidプロジェクトで変則的なフォルダ構成だったのでGradleでうまく扱う方法を紹介します。
サブフォルダや同じ階層のフォルダの場合はGradleでマルチプロジェクトで実現できます。

フォルダ構成

myapp/
  android/ ★rootプロジェクト
    build.gradle
    settings.gradle ★これを編集する
    app/ ★アプリプロジェクト
      build.gradle
library/
  android/ ★ライブラリプロジェクト
    build.gradle

設定

settings.gradle
include ':app'
// ここから追加
include ':library'
project(':library').projectDir = file('../../library/android')
// ここまで追加

参考サイト

Experiment of peer support and remote fitness system for cancer patients using VR technology

2020年7月

Kadinche Co., Ltd. (Headquarters: Shinagawa-ku, Tokyo; Representative Director: Soko Aoki), which develops space-time and human expansion technology, is a peer support and remote fitness system (commonly known as “VR cancer” for VR patients) that uses VR technology. In order to verify the effectiveness of “Peer Support”), we will start a demonstration experiment with the cooperation of Associate Professor Masahiko Sumitani, Director of Palliative Care Department, University of Tokyo Hospital.

About development of “VR cancer peer support”

“Peer support” is especially focused on cancer patients, where patients who experience the same illness in the medical field share worries and anxieties and support each other while sharing the wisdom and information to positively lead their lives thereafter. is spreading.
Normally, patients’ meetings and meetings by medical institutions were the main focus, but due to the recent spread of new coronavirus infections, it has become difficult to provide face-to-face opportunities, so opportunities on the Internet such as SNS and chat are increasing. I will.
However, in SNS and chat, the interaction between patients tends to be weaker than in the face-to-face type, and there are also voices who point out that they are unsatisfactory because it is not possible to conduct hands-on programs such as yoga and gymnastics.
Therefore, by making full use of VR technology, it is possible to develop a virtual space that allows you to experience athletics while allowing you to interact while maintaining anonymity while giving you the illusion that you are facing each other, even though you are participating remotely.

About “VR cancer peer support”system

You can see the introduction video of “VR Peer Support” below.

“VR cancer peer support” has two main functions.
1) Ability to interact with people who are remote (experience collaborators) through conversation and hand movements
2) Ability to perform fitness (upper limb movement) in a virtual space (3D CG)
Both functions can be executed in the same virtual space, so it is also possible to combine 1) and 2) to “exercise fitness while sharing conversations and hand movements”. In addition, the fitness is “daily change”, “stretch”, “boxer size”, “trunk”, etc. are prepared, and 3D CG space according to each fitness is prepared. The trainer’s model gymnastics displayed during fitness displayed the movements measured by motion tracking in 3D CG space.

Fitness training on the beach
Fitness training in the forest

Conducting verification tests for cancer patients

With the cooperation of Associate Professor Masahiko Sumitani, Director of Palliative Care Department, University of Tokyo Hospital, who has been supervised from the development stage, we will start a demonstration experiment at the University of Tokyo Hospital to verify its effectiveness. have become.
In carrying out the demonstration experiment, several cancer patients who were visiting the hospital were invited to participate, and participants were asked to lend an HMD (head-mounted display) to take home with them, and an exercise program prepared in a virtual space Participants are invited to participate in opportunities to interact with each other and to examine the changes from before the experiment.

Communication among the medical doctor & patients
Fitness Program

Future development

Based on the verification results of the verification test, we will further implement the functions that better meet the needs of patients and aim for practical use. We are also considering the application of this activity for cancer patients as a role model in the future in the preventive care field for other diseases, injuries, and seniors.
In addition to the above R&D, we are also focusing on the development of an “online self-fitness system” to promote the habit of exercising at home, centered on senior citizens. We will continue to make efforts to contribute to maintaining and improving the health of people in Japan.

Comment from Associate Professor Masahiko Sumitani, Director, Department of Palliative Care, University of Tokyo Hospital.

We would like to provide a solution in which patients can train by themselves.
Director, Department of Palliative Care, University of Tokyo Hospital
Associate Professor Masahiko Sumitani

In developed countries in Europe and America, including Japan, the number of patients suffering from cancer is increasing year by year, and one in two people in Japan experience cancer. Although medical treatment results for cancer have improved due to advances in medicine, various anxieties and troubles in daily life caused by having cancer may not be solved by only medical staff such as hospitals and clinics. .. In addition, patients who have been successfully treated for cancer often suffer from prolonged physical upset and anxiety.
As a specialist in palliative care and supportive care, we will be in charge of treating various problems that patients have, and in cooperation with cancer therapists, we can reasonably continue the optimal cancer treatment for each patient. I am treating with the goal of. We also provide therapeutic intervention for patients who have undergone cancer treatment.
In addition to such medical treatment at the medical field, peer support (counseling by cancer survivors), in which cancer patients support each other, helps patients with cancer that cannot be covered by medical care. Is spreading as a support for. Many peer support activities have become popular in Japan, but it’s still embarrassing to go to other patients, it is embarrassing to interact with other patients directly, I often listen to my voice.
Therefore, we have jointly developed VR (Virtual Reality) Cancer Peer Support that allows cancer patients to participate more in peer support activities. VR eliminates the physical distance traveled, allowing patients to participate in their favorite places. Also, by using an avatar (human model doll), there is no embarrassment when face-to-face, and lively communication is possible even indirectly.
In addition, the “Fitness” program we provide to cancer patients through VR Cancer Peer Support. It is known that exercise habits in daily life can reduce the risk of cancer development and recurrence, and reduce side effects associated with cancer treatment. I think it’s also true that “I don’t have it,” or “I started, but I was shaved for three days.” From the standpoint of a specialist in cancer palliative care and supportive care, I continue to have the desire to have cancer patients exercise every day, and I would like to realize that with VR cancer peer support. I am.
I hope that patients will be able to manage their own health so that they can live a healthy life while having cancer and after graduating from cancer.