[UE5.3.2][Retarget]IK RetargeterでのT_PoseのキャラクターをAポーズベースのモーションへのリターゲット方法

UE5.3.2 Retarget IK RetargeterでのT_Poseのキャラクターのリターゲット方法

MannyのモーションをT_Poseのキャラクターにリターゲットする方法

Showing Reterget Poseモードにして>Sourceタブを選択して>Create>Import from Animation Sequence を選択

デフォルトで用意されている.AnimSequenceの
/Game/Characters/Mannequins/Animations/Manny/MM_T_Poseを読み込む

反映されればMannyがTposeになる。

Showing Reterget Poseモードボタンを押してRunning Retargetモードにすると

TposeのキャラがAposeになる。

[maya]スキンウェイトを部分的に頂点を選択してコピーしたい。

スキンウェイトを部分的に頂点を選択してコピーしたい。

1 つの頂点からウェイトをコピーする
1 つの頂点を選択し、そのウェイト値を選択したその他の頂点にコピーすることができます。ウェイト値をペーストする頂点は、同じメッシュ上にあっても別のメッシュ上にあっても構いません。

スキン ポイントのウェイト値をコピーしてペーストするには

スキン ウェイト ペイント ツール(Paint Skin Weights Tool)で、選択(Select)またはペイント選択(Paint Select)モードに切り替えます。

ウェイト値をコピーする頂点を選択し、コピー ツール アイコン をクリックします。ウェイト

値をペーストする頂点を選択し、ペースト ツール アイコン をクリックします。コピーしたウェイト値が選択したすべての頂点にペーストされます。

注:
メッシュから別のメッシュにウェイト値をペーストする場合、ソースの頂点に対応するウェイト値のインフルエンスがターゲット メッシュに見つからない場合はエラーが表示されます。

次のホットキーを使用して、頂点から頂点にウェイト値をコピーしてペーストすることもできます。

(Windows) [Alt]+[Ctrl]+[C]、[Alt]+[Ctrl]+[V]
(Mac OS X) [Option]+[Control]+[C]、[Option]+[Control]+[V]


スキンウェイトを部分的に頂点を選択してコピーしたい。がうまくいかない。

// エラー: file: C:/Program Files/Autodesk/Maya2022/scripts/others/artAttrSkinWeightCopy.mel line 22: 選択した項目が多すぎます。ウェイトをコピーする頂点を 1 つだけ選択してください。 //

C:/Program Files/Autodesk/Maya2022/scripts/others/artAttrSkinWeightPaste.mel

1回コピーさせてペーストするのをループさせればできる?

と思って作ったが、いらなくなったコードサンプル 参考にしかならないけど乗せておく。

global proc artAttrSkinWeightCopy_One()
{
    global string $gSkinWeightCopyInfluences[];
    global float $gSkinWeightCopyWeights[];
    
    string $sel[] = `ls -sl -flatten`;
    if(size($sel) < 1) {
        error("選択した項目がありません。ウェイトをコピーする頂点を 1 つだけ選択してください。");		
		return;
    }
    
    if(size($sel) > 1) {
        error("選択した項目が多すぎます。ウェイトをコピーする頂点を 1 つだけ選択してください。");
		return;
    }
    
    string $skinCluster = findSkinClusterFromSelectedComponent($sel[0]);
    if($skinCluster == "")
        return;
    $gSkinWeightCopyInfluences = `skinCluster -q -influence $skinCluster`;
    $gSkinWeightCopyWeights = `skinPercent -q -v $skinCluster`;
            
    
}
global proc artAttrSkinWeightCopy_multiSelect_test()
{
    global string $gSkinWeightCopyInfluences[];
    global float $gSkinWeightCopyWeights[];
    
    string $sel[] = `ls -sl -flatten`;
    if(size($sel) < 1) {
        error("選択した項目がありません。ウェイトをコピーする頂点を 1 つ以上だけ選択してください。");		
		return;
    }
    
    if(size($sel) > 1) {
        error("選択した項目が多すぎます。ウェイトをコピーする頂点を 1 つだけ選択してください。");
		return;
    }
    
    string $skinCluster = findSkinClusterFromSelectedComponent($sel[0]);
    if($skinCluster == "")
        return;
    $gSkinWeightCopyInfluences = `skinCluster -q -influence $skinCluster`;
    print("$gSkinWeightCopyInfluences--------------\n");
    print($gSkinWeightCopyInfluences);
    print("\n--------------\n");
    $gSkinWeightCopyWeights = `skinPercent -q -v $skinCluster`;
    print("$gSkinWeightCopyWeights--------------\n");
    $gSkinWeightCopyWeights_Str=floatArrayToString($gSkinWeightCopyWeights, ",");
    print("$gSkinWeightCopyWeights_Str= "+$gSkinWeightCopyWeights_Str);
    print("\n--------------\n");
}
global proc artAttrSkinWeightCopy_multiSelect2()
{
    $OldSelectVtx = `ls -sl`;
    print("$OldSelectVtx");
    $OldSelectVtx_Str = stringArrayToString($OldSelectVtx, ",");
    print("$OldSelectVtx_Str= "+$OldSelectVtx_Str+"\n");
    
    //UIで選択しておく
    $BaseMesh = "|Mesh|Arm_Only5";
    $PastMesh = "|Mesh|Jacket_For_ShortSkirtUV";
    select($BaseMesh);
    string $selectBaseVtx[] = `polyInfo -nonManifoldVertices`; 
    //string $selectBaseVtx[] = `ls -sl -flatten`; 
    select($PastMesh);
    string $selectPastVtx[] = `polyInfo -nonManifoldVertices`; 
    //string $selectPastVtx[] = `ls -sl -flatten`; 
    
    //選択した頂点を再選択
    select($OldSelectVtx);
    
    $selectBaseVtx_len = `size($selectBaseVtx)`;
    $selectBaseVtx_Str = stringArrayToString($selectBaseVtx, ",");
    print("$selectBaseVtx_Str= "+$selectBaseVtx_Str+"\n");
    print("$selectBaseVtx_len= "+$selectBaseVtx_len+"\n");
    
    for($i = 0; $i < $selectBaseVtx_len; $i++)
    {
	    select($selectBaseVtx[$i]);
	    print("$selectBaseVtx["+$i+"] \n");
	    //artAttrSkinWeightCopy;
	    select($selectPastVtx[$i]);
	    print("$selectPastVtx["+$i+"] \n");
	    //artAttrSkinWeightPaste;
    }
    
    select($OldSelectVtx);
}
artAttrSkinWeightCopy_multiSelect2();

参考URL
https://help.autodesk.com/view/MAYACRE/JPN/?guid=GUID-7D895BB0-1522-4388-96E0-4245127F90AB

[php] [chat]シンプルなIPアドレスファイル名ルームでのチャットを作った。

お客様のチャット

<!-- chat.php -->

<?php
function trace($txt){
    //print($txt);
    $a="a";
}
class RoomLog
{
    
    public $LOG_FILE_NAME;
    public $name;
    public $SPLIT_Str;
    public $message;
    public function get_ip_file_name(){
        global $_SERVER;
        $ip_Address=$_SERVER['REMOTE_ADDR'];
        print("ip_Address= " . $ip_Address . "<br>");
        if($ip_Address=="::1"){
            $ip_Address="192.168.1.29";
            print("テストのためip変数上書きしました。ip_Address= " . $ip_Address . "<br>");
        }
        $ip_Address_Arr = explode(".", $ip_Address);
        $ip_file_name = join('_', $ip_Address_Arr);
        $ip_file_name = "log/ip_" . $ip_file_name . "_chatlog.txt";
        print("ip_file_name= " . $ip_file_name . "<br>");
        return $ip_file_name;
    }
    public function initLog(){
        trace("■ initLog()<br>");
        global $LOG_FILE_NAME;
        global $name;
        global $SPLIT_Str;
        global $message;
        
        $ip_file_name=$this->get_ip_file_name();
        
        // データを書き込むファイルの名前
        //$LOG_FILE_NAME = "chat_class_txt_log.txt";
        $LOG_FILE_NAME = $ip_file_name;
     
        // 区切りのための文字列
        $SPLIT_Str = "|-|";
     
        // 名前を格納する変数
        $name = "お客様";
        // メッセージを格納する変数
        $message = "";
        
        $this->LOG_FILE_NAME=$LOG_FILE_NAME;
        $this->name=$name;
        $this->SPLIT_Str=$SPLIT_Str;
        $this->message=$message;
        /*
        trace("<br>");
        trace("this->LOG_FILE_NAME= " . $this->LOG_FILE_NAME . "<br>");
        trace("this->name= " . $this->name . "<br>");
        trace("this->SPLIT_Str= " . $this->SPLIT_Str . "<br>");
        trace("this->message= " . $this->message . "<br>");
        */
    }
    
    public function startMain(){
        trace("■ startMain()<br>");
        $this->initLog();
        $this->CheckFormPostData();
        $this->LogShow();
    }
    

    public function CheckFormPostData(){
        trace("■ CheckFormPostData()<br>");
        global $_POST;
        
        $name = $this->name;
        $SPLIT_Str = $this->SPLIT_Str;
        $message = $this->message;
        
        
        // 送信されたデータ
        $_POST_string = join(', ', $_POST);
        trace("_POST_string2= " . $_POST_string . "<br>");
        
        if (empty($_POST)) {
            trace("The form is empty.");
        } else {
            trace("Form data is present.");
        }
        
        // 送信された名前とメッセージを変数に代入
        if (isset($_POST['name'])) {
          $name = $_POST['name'];
     
          if (strpos($name, $SPLIT_Str) !== false) {
            // 名前に区切り文字が含まれている場合の処理
            echo "使用できない文字列「|-|」が含まれています。";
            return;
          }
     
          if ($name == "") {
            $name = "お客様";
          }
        }
        if (isset($_POST['message'])) {
          $message = $_POST['message'];
     
          if (strpos($message, $SPLIT_Str) !== false) {
            // メッセージに区切り文字が含まれている場合の処理
            echo "使用できない文字列「|-|」が含まれています。";
            return;
          }
     
          //$this->LOG_FILE_NAME=$LOG_FILE_NAME;
          $this->name=$name;
          //$this->SPLIT_Str=$SPLIT_Str;
          $this->message=$message;
          $this->LogWrite();
        }
    }
   
    
    public function LogWrite(){
      trace("■ LogWrite()<br>");
      $LOG_FILE_NAME = $this->LOG_FILE_NAME;
      $name = $this->name;
      $SPLIT_Str = $this->SPLIT_Str;
      $message = $this->message;
        
      //書き込みモードでファイルを開く
      $fp = fopen($LOG_FILE_NAME, "a") or exit($LOG_FILE_NAME . "が開けません");
 
      // | を区切り文字として2つのデータを繋げて書き込む
      fwrite($fp, $name . $SPLIT_Str . $message . "\n");
      
      
      // リダイレクトのためのHTTPヘッダーを送信
      //header("Location: " . $_SERVER['PHP_SELF'], true, 303);
      
      fclose($fp);
    }

    function LogShow(){
        trace("■ LogShow()<br>");
        //global $LOG_FILE_NAME;
        global $linesNum;
        global $lines;
        $LOG_FILE_NAME = $this->LOG_FILE_NAME;
        //$name = $this->name;
        //$SPLIT_Str = $this->SPLIT_Str;
        //$message = $this->message;
        
        if (!file_exists($LOG_FILE_NAME)) {
          // ファイルがない場合
          echo "書き込みはありません。";
     
          $linesNum = 0;
        } else {
     
          // ファイルの全行を読み取る
          $lines = file($LOG_FILE_NAME);
     
          // 読み込んだ行数
          $linesNum = count($lines);
        }
    }
    
}

$RoomLog_ins = new RoomLog();
$RoomLog_ins->startMain();

?>
 
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>1行メッセージ</title>
</head>
 
<body>
 
<h1>お問い合わせ内容</h1>
 
  <section>
    <?php
 
      // 一行ずつ表示する処理
      for ($i = 0; $i < $linesNum; $i++) {
 
         // 区切り文字でデータを区切って配列に格納
         $array = explode($SPLIT_Str, $lines[$i]);
 
         // 区切り文字の前の部分は名前
         $name = htmlspecialchars($array[0]);
         
         
         // 区切り文字の後の部分はメッセージ
         
         $array_length = count($array);
         if ($array_length == 2) {
           $message = htmlspecialchars($array[1]);
         }
         // 名前とメッセージを表示
         echo '<p>' . $name . "「" . str_replace(PHP_EOL, "", $message) . '」</p>';
      }
    ?>
  </section>


  
 
  <form method="post" action="chat_class_txt.php">
    <div>
      <!--<b>おなまえ</b>-->
      <!--<input name="name" type="text" size="20" maxlength="10">-->
      <input name="name" type="hidden" size="20" maxlength="10">
    </div>
    <div>
      <!--<b>ご入力</b>-->
      <input name="message" type="text" size="50" maxlength="50" required>
      <button name="submit" type="submit">送信</button>
    </div>
    
  </form>
  
</body>
</html>

担当者のチャット画面

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>1行メッセージ</title>
</head>
 
<body>
<!-- chat.php -->

<style>
.base {
  display: flex;
  flex-direction: row;
  width: 100vw;
  height: 90vh;
}
.class1 {
  width: 10%;
}
 
.class2 {
  display: flex;
  flex-direction: column;
  width: 90%;
}

</style>
<style>
  div {
    text-align: center;
    /* background-color: #aaaaaa; 16進数のカラーコードを使用する例 */
  }
  button{
      font-size: 200%;
      width:100px;
      height:100px;
  }
</style>
  <div class="base">
    <div class="class1">

<?php
//$dir = "log";
//$files = scandir($dir);
$files = glob("log/*");
$counter=0;
foreach ($files as $file) {
    //echo("<h2>" . $file . "</h2><br>");
    $url='log_frame.php';
    //echo('<a href="'.$url.'"><h1><div >' . $counter . '</div></h1></a><br>');
    
    $htmlStr='';
    $htmlStr=$htmlStr.'<form method="post" action="chat_class_txt_admin.php">';
    $htmlStr=$htmlStr.'<input type="hidden" name="LOG_FILE_NAME" value="' . $file . '">';
    $htmlStr=$htmlStr.'<button name="submit" type="submit">' . $counter . '</button>';
    $htmlStr=$htmlStr.'</form>';
    echo($htmlStr);

    $counter=$counter+1;
}

?>
      
</div>
<div class="class2">
<?php
function trace($txt){
    //print($txt);
    $a="a";
}
class RoomLog
{
    
    public $LOG_FILE_NAME;
    public $LOG_FILE_NAME_Opened;
    public $name;
    public $SPLIT_Str;
    public $message;
    public function get_ip_file_name(){
        global $_SERVER;
        $ip_Address=$_SERVER['REMOTE_ADDR'];
        trace("ip_Address= " . $ip_Address . "<br>");
        if($ip_Address=="::1"){
            $ip_Address="192.168.1.29";
            trace("テストのためip変数上書きしました。ip_Address= " . $ip_Address . "<br>");
        }
        $ip_Address_Arr = explode(".", $ip_Address);
        $ip_file_name = join('_', $ip_Address_Arr);
        $ip_file_name = "log/ip_" . $ip_file_name . "_chatlog.txt";
        trace("ip_file_name= " . $ip_file_name . "<br>");
        return $ip_file_name;
    }
    
    public function CheckFormPostData_Admin(){
        trace("■ CheckFormPostData_Admin()<br>");
        global $_POST;
        
        // 送信されたデータ
        $_POST_string = join(', ', $_POST);
        trace("_POST_string1= " . $_POST_string . "<br>");
        
        if (empty($_POST)) {
            trace("The form is empty.<br>");
        } else {
            trace("Form data is OK present.<br>");
        }
        if (isset($_POST['LOG_FILE_NAME'])) {
          $LOG_FILE_NAME = $_POST['LOG_FILE_NAME'];
          $this->LOG_FILE_NAME=$LOG_FILE_NAME;
          print("LOG_FILE_NAME= " . $LOG_FILE_NAME . "<br>");
        }
        /*
        // 送信された名前とメッセージを変数に代入
        if (isset($_POST['name'])) {
          $name = $_POST['name'];
     
          if (strpos($name, $SPLIT_Str) !== false) {
            // 名前に区切り文字が含まれている場合の処理
            echo "使用できない文字列「|-|」が含まれています。";
            return;
          }
     
          if ($name == "") {
            $name = "お客様";
          }
        }
        if (isset($_POST['message'])) {
          $message = $_POST['message'];
     
          if (strpos($message, $SPLIT_Str) !== false) {
            // メッセージに区切り文字が含まれている場合の処理
            echo "使用できない文字列「|-|」が含まれています。";
            return;
          }
     
          //$this->LOG_FILE_NAME=$LOG_FILE_NAME;
          $this->name=$name;
          //$this->SPLIT_Str=$SPLIT_Str;
          $this->message=$message;
          $this->LogWrite();
        }
        */
        return $LOG_FILE_NAME;
    }

    public function initLog(){
        trace("■ initLog()<br>");
        global $LOG_FILE_NAME;
        global $name;
        global $SPLIT_Str;
        global $message;
        
        $ip_file_name=$this->CheckFormPostData_Admin();
        
        // データを書き込むファイルの名前
        //$LOG_FILE_NAME = "chat_class_txt_log.txt";
        $LOG_FILE_NAME = $ip_file_name;
     
        // 区切りのための文字列
        $SPLIT_Str = "|-|";
     
        // 名前を格納する変数
        $name = "担当者";
        // メッセージを格納する変数
        $message = "";
        
        $this->LOG_FILE_NAME=$LOG_FILE_NAME;
        $this->name=$name;
        $this->SPLIT_Str=$SPLIT_Str;
        $this->message=$message;
        /*
        trace("<br>");
        trace("this->LOG_FILE_NAME= " . $this->LOG_FILE_NAME . "<br>");
        trace("this->name= " . $this->name . "<br>");
        trace("this->SPLIT_Str= " . $this->SPLIT_Str . "<br>");
        trace("this->message= " . $this->message . "<br>");
        */
    }
    
    public function startMain(){
        trace("■ startMain()<br>");
        $this->initLog();
        $this->CheckFormPostData();
        $this->LogShow();
    }
    

    public function CheckFormPostData(){
        trace("■ CheckFormPostData()<br>");
        global $_POST;
        
        $name = $this->name;
        $SPLIT_Str = $this->SPLIT_Str;
        $message = $this->message;
        
        
        // 送信されたデータ
        $_POST_string = join(', ', $_POST);
        //trace("_POST_string2= " . $_POST_string . "<br>");
        
        if (empty($_POST)) {
            trace("The form is empty.<br>");
        } else {
            trace("Form data is present.<br>");
        }
        
        // 送信された名前とメッセージを変数に代入
        if (isset($_POST['name'])) {
          $name = $_POST['name'];
     
          if (strpos($name, $SPLIT_Str) !== false) {
            // 名前に区切り文字が含まれている場合の処理
            echo "使用できない文字列「|-|」が含まれています。<br>";
            return;
          }
     
          if ($name == "") {
            $name = "担当者";
          }
        }
        if (isset($_POST['message'])) {
          $message = $_POST['message'];
     
          if (strpos($message, $SPLIT_Str) !== false) {
            // メッセージに区切り文字が含まれている場合の処理
            echo "使用できない文字列「|-|」が含まれています。<br>";
            return;
          }
     
          //$this->LOG_FILE_NAME=$LOG_FILE_NAME;
          $this->name=$name;
          //$this->SPLIT_Str=$SPLIT_Str;
          $this->message=$message;
          $this->LogWrite();
        }
    }
   
    
    public function LogWrite(){
      trace("■ LogWrite()<br>");
      $LOG_FILE_NAME = $this->LOG_FILE_NAME;
      $name = $this->name;
      $SPLIT_Str = $this->SPLIT_Str;
      $message = $this->message;
        
      //書き込みモードでファイルを開く
      $fp = fopen($LOG_FILE_NAME, "a") or exit($LOG_FILE_NAME . "が開けません<br>");
 
      // | を区切り文字として2つのデータを繋げて書き込む
      fwrite($fp, $name . $SPLIT_Str . $message . "\n");
      
      
      // リダイレクトのためのHTTPヘッダーを送信
      //header("Location: " . $_SERVER['PHP_SELF'], true, 303);
      
      fclose($fp);
    }

    function LogShow(){
        trace("■ LogShow()<br>");
        //global $LOG_FILE_NAME;
        global $linesNum;
        global $lines;
        $LOG_FILE_NAME = $this->LOG_FILE_NAME;
        //$name = $this->name;
        //$SPLIT_Str = $this->SPLIT_Str;
        //$message = $this->message;
        
        if (!file_exists($LOG_FILE_NAME)) {
          // ファイルがない場合
          echo "書き込みはありません。<br>";
     
          $linesNum = 0;
        } else {
     
          // ファイルの全行を読み取る
          $lines = file($LOG_FILE_NAME);
     
          // 読み込んだ行数
          $linesNum = count($lines);
        }
    }
    
}

$RoomLog_ins = new RoomLog();
$RoomLog_ins->startMain();

?>
 

 
<h1>お問い合わせ内容</h1>
 
  <section>
    <?php
 
      // 一行ずつ表示する処理
      for ($i = 0; $i < $linesNum; $i++) {
 
         // 区切り文字でデータを区切って配列に格納
         $array = explode($SPLIT_Str, $lines[$i]);
 
         // 区切り文字の前の部分は名前
         $name = htmlspecialchars($array[0]);
         
         
         // 区切り文字の後の部分はメッセージ
         
         $array_length = count($array);
         if ($array_length == 2) {
           $message = htmlspecialchars($array[1]);
         }
         // 名前とメッセージを表示
         echo '<p>' . $name . "「" . str_replace(PHP_EOL, "", $message) . '」</p>';
      }
    ?>
  </section>


  
 
  <form method="post" action="chat_class_txt_admin.php">
    <div>
      <!--<b>おなまえ</b>-->
      <!--<input name="name" type="text" size="20" maxlength="10">-->
      <input name="name" type="hidden" size="20" maxlength="10">
    </div>
    <div>
      <!--<b>ご入力</b>-->
      <?php
      echo('<input type="hidden" name="LOG_FILE_NAME" value="' . $LOG_FILE_NAME . '">');
      ?>
      <input name="message" type="text" size="50" maxlength="50" required>
      <button name="submit" type="submit">送信</button>
    </div>
    
  </form>
  
  
    </div><!--div class="class2"-->
  </div><!--div class="base"-->
</body>
</html>

こちらのサイトを参考にしました。
PHPで作るチャット(7) クロスサイトスクリプティング(XSS)の修正

このPHPをクラスベースで書き直しました。

[xampp] php Rechet chatを作る勉強。

参考サイト

[PHP]Ratchetの初期設定とテキストのリアルタイム通信テスト

Xamppをwindowsをインストール

https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/7.4.33/

お名前.comのPHPが7.4なので

https://sourceforge.net/projects/xampp/files/XAMPP%20Windows/7.4.33/xampp-windows-x64-7.4.33-0-VC15-installer.exe/download

をダウンロードした。

システム環境変数にphpのパスを通す

C:\xampp\php

PHPのバージョン確認

PS C:\xampp\htdocs> php -v
PHP 7.4.33 (cli) (built: Nov  2 2022 16:00:55) ( ZTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
PS C:\xampp\htdocs>

Composerをインストール

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === 'e21205b207c3ff031906575712edab6f13eb0b361f2085f1f1237b7126d785e826a450292b6cfd1d64d92e6563bbde02') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

XAMPP の htdocs ディレクトリに任意の名前のフォルダを作成し、ターミナルでアクセスできる状態にします。この例では MyChat というフォルダ名にしています。

php ../composer.phar require cboden/ratchet

こんなファイルが出てきます。

composer.json を開き autoload の5行を追記します。

{
    "autoload": {
        "psr-4": {
            "MyApp\\": "src"
        }
    },
    "require": {
        "cboden/ratchet": "^0.4.3"
    }
}

ディレクトリ MyChat にフォルダ src/ を作成し、その中に(Chat.php)を作成します。

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
 
class Chat implements MessageComponentInterface {
    public function onOpen(ConnectionInterface $conn) {
    }
 
    public function onMessage(ConnectionInterface $from, $msg) {
    }
 
    public function onClose(ConnectionInterface $conn) {
    }
 
    public function onError(ConnectionInterface $conn, \Exception $e) {
    }
}

同様にフォルダ bin/ を作成し、その中にスクリプト(chat-server.php)を作成してください。

<?php
use Ratchet\Server\IoServer;
use MyApp\Chat;
 
    require dirname(__DIR__) . '/vendor/autoload.php';
 
    $server = IoServer::factory(
        new Chat(),
        8080
    );
 
    $server->run();

以上のスクリプトを作成後、ターミナルで以下のコマンドを入力してください。

php bin/chat-server.php

正常に動作するとターミナルには何も表示されないはずですが、以下のようなエラーが表示される場合があります。

PS C:\xampp\htdocs\MyChat> php bin/chat-server.php
PHP Fatal error:  Uncaught Error: Class 'MyApp\Chat' not found in C:\xampp\htdocs\MyChat\bin\chat-server.php:8
Stack trace:
#0 {main}
  thrown in C:\xampp\htdocs\MyChat\bin\chat-server.php on line 8

Fatal error: Uncaught Error: Class 'MyApp\Chat' not found in C:\xampp\htdocs\MyChat\bin\chat-server.php:8
Stack trace:
#0 {main}
  thrown in C:\xampp\htdocs\MyChat\bin\chat-server.php on line 8
PS C:\xampp\htdocs\MyChat>

もしこのエラーが表示されたなら composer.phar のアップデートを実行してみてください。アップデートのコマンドは以下のとおりです。

	php ../composer.phar update

再度やってみます。

php bin/chat-server.php

正常に動作した場合は control+C で終了させてください。

以上で通信のための準備が整いました。

メッセージ送信の実行

実際に通信をテストするには、まず Chat.php を以下のように書き換えます。

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
 
class Chat implements MessageComponentInterface {
    protected $clients;
 
    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }
 
    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);
 
        echo "New connection! ({$conn->resourceId})\n";
    }
 
    public function onMessage(ConnectionInterface $from, $msg) {
        $numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
 
        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }
    }
 
    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);
 
        echo "Connection {$conn->resourceId} has disconnected\n";
    }
 
    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";
 
        $conn->close();
    }
}

そして、ターミナルのウィンドウを3つ開き、それぞれ以下のコマンドを入力します。

php bin/chat-server.php
telnet localhost 8080
telnet localhost 8080

もし telnet がないと言われた場合は python を利用する以下のコマンドを試してみてください。

	python -m telnetlib localhost 8080

実行結果です。一方のtelnetにメッセージを入力すると、他方にメッセージが表示されます。接続状態などは bin/chat-server.php を実行したウィンドウに表示されます。

ブラウザを利用したメッセージの送信

chat-server.php を以下のように書き換えます。

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
 
    require dirname(__DIR__) . '/vendor/autoload.php';
 
    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Chat()
            )
        ),
        8080
    );
 
    $server->run();

ターミナルで再度 bin/chat-server.php を実行し、

MyChat/index.htmlに以下のHTMLフォームボタンで動くとjavascriptを入力します。

<br><br><br><br><br><br><br><br>
<a href="javascript:myFunction();">リンクでJSのmyFunction()実行</a>
<script>
function myFunction() {
// フォームボタンがクリックされたときの処理をここに記述

//------------------------------------------------------
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
    console.log("Connection established!");
};
 
conn.onmessage = function(e) {
    console.log(e.data);
};
//------------------------------------------------------
alert('入室しました!');
}
</script>

実行結果は以下のとおりです。

ターミナルにブラウザから send によって送信したメッセージが表示されました。

以上、Ratchetの初期設定と、それを利用した通信の例でした。

[maya] maya_usd で get Selected Prim Path

maya_usd 選択したprimからprimのpathを得る方法
ls で取れた、

ufeObjects(ufe)

-sl/selectionフラグ と組み合わせて使用​​すると、ネイティブ Maya オブジェクトだけでなく、UFE インターフェイスを通じて定義されたオブジェクトも返されます。

import maya.cmds as cmds
 
proxy_prim_path = cmds.ls(sl=True, ufe = True)
#or
proxy_prim_path = cmds.ls(sl=True, ufeObjects = True)
print("proxy_prim_path= "+str(proxy_prim_path))

Output

proxy_prim_path= ['|stage1|stageShape1,/Ball1/Ball_Mesh']

参考URL

https://help.autodesk.com/cloudhelp/2022/ENU/Maya-Tech-Docs/CommandsPython/ls.html

https://stackoverflow.com/questions/76558940/select-and-hide-multiple-usd-prims-in-maya

[maya][python]scriptEditorInfoでスクリプトエディタの内容のログの最後の行を取る

Take the last line of the log in the contents of the script editor

#!/usr/bin/env python
# -*- coding: utf-8 -*-
workSpaceDir=cmds.workspace( q=True, rootDirectory=True )
print("workSpaceDir= "+workSpaceDir)
historyFilename=workSpaceDir+'scriptEditorInfo_tempHistoryLog7.txt'
print("historyFilename= "+historyFilename)
cmds.scriptEditorInfo(input="")
cmds.scriptEditorInfo( historyFilename=historyFilename, writeHistory=True )

print("----startLog00700---")
#-----この間にUSD prim を選択させてみたい。 ----------
#------難しいかな??
#-----この間にUSD prim を選択させてみたい。 ----------
import codecs
fin  = codecs.open(historyFilename, 'r', 'shift_jis')
lineCount=0
lineArr=[]
for line in fin:
    #print("lineNum:"+str(lineCount)+" lineStr:"+line)
    lineCount=lineCount+1
    lineArr.append(line)
#fout = codecs.open('sjis.txt', 'w', 'shift_jis')
#fin_str=str(fin)
lineArr_len=len(lineArr)
print("lineArr_len= "+str(lineArr_len))
LastLine_Str=lineArr[lineArr_len-1]
print("LastLine_Str= "+LastLine_Str)

cmds.scriptEditorInfo(input="")
cmds.scriptEditorInfo( historyFilename=historyFilename, writeHistory=False )

print("----NotLoged----")

[maya][mel] scriptedPanel のサンプルを動作させてみた。想像と違った。

I tried running the scriptedPanel sample.

// define callbacks for this type and make it a unique type
// as we don't want two panels sharing the same global data.

scriptedPanelType
    -ccb sampleCreateCallback
    -icb sampleInitCallback
    -acb sampleAddCallback
    -rcb sampleRemoveCallback
    -dcb sampleDeleteCallback
    -scb sampleSaveStateCallback
    -unique true
    "sampleScriptedPanelType6";


global proc sampleCreateCallback(string $panelName) {
//
//  Description:
//      Create any editors unparented here and do
//      any other initialization required.
//
//      In this example we will only declare a global array to
//        maintain some state information.
//
    global float $gSampleState[5];

}


global proc sampleInitCallback(string $panelName) {
//
//  Description:
//      Re-initialize the panel on file -new or file -open.
//
//      In this example we will only re-init the global array.
//
    global float $gSampleState[];

       $gSampleState[0] = 20.2;
       $gSampleState[1] = 50.5;
       $gSampleState[2] = 34.7;
       $gSampleState[3] = 2.0;
       $gSampleState[4] = 1.0;

}

global proc sampleAddCallback(string $panelName) {
//
//  Description:  Create UI and parent any editors.
//
    global float $gSampleState[];

    columnLayout -adj true topCol;
    separator -style "none" -h 10;
        frameLayout -l "Sliders" -mw 10;
            columnLayout -adj true sampleCol;
                separator -style "none" -h 10;

                floatSliderGrp -l "Property A" -f true
                    -v $gSampleState[0]
                    fsg1;
                floatSliderGrp -l "Property B" -f true
                    -v $gSampleState[1]
                    fsg2;
                floatSliderGrp -l "Property C" -f true
                    -v $gSampleState[2]
                    fsg3;
                separator -style "none" -h 10;
            setParent ..;
        setParent ..;

        separator -style "none" -h 10;
        frameLayout -l "Radio Buttons" -mw 10;
            columnLayout sampleCol2;
                separator -style "none" -h 10;
                radioButtonGrp -nrb 3
                    -l "Big Options"
                    -la3 "Option 1" "Option 2" "Option 3"
                    -select $gSampleState[3]
                    rbg;
                radioButtonGrp -nrb 3
                    -l "Little Options"
                    -la3 "Option 4" "Option 5" "Option 6"
                    -select $gSampleState[4]
                    rbg2;
                separator -style "none" -h 10;

}

global proc sampleRemoveCallback(string $panelName) {
//
//  Description:
//        Unparent any editors and save state if required.
//
        global float $gSampleState[];
       //  Scope the control names to this panel.
       //
       string $control = `scriptedPanel -q -control $panelName`;
       setParent $control;

       $gSampleState[0] = `floatSliderGrp -q -v fsg1`;
       $gSampleState[1] = `floatSliderGrp -q -v fsg2`;
       $gSampleState[2] = `floatSliderGrp -q -v fsg3`;
       $gSampleState[3] = `radioButtonGrp -q -sl rbg`;
       $gSampleState[4] = `radioButtonGrp -q -sl rbg2`;
}

global proc sampleDeleteCallback(string $panelName) {
//
//  Description:
//        Delete any editors and do any other cleanup required.

}

global proc string sampleSaveStateCallback(string $panelName) {
//
//  Description:
//        Return a string that will restore the current state
//        when it is executed.

        global float $gSampleState[];
       $indent = "\n\t\t\t";

       return ($indent+"$gSampleState[0]="+$gSampleState[0]+";" +
               $indent+"$gSampleState[1]="+$gSampleState[1]+";" +
               $indent+"$gSampleState[2]="+$gSampleState[2]+";" +
               $indent+"$gSampleState[3]="+$gSampleState[3]+";" +
               $indent+"$gSampleState[4]="+$gSampleState[4]+";" +
               $indent+"setSamplePanelState $panelName;\n" );
}

global proc setSamplePanelState( string $whichPanel ) {
//
//  Description:
//        This is a convenience proc to set the panel state from the
//        global array

        global float $gSampleState[];

       //  Scope the control names to this panel.
       //
       string $control = `scriptedPanel -q -control $whichPanel`;
       if ("" != $control) {
              setParent $control;

              floatSliderGrp -e -v $gSampleState[0] fsg1;
              floatSliderGrp -e -v $gSampleState[1] fsg2;
              floatSliderGrp -e -v $gSampleState[2] fsg3;
              if (0 != $gSampleState[3]) {
               radioButtonGrp -e -sl $gSampleState[3] rbg;
              };
           if (0 != $gSampleState[4]) {
               radioButtonGrp -e -sl $gSampleState[4] rbg2;
           }
       }
}


//  This script will create an unparented scripted panel, place it
//  in one window, remove it, and place it in another window then
//  return it to the first window.
//

//    Create unparented scripted panel
//
scriptedPanel -unParent -type "sampleScriptedPanelType6" -label "Sample" "sampleScriptedPanel6";

//    Create a couple of windows and parent the scripted panel to the first.
//
window "sampleWin6";
frameLayout -lv false -bv false frm;
scriptedPanel -e -parent "sampleWin6|frm" "sampleScriptedPanel6";
showWindow;
/*
window -w `window -q -w sampleWin` -h `window -q -h "sampleWin"` "sampleWin2";
frameLayout -lv false -bv false frm;
showWindow;
*/

[maya]maya_usdでstageのレイヤーにprimxformを作る、そのprimxformにAdd USD Referenceを追加する。

Create a primxform in the stage layer with maya_usd, and add Add USD Reference to that primxform.

print("add_primxform_for_stage_layer")

import maya.cmds as cmds
from maya import cmds
import mayaUsd.ufe
from pxr import Usd, UsdGeom
import re
import os
#cmds.workspace( directory=workspacepath)でいいかとおもっていたけどちがかった件。
def evalMelSetProject(FullDirPath):
	print("-----------------------------------maya.mel.eval evalMelSetProject(evalstr)----------------------------------------")# 20161121
	evalstr='setProject("'+FullDirPath+'");' #OK
	print("evalstr="+evalstr);
	maya.mel.eval(evalstr) #OK
	print("----------------------------------maya.mel.eval evalMelSetProject(evalstr) End----------------------------------")
	

def get_stage(stagePath):
    import mayaUsd.ufe
    #stagePath="|stage1|stageShape1"
    #stage = mayaUsd.ufe.getStage("|stage1|stageShape1")
    stage = mayaUsd.ufe.getStage(stagePath)
    print("stage= "+str(stage))
    # レイヤーを取得
    layer = stage.GetRootLayer()
    print("layer= "+str(layer))
    return stage


    
def get_selected_maya_usd_stage():
    selectedlist=cmds.ls(sl=True,long=1)
    print("selectedlist= "+str(selectedlist))
    selectedZero=selectedlist[0]
    print("selectedZero= "+selectedZero)
    selectedZeroType=cmds.objectType( selectedZero )
    print("selectedZeroType= "+str(selectedZeroType))
    usd_stage=""
    stagePath=""
    if(str(selectedZeroType)=="mayaUsdProxyShape"):
        layerPath=selectedZero
        usd_stage=get_stage(layerPath)
    elif(str(selectedZeroType)=="transform"):
        stageNumStr=selectedZero[6:]
        layerPath="|stage"+stageNumStr+"|stageShape"+stageNumStr
        print("layerPath= "+layerPath)
        cmds.select(layerPath)
        usd_stage=get_stage(layerPath)
    else:
        print("not stage!!!!")
    return usd_stage,layerPath


def usd_increment_name(name,existing_names):
    new_name = name
    i = 1
    # in演算子 new_name が existing_names に存在する場合はTrueを、そうでない場合はFalseを返します。
    while new_name in existing_names:
        new_name = name+str(i)
        print("存在します。"+str(new_name))
        i += 1
       
    else:
        print("while out  "+str(new_name))
    return new_name  

print("----start-----")
def add_prim_xform_for_stage_layer(add_ref_USD_file_path):
    #---------------------SetProject-------------------------
    filePath = cmds.file(q=1,sceneName=1)
    print("filePath= "+filePath)
    dirPath = os.path.dirname(filePath)
    dirPath=re.sub(r'\\', '/', dirPath)
    #dirPath=os.path.abspath(dirPath)
    print("dirPath= "+dirPath)
    FullDirPath=dirPath
    evalMelSetProject(FullDirPath)
    #-------------------------------------------------------
    
    stage,layerPath = get_selected_maya_usd_stage()
    print("stage= "+str(stage))
    print("layerPath= "+str(layerPath))
    # レイヤーを取得
    #layer = stage.GetEditTarget().GetLayer()
    layer = stage.GetRootLayer()
    print("layer= "+str(layer))
    
    # Primを作成
    prim_count=1
    prim_path = "/Xform"+str(prim_count)
    newPrimStagePath=layerPath+","+prim_path
    print("newPrimStagePath= "+newPrimStagePath)
    
    #layerPrimList = cmds.listRelatives(layerPath,children=1)
    #layerPrimList = cmds.listConnections(layerPath,destination=1)
    #print("layerPrimList= "+str(layerPrimList))

    # レイヤー内のすべてのPrimを取得
    all_prims = stage.Traverse()
    print("all_prims= "+str(all_prims))
    # Primのリストを出力
    
    all_primName_list=[]
    for prim in all_prims:
        print(prim.GetPath())
        all_primName_list.append(str(prim.GetPath()))
    print("all_primName_list= "+str(all_primName_list))
    
    
    newPrim_path=usd_increment_name("/Xform",all_primName_list)
    print("newPrim_path= "+newPrim_path)
    
    # Primを作成
    prim = UsdGeom.Xform.Define(stage, newPrim_path)
    
    # レイヤーにPrimを追加
    #layer.GetPrimAtPath(newPrim_path)
    
    print("Primが追加されました:", prim.GetPath())
   
    # 追加するUSDファイルのパス
    referencePath = dirPath+"/Usd/S_Stg_Cys_StartArea_Grd.usda"
    referencePath = add_ref_USD_file_path
    print("referencePath= "+referencePath)
    # USDリファレンスを追加
    prim.GetPrim().GetReferences().AddReference(referencePath)
    
    # ステージを保存
    #
    #setAttr -type "string" |stage6|stageShape6.filePath "D:/SandBox/USD_Maya2023/16_newyear/stageShape6-1GGoNk.usd";
    #cmds.setAttr -type "string" |stage6|stageShape6.filePath "D:/SandBox/USD_Maya2023/16_newyear/stageShape6-1GGoNk.usd";
    attName=layerPath+".filePath"
    layout_attpath=dirPath+"/Usd/Stg_Cys_003Floor01_example.usd"
    layout_attpath=dirPath+"/Layout_00100.usd"
    print("layout_attpath= "+layout_attpath)
    cmds.setAttr( attName, layout_attpath,type="string")
    #stage.GetRootLayer().subLayerPaths.append(dirPath+"Usd/Stg_Cys_003Floor01_example.usd")
    #stage.GetRootLayer().Save()
    """"""
    
#add_prim_xform_for_stage_layer()

g_lastSetPath=""

def select_exportDir(self):
    
    filePath = cmds.fileDialog2( cap = 'リファレンスするディレクトリの選択', okc = 'リファレンスするディレクトリを設定',dialogStyle = 2, fileMode = 3,startingDirectory=get_lastSetPath())
    if filePath == None:
        return False
    else:
        set_refDirPath(filePath[0]+"/")
        
def set_refDirPath(refDir):
    print("refDir= "+refDir)
    refDir_Arr=refDir.split("/")
    refDir_Arr_last=len(refDir_Arr)
    print("refDir_Arr_last= "+str(refDir_Arr_last))
    DirName=refDir_Arr[refDir_Arr_last-2]
    print("DirName= "+DirName)
    #D:/SandBox/USD_Maya2023/17_subfolder/Stick/Stick.mb
    ref_USD_filePath=refDir+DirName+".usda"
    add_prim_xform_for_stage_layer(ref_USD_filePath)
    
def exportFile():
    filePath = cmds.fileDialog2(fileFilter = '*.json', cap = '書き出し', okc = '書き出し',ds = 2, fm = 0)
    if filePath == None:
        return False
               
def importFile():
    filePath = cmds.fileDialog2(fileFilter = '*.json', cap = '読み込み', okc = '読み込み',ds = 2, fm = 1)
    if filePath == None:
        return False

def get_lastSetPath():
    global g_lastSetPath
    lastSetPath=""
    if(g_lastSetPath==""):
        print("g_lastSetPath=は値なし")
        scenePath=get_scenePath_ref()
        scenePath=os.path.abspath(scenePath)
        lastSetPath=scenePath
        g_lastSetPath=lastSetPath
    else:
        print("g_lastSetPath=は値 g_lastSetPath="+g_lastSetPath)
        lastSetPath=g_lastSetPath
    print("g_lastSetPath= "+g_lastSetPath)
    print("lastSetPath= "+lastSetPath)
    return lastSetPath

def get_scenePath_ref():
    scenefilePath = cmds.file(q=1, sceneName=1)
    mayaPath,mayaFile = os.path.split(scenefilePath)
    #mayaPath = mayaPath + "/Usd/"
    mayaPath=os.path.abspath(mayaPath)
    return mayaPath


text_Field_id=""       
def createWindow():
    scenefilePath = cmds.file(q=1, sceneName=1)

    USD_window = cmds.window("FURC_USD_Layout_Add_PrimXformReference_For_StageLayer_Window", widthHeight=(400, 200))
    USD_layout = cmds.columnLayout("USD_layout",adjustableColumn=True, parent=USD_window)

    cmds.text (label="primをぶら下げたいステージのレイヤーを選択して、", align='left', parent=USD_layout)
    cmds.text (label="[Add USD Referernce/Payload...]を押してください", align='left', parent=USD_layout)
    cmds.separator(parent=USD_layout)
    
    cmds.button(label="Add USD Referernce/Payload... ", command=select_exportDir, parent=USD_layout)
    
    #cmds.separator(parent=USD_layout)

    #cmds.button(label="Add USD Referernce/Payload... ", command=add_prim_xform_for_stage_layer, parent=USD_layout)

    cmds.showWindow(USD_window)
    return None


def folderOpen(self):
    Exportpath = get_lastExportDirPath()
    Exportpath = Exportpath.replace('/', '\\')
    subprocess.Popen(["explorer", "/root,", Exportpath], shell=True)
    print(USD.mayaPath)

def get_scenePath():
    scenefilePath = cmds.file(q=1, sceneName=1)
    mayaPath,mayaFile = os.path.split(scenefilePath)
    mayaPath = mayaPath + "/Usd/"
    return mayaPath
    
def btn_scene(self):
    scenePath = get_scenePath()
    print("scenePath= "+scenePath)
    set_lastExportDirPath(scenePath)
    
def changeTextFld(*arg):
    #mayaPath = get_scenePath()
    #cmds.textField("pathTxtFld", edit=True, text=get_lastExportDirPath())
    #pathTxtFld_value=cmds.textField("pathTxtFld", r=True, v=True)
    #pathTxtFld_value = cmds.textField("pathTxtFld", q=True, text=True)
    text_Field_id="FURC_USD_Layout_Add_PrimXformReference_For_StageLayer_Window|USD_layout|pathTxtFld"
    print("text_Field_id= "+text_Field_id)
    pathTxtFld_value = cmds.textField(text_Field_id, q=True, text=True)
    #pathTxtFld_value = pathTxtFld
    print("pathTxtFld_value= "+pathTxtFld_value)
    set_lastExportDirPath(pathTxtFld_value)
    
def clearWindow():
    if cmds.window("FURC_USD_Layout_Add_PrimXformReference_For_StageLayer_Window",exists=True):
        cmds.deleteUI("FURC_USD_Layout_Add_PrimXformReference_For_StageLayer_Window")
    return None
    
def FURC_USD_Layout_Add_PrimXformReference_For_StageLayer_Window_Func():
    if cmds.window("FURC_USD_Layout_Add_PrimXformReference_For_StageLayer_Window",exists=True):
        cmds.deleteUI("FURC_USD_Layout_Add_PrimXformReference_For_StageLayer_Window")
    createWindow()



FURC_USD_Layout_Add_PrimXformReference_For_StageLayer_Window_Func()

[maya]maya_usd で選択したstageのLayerにPrimXformを追加する、同じ名前がある場合は別の名前で追加

Add a prim to the layer of the stage selected with maya_usd. It has the same name but is added with a different name.

print("add_primxform_for_stage_layer")

import maya.cmds as cmds
from maya import cmds
import mayaUsd.ufe
from pxr import Usd, UsdGeom

def get_stage(stagePath):
    import mayaUsd.ufe
    stage = mayaUsd.ufe.getStage(stagePath)
    print("stage= "+str(stage))
    # レイヤーを取得
    layer = stage.GetRootLayer()
    print("layer= "+str(layer))
    return stage


    
def get_selected_maya_usd_stage():
    selectedlist=cmds.ls(sl=True,long=1)
    print("selectedlist= "+str(selectedlist))
    selectedZero=selectedlist[0]
    selectedZeroType=cmds.objectType( selectedZero )
    print("selectedZeroType= "+str(selectedZeroType))
    usd_stage=""
    stagePath=""
    if(str(selectedZeroType)=="mayaUsdProxyShape"):
        layerPath=selectedZero
        usd_stage=get_stage(layerPath)
    elif(str(selectedZeroType)=="transform"):
        layerPath="|stage"+stageNumStr+"|stageShape"+stageNumStr
        cmds.select(layerPath)
        usd_stage=get_stage(layerPath)
    else:
        print("not stage!!!!")
    return usd_stage,layerPath

def Exist_Prim(prim_path):
    from maya import cmds
    from mayaUsd import ufe, lib
    from pxr import Sdf
    # Primが存在するかどうかを確認
    #primPath = Sdf.Path('/path/to/your/prim')
    primPath = Sdf.Path(prim_path)
    primExist = stage.GetPrimAtPath(primPath)
    if primExist:
        print('Primが存在します')
    else:
        print('Primが存在しません')
    return primExist

def usd_increment_name(name,existing_names):
    new_name = name
    i = 1
    # in演算子 new_name が existing_names に存在する場合はTrueを、そうでない場合はFalseを返します。
    while new_name in existing_names:
        new_name = name+str(i)
        print("存在します。"+str(new_name))
        i += 1
       
    else:
        print("while out")
    return new_name  

print("----start-----")
def add_prim_xform_for_stage_layer():

    stage,layerPath = get_selected_maya_usd_stage()
    
    # レイヤーを取得
    layer = stage.GetRootLayer()
    print("layer= "+str(layer))
    
    # Primを作成
    prim_count=1
    prim_path = "/Xform"+str(prim_count)
    newPrimStagePath=layerPath+","+prim_path
    print("newPrimStagePath= "+newPrimStagePath)

    Exist_Prim(newPrimStagePath)

    # レイヤー内のすべてのPrimを取得
    all_prims = stage.Traverse()
    print("all_prims= "+str(all_prims))
    # Primのリストを出力
    
    all_primName_list=[]
    for prim in all_prims:
        print(prim.GetPath())
        all_primName_list.append(str(prim.GetPath()))
    print("all_primName_list= "+str(all_primName_list))
    
    
    newPrim_path=usd_increment_name("/Xform",all_primName_list)
    print("newPrim_path= "+newPrim_path)
    
    # Primを作成
    prim = UsdGeom.Xform.Define(stage, newPrim_path)
    
    # レイヤーにPrimを追加
    #layer.GetPrimAtPath(newPrim_path)
    
    print("Primが追加されました:", prim.GetPath())


add_prim_xform_for_stage_layer()