Exemplo n.º 1
0
def readFile():
    # Pathオブジェクトを生成
    p = Path(vrmapi.SYSTEM().GetLayoutDir() + "\\read")
    l = list(p.glob("*.txt"))
    for item in l:
        try:
            #withでテキスト読み込みモード使用
            with open(item, 'r') as text:
                # 文字列を全て読み込む
                t = text.read()
                # タブで分割
                line = t.split()
                # 要素が0:Object種別、1:ID、2:命令、3:Paramの4つ以上
                if len(line) >= 4:
                    readFileLine(line)
                #vrmapi.LOG(str(t))
            # 読み込んだファイルは別フォルダへ移動
            re = vrmapi.SYSTEM().GetLayoutDir() + "\\read_end\\" + item.name
            #vrmapi.LOG(str(re))
            shutil.move(item, re)
            # 出力機能
            global _sendState
            if _sendState == True:
                sendStateFile()
        except Exception as e:
            # エラーファイルは名前を変えて別フォルダへ移動
            re = vrmapi.SYSTEM().GetLayoutDir(
            ) + "\\read_end\\ERR_" + item.name
            vrmapi.LOG(str(e))
            vrmapi.LOG(str(re))
            shutil.move(item, re)
Exemplo n.º 2
0
def vrmevent(obj, ev, param):
    if ev == 'init':
        # フォルダチェック
        dir = vrmapi.SYSTEM().GetLayoutDir()
        if (os.path.exists(dir + "\\read") == False):
            vrmapi.LOG(dir + "\\read フォルダがありません。ファイル連携機能を無効にします。")
            return
        if (os.path.exists(dir + "\\read_end") == False):
            vrmapi.LOG(dir + "\\read_end フォルダがありません。ファイル連携機能を無効にします。")
            return
        global _sendState
        if _sendState == True:
            if (os.path.exists(dir + "\\send") == False):
                vrmapi.LOG(dir + "\\send フォルダがありません。出力機能を無効にします。")
                # 出力機能無効化
                _sendState = False
                return
            else:
                vrmapi.LOG("出力機能が有効です。")
        # 起動時に0.1秒間隔のタイマーイベントを登録
        obj.SetEventTimer(0.1)
        # (任意)レイアウト内の全編成の電源を一括設定(0:OFF, 1:ON)
        #setPowerAll(0)
        # (任意)sendフォルダにレイアウト初期情報を出力
        sendSettingFile()
    elif ev == 'timer':
        # タイマーイベントでフォルダを周期監視
        readFile()
Exemplo n.º 3
0
def process_layout_event(obj, ev, param):
    """frameイベントのたびにクライアントからの接続要求とコマンド文字列を処理する。

    VRM-NXのレイアウトスクリプトに記述したvrmevent()から呼ばれる。

    """
    global _servercommandsocket, _clientcommandsocket, _clientcommandstream
    global _servereventsocket, _clienteventsocket, _clienteventstream

    if ev == 'frame':
        # コマンド用ソケットへの接続を受け付ける。
        # 接続要求が無いときはBlockingIOError発生で次の処理に進む。
        try:
            newclientsocket, (address, port) = _servercommandsocket.accept()
            vrmapi.LOG(f'commandsocket: {address}:{port}')
            _closecommandsocket()
            _clientcommandsocket = newclientsocket
            _clientcommandstream = _clientcommandsocket.makefile(mode='rw')
        except (BlockingIOError, socket.error):
            pass
        # イベント用ソケットへの接続を受け付ける。
        # 接続要求が無いときはBlockingIOError発生で次の処理に進む。
        try:
            newclientsocket1, (address, port) = _servereventsocket.accept()
            vrmapi.LOG(f'eventsocket: {address}:{port}')
            _closeeventsocket()
            _clienteventsocket = newclientsocket1
            _clienteventstream = _clienteventsocket.makefile(mode='rw')
        except (BlockingIOError, socket.error):
            pass

        # コマンド用ソケットからコマンドを読み込んでパーサーに渡す。
        # 受信バッファーにコマンドが無いときは次の処理に進む。
        if _clientcommandstream:
            try:
                while True:
                    command = _clientcommandstream.readline().rstrip()
                    if not command:
                        break
                    #vrmapi.LOG(f'command:{command}')

                    response = None
                    try:
                        response = atovrmnxparser.execvrmapi(command)
                    except Exception as e:
                        vrmapi.LOG(f'execvrmapi("{command}"): {e}')

                    if response is not None:
                        #vrmapi.LOG(f'response:{response}')
                        try:
                            _clientcommandstream.write(f'{response}\n')
                            _clientcommandstream.flush()
                        except Exception as e:
                            vrmapi.LOG(f'commandsocket write: {e}')
                            _closecommandsocket()
            except Exception as e:
                vrmapi.LOG(f'commandsocket read: {e}')
                _closecommandsocket()
Exemplo n.º 4
0
def init():
    # 編成リストを新規リストに格納
    tList = vrmapi.LAYOUT().GetTrainList()
    # 編成リストから編成を繰り返し取得
    for obj in tList:
        # ダミー編成以外
        if obj.GetDummyMode() == False:
            # 編成オブジェクト内に表示用タグ作成
            di = obj.GetDict()
            di['pw_ch1'] = [0]
            di['pw_ch2'] = [0]
            di['pw_drl'] = [0]
            di['pw_drr'] = [0]
            di['pw_msg'] = ''
            # 音の初期値を入力
            if obj.GetSoundPlayMode() == 2:
                di['pw_ch2'] = [1]
        else:
            vrmapi.LOG("{0} [{1}] ダミースキップ".format(obj.GetNAME(), obj.GetID()))

    # ポイントリストを新規リストに格納
    pList=list()
    vrmapi.LAYOUT().ListPoint(pList)
    # ポイントリストからポイントを繰り返し取得
    for obj in pList:
        # 頭文字「dummy」は対象外
        if obj.GetNAME()[0:5] != 'dummy':
            # ポイントオブジェクトに表示用タグ作成
            di = obj.GetDict()
            # 初期値設定
            di['pw_r'] = [obj.GetBranch()]
        else:
            vrmapi.LOG("{0} [{1}] ダミースキップ".format(obj.GetNAME(), obj.GetID()))


    # 信号リストを新規リストに格納
    sList=list()
    vrmapi.LAYOUT().ListSignal(sList)
    # ポイントリストからポイントを繰り返し取得
    for obj in sList:
        # 頭文字「dummy」は対象外
        if obj.GetNAME()[0:5] != 'dummy':
            # ポイントオブジェクトに表示用タグ作成
            di = obj.GetDict()
            # 初期値設定
            di['pw_s0'] = [obj.GetStat(0)]
            di['pw_s1'] = [obj.GetStat(1)]
        else:
            vrmapi.LOG("{0} [{1}] ダミースキップ".format(obj.GetNAME(), obj.GetID()))
Exemplo n.º 5
0
def readFileLine(line):
    # 種別T=列車オブジェクト
    if line[0] == "T":
        #vrmapi.LOG(line[1])
        train = vrmapi.LAYOUT().GetTrain(int(line[1]))
        if line[2] == "AutoSpeedCTRL":
            #vrmapi.LOG(line[2])
            train.AutoSpeedCTRL(int(line[3]), float(line[4]))
        elif line[2] == "Turn":
            train.Turn()
        elif line[2] == "PlayHorn":
            train.PlayHorn(int(line[3]))
        elif line[2] == "SplitTrain":
            spl = train.SplitTrain(int(line[3]))
            vrmapi.LOG("Train[{}].SplitTrain({})->Train[{}]".format(
                line[1], line[3], spl))
        elif line[2] == "SetPower":
            setPower(train, int(line[3]))
    # 種別P=ポイントオブジェクト
    elif line[0] == "P":
        #vrmapi.LOG(line[1])
        # 向き
        d = int(line[3])
        # アンダーバーで複数あり(カンマは運転盤のcheckbox.Nameでエラーのため使えず)
        if ('_') in line[1]:
            # アンダーバーで分割
            pAry = line[1].split('_')
            # 複数ポイント処理
            for p in pAry:
                pid = int(p)
                # 負数の場合
                if pid < 0:
                    # 整数に戻す
                    pid = -pid
                    # 方向反転
                    if d == 0:
                        d = 1
                    else:
                        d = 0
                # ID検索
                point = vrmapi.LAYOUT().GetPoint(pid)
                vrmapi.LOG("SetBranch:" + str(pid) + " " + str(d))
                if line[2] == "SetBranch":
                    point.SetBranch(d)
        else:
            # ID検索
            point = vrmapi.LAYOUT().GetPoint(int(line[1]))
            if line[2] == "SetBranch":
                point.SetBranch(d)
Exemplo n.º 6
0
def sendStateFile():
    dir = vrmapi.SYSTEM().GetLayoutDir()
    if (os.path.exists(dir + "\\send") == False):
        vrmapi.LOG(dir + "\\send フォルダがありません。")
        return

    s = list()

    # 編成リストを新規編成リストに格納
    tList = vrmapi.LAYOUT().GetTrainList()
    # 新規編成リストから編成を繰り返し取得
    for t in tList:
        # ダミー編成は除外
        if t.GetDummyMode() == False:
            s.append('t\t{0}\t{1:.1f}\n'.format(t.GetID(), t.GetVoltage()))
    s.append('\n')

    # 新規ポイントリストを作成
    pList = list()
    # ポイントリストを新規ポイントリストに格納
    vrmapi.LAYOUT().ListPoint(pList)
    # 新規ポイントリストからポイントを繰り返し取得
    for p in pList:
        # 頭文字「dummy」は対象外
        if p.GetNAME()[0:5] != 'dummy':
            s.append('p\t{0}\t{1}\n'.format(p.GetID(), p.GetBranch()))
    #s.append('\n')

    # 結合
    text = ''.join(s)
    # ファイル出力
    timeText = datetime.now().strftime('%Y%m%d%H%M%S%f')
    path_w = dir + "\\send\\" + timeText + '.txt'
    with open(path_w, mode='w') as f:
        f.write(text)
Exemplo n.º 7
0
def sendSettingFile():
    dir = vrmapi.SYSTEM().GetLayoutDir()
    if (os.path.exists(dir + "\\send") == False):
        vrmapi.LOG(dir + "\\send フォルダがありません。")
        return

    s = list()

    # 編成リストを新規編成リストに格納
    tList = vrmapi.LAYOUT().GetTrainList()
    # 新規編成リストから編成を繰り返し取得
    for t in tList:
        pos = t.GetPosition()
        s.append(
            't\t{0}\t{1}\t{2}\t{3:.0f}\t{4:.0f}\t{5:.0f}\t{6:.0f}\t{7}'.format(
                t.GetID(), t.GetNAME(), t.GetTrainNumber(), pos[0], pos[2],
                pos[1], t.GetRotate(), len(t.GetCarList())))
        if t.GetDummyMode() == True:
            s.append('\tdummy\n')
        else:
            s.append('\n')
    s.append('\n')

    # 新規ポイントリストを作成
    pList = list()
    # ポイントリストを新規ポイントリストに格納
    vrmapi.LAYOUT().ListPoint(pList)
    # 新規ポイントリストからポイントを繰り返し取得
    for p in pList:
        pos = p.GetPosition()
        s.append(
            'p\t{0}\t{1}\t{2}\t{3:.0f}\t{4:.0f}\t{5:.0f}\t{6:.0f}\n'.format(
                p.GetID(), p.GetNAME(), p.GetBranch(), pos[0], pos[2], pos[1],
                p.GetRotate()))
    #s.append('\n')

    # 結合
    text = ''.join(s)
    # ファイル出力
    timeText = datetime.now().strftime('%Y%m%d%H%M%S%f')
    path_w = dir + "\\send\\" + timeText + '.txt'
    with open(path_w, mode='w') as f:
        f.write(text)
        vrmapi.LOG(path_w + " を出力しました。")
Exemplo n.º 8
0
def kill_event(evid):
    """ATENXA式イベントをキャンセル。
    
    ATENXA式のイベントのみキャンセルできます。
    
    Args:
        evid: イベントID
    """
    try:
        obj = _register[evid]._obj
        del _register[evid]
    except KeyError:
        vrmapi.LOG('[ATENXA.EVENT WARNING]不正なイベントID (ID {})'.format(evid))
    obj.ResetEvent(evid)
Exemplo n.º 9
0
def process_ats_event(obj, ev, param):
    """catchイベントを文字列にしてクライアントに送信する。

    VRM-NXのレイアウトスクリプトに記述したvrmevent_userats()から呼ばれる。
    """
    global _clienteventsocket, _clienteventstream

    if ev == 'catch':
        # catchイベントを文字列にしてクライアントに送る。
        s = f'catch {obj.GetID()} {param["trainid"]} {param["dir"]} {param["tire"]}\n'
        #vrmapi.LOG(s)
        if _clienteventstream:
            try:
                _clienteventstream.write(s)
                _clienteventstream.flush()
            except Exception as e:
                vrmapi.LOG(f'eventsocket write: {e}')
                _closeeventsocket()
Exemplo n.º 10
0
def setPower(tra, sw):
    # サウンド変更
    if sw == 0:
        # 再生停止
        tra.SetSoundPlayMode(0)
    else:
        # 常時再生
        tra.SetSoundPlayMode(2)
    #車両数を取得
    len = tra.GetNumberOfCars()
    #車両ごとに処理
    for i in range(0, len):
        #ダミーは対象外
        if tra.GetDummyMode():
            vrmapi.LOG(tra.GetNAME() + " ダミースキップ")
        else:
            # 車両を取得
            car = tra.GetCar(i)
            # 方向幕
            car.SetRollsignLight(sw)
            # 室内灯
            car.SetRoomlight(sw)
            # LED
            car.SetLEDLight(sw)
            # 運転台室内灯
            car.SetCabLight(sw)
            # パンダグラフ個数確認
            for j in range(0, car.GetCountOfPantograph()):
                # パンタグラフ
                car.SetPantograph(j, sw)
            # 先頭車両処理(ifを外して中間連結車も含む)
            #if i == 0:
            # ヘッドライト
            car.SetHeadlight(sw)
            # 最後尾車両処理(ifを外して中間連結車も含む)
            #if i == len - 1:
            # テールライト
            car.SetTaillight(sw)
            # 運転台室内灯
            car.SetCabLight(sw)
            # 蒸気機関車用(テンダーも対象)
            if car.GetCarType() == 1:
                # 煙
                car.SetSmoke(sw)
Exemplo n.º 11
0
def execvrmapi(command):
    """コマンド文字列を解釈し、vrmapiのメソッドを呼ぶ。
    パターンに'.*'が含まれるので長いパターンから短いパターンの順に探す。
    値を返すコマンドのときはvrmapiのメソッドの戻り値を文字列にして返す。
    """
    m = _pat4.search(command)
    if m:
        cmd = f'{m.group(1)}().{m.group(3)}().{m.group(5)}().{m.group(7)}()'

        vrmapi.LOG(f'サーバー未実装: {command}')
        return None

    m = _pat3.search(command)
    if m:
        cmd = f'{m.group(1)}().{m.group(3)}().{m.group(5)}()'

        if cmd == 'LAYOUT().GetATS().ClearUserEventFunction()':
            if m.group(2) != '': return None
            ats = int(m.group(4))
            if m.group(6) != '': return None
            vrmapi.LAYOUT().GetATS(ats).ClearUserEventFunction()
            return None

        elif cmd == 'LAYOUT().GetATS().SetUserEventFunction()':
            if m.group(2) != '': return None
            ats = int(m.group(4))
            name = m.group(6)[1:-1]
            vrmapi.LAYOUT().GetATS(ats).SetUserEventFunction(name)
            return None

        elif cmd == 'LAYOUT().GetPoint().GetBranch()':
            if m.group(2) != '': return ''
            point = int(m.group(4))
            if m.group(6) != '': return ''
            return str(vrmapi.LAYOUT().GetPoint(point).GetBranch())

        elif cmd == 'LAYOUT().GetPoint().SetBranch()':
            if m.group(2) != '': return None
            point = int(m.group(4))
            branch = int(m.group(6))
            vrmapi.LAYOUT().GetPoint(point).SetBranch(branch)
            return None

        elif cmd == 'LAYOUT().GetPoint().SwitchBranch()':
            if m.group(2) != '': return None
            point = int(m.group(4))
            if m.group(6) != '': return None
            vrmapi.LAYOUT().GetPoint(point).SwitchBranch()
            return None

        elif cmd == 'LAYOUT().GetTrain().AutoSpeedCTRL()':
            if m.group(2) != '': return None
            train = int(m.group(4))
            lst = m.group(6).split(',')
            distance = float(lst[0].strip())
            voltage = float(lst[1].strip())
            vrmapi.LAYOUT().GetTrain(train).AutoSpeedCTRL(distance, voltage)
            return None

        elif cmd == 'LAYOUT().GetTrain().GetDirection()':
            if m.group(2) != '': return ''
            train = int(m.group(4))
            if m.group(6) != '': return ''
            return str(vrmapi.LAYOUT().GetTrain(train).GetDirection())

        elif cmd == 'LAYOUT().GetTrain().GetVoltage()':
            if m.group(2) != '': return ''
            train = int(m.group(4))
            if m.group(6) != '': return ''
            return str(vrmapi.LAYOUT().GetTrain(train).GetVoltage())

        elif cmd == 'LAYOUT().GetTrain().SetTimerVoltage()':
            if m.group(2) != '': return None
            train = int(m.group(4))
            lst = m.group(6).split(',')
            sec = float(lst[0].strip())
            voltage = float(lst[1].strip())
            vrmapi.LAYOUT().GetTrain(train).SetTimerVoltage(sec, voltage)
            return None

        elif cmd == 'LAYOUT().GetTrain().SetTrainCode()':
            if m.group(2) != '': return None
            train = int(m.group(4))
            code = int(m.group(6))
            vrmapi.LAYOUT().GetTrain(train).SetTrainCode(code)
            return None

        elif cmd == 'LAYOUT().GetTrain().SetTrainNumber()':
            if m.group(2) != '': return None
            train = int(m.group(4))
            number = m.group(6)[1:-1]
            vrmapi.LAYOUT().GetTrain(train).SetTrainNumber(number)
            return None

        elif cmd == 'LAYOUT().GetTrain().SetVoltage()':
            if m.group(2) != '': return None
            train = int(m.group(4))
            voltage = float(m.group(6))
            vrmapi.LAYOUT().GetTrain(train).SetVoltage(voltage)
            return None

        elif cmd == 'LAYOUT().GetTrain().Turn()':
            if m.group(2) != '': return None
            train = int(m.group(4))
            if m.group(6) != '': return None
            vrmapi.LAYOUT().GetTrain(train).Turn()
            return None

        vrmapi.LOG(f'サーバー未実装: {command}')
        return None

    m = _pat2.search(command)
    if m:
        cmd = f'{m.group(1)}().{m.group(3)}()'

        vrmapi.LOG(f'サーバー未実装: {command}')
        return None

    m = _pat1.search(command)
    if m:
        cmd = f'{m.group(1)}()'

        if cmd == 'AutoSpeedCTRL()':
            lst = m.group(2).split(',')
            distance = float(lst[0].strip())
            voltage = float(lst[1].strip())
            train = _activetrain()
            if train is None: return None
            train.AutoSpeedCTRL(distance, voltage)
            return None

        elif cmd == 'GetDirection()':
            if m.group(2) != '': return ''
            train = _activetrain()
            if train is None: return ''
            return str(train.GetDirection())

        elif cmd == 'GetVoltage()':
            if m.group(2) != '': return ''
            train = _activetrain()
            if train is None: return ''
            return str(train.GetVoltage())

        elif cmd == 'GetID()':
            if m.group(2) != '': return ''
            train = _activetrain()
            if train is None: return ''
            return str(train.GetID())

        elif cmd == 'SetTimerVoltage()':
            lst = m.group(2).split(',')
            sec = float(lst[0].strip())
            voltage = float(lst[1].strip())
            train = _activetrain()
            if train is None: return None
            train.SetTimerVoltage(sec, voltage)
            return None

        elif cmd == 'SetVoltage()':
            voltage = float(m.group(2))
            train = _activetrain()
            if train is None: return None
            train.SetVoltage(voltage)
            return None

        elif cmd == 'Turn()':
            if m.group(2) != '': return None
            train = _activetrain()
            if train is None: return None
            train.Turn()
            return None

        vrmapi.LOG(f'サーバー未実装: {command}')
        return None
Exemplo n.º 12
0
_servercommandsocket.listen(1)
_clientcommandsocket = None
_clientcommandstream = None

# ノンブロッキングモードのイベント用ソケットを用意して接続受付開始
_servereventsocket = socket.socket()
_servereventsocket.setblocking(False)
_servereventsocket.bind(_eventsocketaddress)
_servereventsocket.listen(1)
_clienteventsocket = None
_clienteventstream = None

# VRM-NXにframeイベントの発生を依頼
vrmapi.LAYOUT().SetEventFrame()

vrmapi.LOG(f'{__name__} : ### Startup ###')


def _closecommandsocket():
    global _clientcommandsocket, _clientcommandstream

    if _clientcommandsocket:
        _clientcommandsocket.close()
        _clientcommandsocket = None
        _clientcommandstream = None


def _closeeventsocket():
    global _clienteventsocket, _clienteventstream

    if _clienteventsocket:
Exemplo n.º 13
0
def _dispgui():
    """操作パネル"""
    global _shakemode
    global _fov
    global _depth
    global _fnum
    global _trainlist
    global _tracking_mode
    global _tracking_car
    global _tracking_trainid
    global _tracking_trnlen
    global _tracking_carnum
    global _tracking_relative
    global _tracking_af
    global _fuzzytrack
    global _aemode
    global _aeparam
    IMGUI.Begin("ToruoWin", "撮る夫くん")
    action = False
    action += IMGUI.SliderFloat("zoom", "FOV(ズーム角度)", _fov, 10.0, 135.0)
    action += IMGUI.SliderFloat("focus", "合焦中心", _depth, 0.1, 0.5)
    #if not _aemode[0]:
    action += IMGUI.SliderFloat("fnum", "絞り", _fnum, 2.0, 200.0)
    action += IMGUI.SliderFloat("blur", "ぼけの強さ", _blur, 0.0, 2.0)
    if action:
        _focus()
    IMGUI.Separator()
    if IMGUI.Checkbox("program_ae", "プログラムAE", _aemode):
        _focus()
    IMGUI.SameLine()
    if IMGUI.Checkbox("shake", "手ブレモード", _shakemode):
        setshakemode(_shakemode[0])
    if IMGUI.TreeNode("childbtn",  "保存済み撮る夫くん"):
        if _toruos:
            for i,d in enumerate(_toruos):
                if IMGUI.RadioButton("toruo{}".format(i), "撮る夫くん {}".format(i), _childid, i):
                    jump_toruo(i)
                    # vrmapi.LOG('撮る夫くん {}'.format(i))
        else:
            IMGUI.Text("撮る夫くんは保存されていません")
        if IMGUI.Button("addtoruo", "現在視点を保存"):
            _save_toruo()
        IMGUI.SameLine()
        if IMGUI.Button("deltoruo", "現在の撮る夫くんを削除"):
            del _toruos[_childid[0]]
            _save_config()
        IMGUI.TreePop()

    if IMGUI.TreeNode("target", "追尾モード"):
        IMGUI.Checkbox("trackmode", "追尾モード", _tracking_mode)
        IMGUI.SameLine()
        IMGUI.Checkbox("trackaf", "オートフォーカス", _tracking_af)
        if IMGUI.TreeNode("targettrn", "対象の編成"):
            if IMGUI.Button("trnlist", "編成リストを更新"):
                _refresh_trainlist()
            if IMGUI.RadioButton("notrack", "追尾なし", _tracking_trainid, 0):
                _tracking_car = None
            for i, tid in enumerate(_trainlist['id']):
                if IMGUI.RadioButton("trn{}".format(tid), _trainlist['name'][i], _tracking_trainid, tid):
                    _tracking_carnum[0] = 1
                    _tracking_car = LAYOUT.GetTrain(_tracking_trainid[0]).GetCar(_tracking_carnum[0]-1)
                    _tracking_trnlen = _trainlist['obj'][i].GetNumberOfCars()
                    vrmapi.LOG("[撮る夫くん]追尾対象変更 {}".format(_trainlist['name'][i]))
            if IMGUI.Checkbox("trackfuzzy", "ファジィ追尾", _fuzzytrack):
                _tracking_carnum[0] = int(round(_tracking_carnum[0]))
            if _tracking_trainid[0]:
                if _fuzzytrack[0]:
                    if IMGUI.SliderFloat('carnofuzzy', "ファジィ号車番号", _tracking_carnum, 1.0, _tracking_trnlen):
                        _tracking_car = LAYOUT.GetTrain(_tracking_trainid[0]).GetCar(int(round(_tracking_carnum[0]))-1)
                else:
                    if IMGUI.SliderInt("carno", "号車番号", _tracking_carnum, 1, _tracking_trnlen):
                        _tracking_car = LAYOUT.GetTrain(_tracking_trainid[0]).GetCar(_tracking_carnum[0]-1)
                IMGUI.Text("車体長: {0:.1f}mm".format(vecdistance(_tracking_car.GetLinkPosition(0), _tracking_car.GetLinkPosition(1))))
            IMGUI.SliderFloat("relx", "相対X", _tracking_relative['x'], -150.0, 150.0)
            IMGUI.SliderFloat("rely", "相対Y", _tracking_relative['y'], -50.0, 50.0)
            IMGUI.SliderFloat("relz", "相対Z", _tracking_relative['z'], -50.0, 50.0)
            IMGUI.TreePop()
        IMGUI.SliderFloat("trdist", "追尾距離", _tracking_dist, 100.0, 2500.0)
        IMGUI.Text(str(_tracking_car))
        IMGUI.TreePop()

    if IMGUI.TreeNode("sunpos", "撮影環境設定"):
        IMGUI.Text("太陽位置")
        if IMGUI.SliderFloat('sun_longitude', '経度', _sunpos[0], -180.0, 180.0):
            LAYOUT.SKY().SetSunPos(_sunpos[0][0], _sunpos[1][0])
        if IMGUI.SliderFloat('sun_latiitude', '緯度', _sunpos[1], 0.0, 90.0):
            LAYOUT.SKY().SetSunPos(_sunpos[0][0], _sunpos[1][0])
        IMGUI.TreePop()        
    if IMGUI.TreeNode("details", "詳細設定"):
        IMGUI.Text("AE詳細設定")
        IMGUI.SliderFloat('ae1', 'ぼけ限界FOV', _aeparam['blurfin'], 35.0,135.0)
        IMGUI.SliderFloat('ae2', 'F増加率', _aeparam['ftg'], 0.1,1.0)
        IMGUI.SliderFloat('ae3', 'FOV10でのF', _aeparam['f10'], 1.0, 50.0)
        IMGUI.TreePop()
    IMGUI.Separator()
    if IMGUI.Button("closer", "メニューを閉じる"):
        global _guidisp
        _guidisp = 0
    if DEBUG:
        pos = NXSYS.GetGlobalCameraPos()
        pos_from = pos[:3]
        pos_at = pos[3:]
        IMGUI.Text("From: {}".format(pos_from))
        IMGUI.Text("At  : {}".format(pos_at))
        IMGUI.Text("Dist: {}".format(vecdistance(pos_from, pos_at)))
    IMGUI.End()
Exemplo n.º 14
0
def activate(obj, ev, param):
    """撮る夫くんを有効にするコマンド。
    
    レイアウトオブジェクトのイベントハンドラの先頭に書いてください(ifの中には入れない)::
    
        import vrmapi
        import toruo
        
        def vrmevent(obj,ev,param):
            toruo.activate(obj,ev,param)
            if ev == 'init':
                pass
            
    Args:
        obj:    イベントハンドラが受け取るobj
        ev:     イベントハンドラが受け取るev
        param:  イベントハンドラが受け取るparam
        
    """
    if ev == 'init':
        global _PARENT
        _PARENT = obj
        obj.SetEventFrame(106000)
        obj.SetEventKeyDown('P', 106001)
        _load_config()
        _refresh_trainlist()
        vrmapi.LOG('撮る夫くん(Ver.{}) stand by. {}'.format(__version__, DIRECTORY))
        return
    elif param['eventid'] == _shake_evid:
        # (Afterイベント)
        _update_shake()
        return
    elif ev == 'keydown':
        if param['keycode'] == 'P':
            # GUI表示をON/OFF
            global _guidisp
            _guidisp = (_guidisp+1)%2
        return

    if ev != 'frame':
        return

    if _guidisp:
        _dispgui()
    if not LAYOUT.IsViewGlobal():
        return
    ftime = _updateframetime(param['eventtime'])
    campos = NXSYS.GetGlobalCameraPos()
    global _shake_hr
    global _shake_vt

    # ズームイン
    stat = NXSYS.GetKeyStat('E') + NXSYS.GetKeyStat('W') + NXSYS.GetKeyStat('R') + 3.0
    if stat > 0.0:
        _zoom(-1, ftime)

    # ズームアウト
    stat = NXSYS.GetKeyStat('S') + NXSYS.GetKeyStat('D') + NXSYS.GetKeyStat('F') + 3.0
    if stat > 0.0:
        _zoom(1, ftime)

    # 左回転
    stat = NXSYS.GetKeyStat('W') + NXSYS.GetKeyStat('S') + 2.0
    if stat > 0.0:
        _rotate(campos, -1, ftime)

    # 右回転
    stat = NXSYS.GetKeyStat('R') + NXSYS.GetKeyStat('F') + 2.0
    if stat > 0.0:
        _rotate(campos, 1, ftime)

    # 追尾処理
    istracking = False

    if _tracking_mode[0] and _tracking_car:
        if _fuzzytrack[0]:
            tgtpos = _tracktargetpos_fuzzy(_tracking_trainid[0], _tracking_carnum[0]-1)
        else:
            tgtpos = _getcarworldpos(car=_tracking_car)
        vrmapi.LOG(str(tgtpos))
        dist = vecdistance(campos[0:3], tgtpos)
        if dist < _tracking_dist[0]:
            istracking = True
            campos[3:6] = tgtpos
            if _tracking_af[0]:
                global _depth
                #global _blur
                # Auto Focus (Program Exposure)
                _depth[0] = pow(dist, -0.25)
                #_blur[0] = 2*(135.0-_fov[0])/125.0
                _focus()

    # ブレ計算
    if _shakemode[0]:
        if istracking:
            _shake_hr += _shake_dhr * dRot * ftime
            _shake_vt += _shake_dvt * dRot * ftime
            _rotate(campos, _shake_hr, 1.0)
            _rotatevt(campos, _shake_vt, 1.0)
        else:
            _rotate(campos, _shake_dhr, ftime)
            _rotatevt(campos, _shake_dvt, ftime)
            
    NXSYS.SetGlobalCameraPos(campos)
Exemplo n.º 15
0
def imguiMakeTrain(gui, tr):
    # 編成ID
    strId = str(tr.GetID())
    # 編成内のパラメータを取得
    di = tr.GetDict()

    # 編成名が無ければ新規生成車両とみなす
    if 'pw_ch1' not in di.keys():
        di['pw_ch1'] = [0]
        di['pw_ch2'] = [0]
        di['pw_drl'] = [0]
        di['pw_drr'] = [0]
        di['pw_msg'] = ''
        # 音の初期値を入力
        if obj.GetSoundPlayMode() == 2:
            di['pw_ch2'] = [1]
        vrmapi.LOG("[{0}] {1} が検出されました".format(strId, tr.GetNAME()))

    # 編成名ラジオボタン
    global _activeTrainRdo
    if gui.RadioButton("rdo" + strId, tr.GetTrainNumber(), _activeTrainRdo, tr.GetID()):
        # 編成操作(アクティブ化)
        tr.SetActive()
        tr.SetView()
        # 車両操作対象
        global _activeTrainObj
        _activeTrainObj = tr
    gui.SameLine()

    # 反転ボタン
    # 電圧取得
    vlary = [tr.GetVoltage()]
    if gui.Button('bt2' + strId, "反"):
        # 方向転換
        tr.Turn()
    gui.SameLine()

    # 速度スライドバー
    # スライドバーサイズ調整
    gui.PushItemWidth(100.0)
    if gui.SliderFloat('vl' + strId, '', vlary, 0, 1.0):
        # 電圧反映
        tr.SetVoltage(vlary[0])
    # サイズリセット
    gui.PopItemWidth()
    gui.SameLine()
    # 速度小数点1桁丸めkm/h表示
    gui.Text((str(round(tr.GetSpeed(), 1)) + 'km/h').rjust(9))
    gui.SameLine()

    # 全点灯
    gui.Text(" 全灯")
    gui.SameLine()
    swary = di['pw_ch1']
    # 点灯チェックボックス
    if gui.Checkbox('ch1' + strId, '', swary):
        setPower(tr, swary[0])
    gui.SameLine()

    # サウンド
    gui.Text(" 音")
    gui.SameLine()
    swary = di['pw_ch2']
    # 音チェックボックス
    if gui.Checkbox('ch2' + strId, '', swary):
        # 音操作
        setSound(tr, swary[0])
    gui.SameLine()

    # 扉L
    gui.Text(" 扉LR")
    gui.SameLine()
    swary = di['pw_drl']
    # 扉Lチェックボックス
    if gui.Checkbox('dr0' + strId, '', swary):
        # 扉L操作
        setDoor(tr, swary[0], 0)
    gui.SameLine()

    # 扉R
    #gui.Text("扉R")
    #gui.SameLine()
    swary = di['pw_drr']
    # 扉Rチェックボックス
    if gui.Checkbox('dr1' + strId, '', swary):
        # 扉R操作
        setDoor(tr, swary[0], 1)
    gui.SameLine()

    # 警笛ボタン
    if gui.Button('bt3' + strId, '笛'):
        # 警笛
        tr.PlayHorn(0)
    gui.SameLine()

    # 名前表示
    gui.Text("[{0}] {1} {2}両".format(strId, tr.GetNAME(), len(tr.GetCarList())))
    gui.SameLine()

    # 位置情報を表示
    gui.Text(di['pw_msg'])
Exemplo n.º 16
0
__title__ = "パワーユニットくん Ver.1.5"
__author__ = "Caldia"
__update__  = "2021/05/25"

import vrmapi

# ファイル読み込みの確認用
vrmapi.LOG("import " + __title__)
# ウィンドウ描画フラグ
_drawEnable = True
# アクティブ編成オブジェクト
_activeTrainObj = None
# ラジオボタン用
_activeTrainRdo = [0]

# main
def vrmevent(obj,ev,param):
    global _drawEnable
    if ev == 'init':
        # 初期化
        init()
        # フレームイベント登録
        obj.SetEventFrame()
        # pキー登録
        obj.SetEventKeyDown('P')
    elif ev == 'frame':
        if _drawEnable:
            # ImGui描画
            drawFrame()
    elif ev == 'keydown':
        # ウィンドウ描画のON/OFF