Lingara Lingara ドキュメント 学習ガイド API ライブラリ アプリ 作成 埋め込み ウェブ版
言語: 日本語

Godot

このページは英語から翻訳されています。内容に相違がある場合は、英語のページが正しい内容です。 英語のページを読む

Godot には 2 つの言語があり、Lingara にはそれぞれ用のキットがあります。GDScript のゲームは Lingara アドオンを使います。Godot の C# のゲームは、Unity のゲームと同じパッケージである Lingara.Embed を使います。1 つのプロジェクトではどちらか一方を使い、両方を使うことはありません。以下のタブでそれぞれを示します。

インストール

GDScript. Godot Asset Library から Lingara アドオンをインストールし、Project Settings の Plugins で有効にします。有効にすると Lingara という名前のオートロードが追加され、すべてのシーンから /root/Lingara で参照できます。

C#. Lingara.Embed をパッケージ参照としてプロジェクトに追加します。以下のサンプルノード LingaraEmbedNode はパッケージには含まれていません。そのソースをプロジェクトに追加し、シーンに配置してください。

サーバーからトークンを取得する

どちらのキットもシークレットを保持しません。コアがトークンを必要とすると、あなた自身のサーバーに要求し、サーバーは サーバーキット でトークンを発行して、トークンとその有効期限を返します。

アドオンでは、Project Settings でサーバーのトークンルートを設定すると、Lingara が専用のスレッドでそれを呼び出します。ルートにプレイヤーのセッションが必要な場合は、プロジェクト設定はエクスポートに含まれて配布されるため、代わりに実行時に設定してください。あるいは token_needed に接続し、各要求に自分で応答します。C# では、クライアントがトークンを要求するたびに、サンプルノードがトークンルートに POST します。いずれの場合も、失敗は token_unavailable または TokenUnavailable で報告してください。そうすれば、待機中の呼び出しがただちに失敗します。

毎フレームイベントを処理する

コアはネットワーク I/O を専用のスレッドで実行します。アドオンのオートロードはフレームごとに 1 回それを空にし、イベントごとに 1 つのシグナルを発行するため、ゲームに必要なシグナルを接続するだけでよく、自分で何かを取り出す必要はありません。C# ノードは _process の中で、1 フレームあたり最大 256 イベントを取り出し、それぞれを Godot シグナルとして再発行します。

同じシグナルで、ストリーミングされる NPC の返答(NPC との会話 を参照)と練習の更新(練習の結果 を参照)も届きます。

<PackageReference Include="Lingara.Embed" Version="0.1.0-alpha.6" />
コード例の言語

Godot C#

// Your own server mints the token: never put a client secret in a game. The
// continuation may run off the main thread, which the client allows.
private async Task FetchToken()
{
    try
    {
        using var response = await Http.PostAsync(TokenUrl, new StringContent("{}"));
        response.EnsureSuccessStatusCode();
        using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
        Client?.ProvideToken(body.RootElement.GetProperty("token").GetString(), body.RootElement.GetProperty("expires_at").GetString());
    }
    catch (Exception e) when (e is HttpRequestException || e is JsonException || e is KeyNotFoundException)
    {
        Client?.TokenUnavailable(e.Message); // fail the waiting calls now
    }
}

GDScript

# The common case: set Project Settings > lingara/token_url to your server's
# token route, which answers exactly {"token", "expires_at"}. Lingara POSTs to
# it on its own thread whenever it needs a token. If the route needs the
# player's session, set it at run time instead (never in ProjectSettings,
# which ships inside the export):
func use_my_session(session_cookie: String) -> void:
	lingara.set_token_endpoint("https://game.example.com/lingara-token", {"cookie": session_cookie})


# Or answer each token_needed yourself, with whatever login your game has.
func _on_token_needed(_request: int, _reason: String) -> void:
	var http := HTTPRequest.new()
	add_child(http)
	http.request("https://game.example.com/lingara-token", [], HTTPClient.METHOD_POST, "{}")
	var reply: Array = await http.request_completed
	http.queue_free()
	var body: Variant = JSON.parse_string((reply[3] as PackedByteArray).get_string_from_utf8())
	if reply[1] == 200 and body is Dictionary:
		lingara.provide_token(body["token"], body["expires_at"])
	else:
		lingara.token_unavailable("the token route answered %d" % reply[1])
コード例の言語

Godot C#

public override void _Process(double delta)
{
    if (Client == null) return;
    events.Clear();
    Client.Drain(events); // at most 256 a frame; the rest wait for the next
    foreach (var e in events)
    {
        switch (e)
        {
            case EmbedEvent.TokenNeeded _: _ = FetchToken(); break;
            case EmbedEvent.NpcTurn { Update: NpcTurnUpdate.Fragment f } t:
                EmitSignal(SignalName.NpcTurnFragment, t.Dialogue.Value, t.Request.Value, f.Text); break;
            case EmbedEvent.NpcTurn { Update: NpcTurnUpdate.Finished f } t:
                EmitSignal(SignalName.NpcTurnFinished, t.Dialogue.Value, t.Request.Value, f.Text); break;
            case EmbedEvent.Practice p: EmitSignal(SignalName.PracticeChanged, p.Session.Value, p.Snapshot.Phase.ToString()); break;
            case EmbedEvent.Failed f: EmitSignal(SignalName.Failed, f.Error.KindName, f.Error.Message, f.Error.Request?.Value ?? 0); break;
            case EmbedEvent.Log log: GD.Print($"[lingara] {log.Level} {log.Target}: {log.Message}"); break;
        }
    }
}

GDScript

# The Lingara autoload the plugin adds, reached by path and typed, so every
# call and signal below is checked against LingaraEmbed.
@onready var lingara: LingaraEmbed = get_node("/root/Lingara")

# Enable the plugin (Project > Project Settings > Plugins): it adds the
# Lingara autoload, which drains the core once per frame and emits one signal
# per event. Connect the signals your game needs; you never call drain.
func _ready() -> void:
	lingara.token_needed.connect(_on_token_needed)
	lingara.event_received.connect(_on_event)
	lingara.error_raised.connect(func(error: Dictionary) -> void: push_warning(error.message))
	lingara.practice_changed.connect(_on_practice_changed)
	lingara.practice_finished.connect(_on_practice_finished)
	mei.replied.connect(_on_mei_replied)


func _on_event(_id: String, event_type: String, _created_at: String, data: Dictionary) -> void:
	if event_type == "lesson_plan.ready":
		print("a plan is ready: ", data.get("plan_id"))