repo_id
stringlengths
4
98
size
int64
611
5.02M
file_path
stringlengths
1
276
content
stringlengths
611
5.02M
shard_id
int64
0
109
quality_score
float32
0.5
1
quality_prediction
int8
1
1
quality_confidence
float32
0.5
1
topic_primary
stringclasses
1 value
topic_group
stringclasses
1 value
topic_score
float32
0.05
1
topic_all
stringclasses
96 values
quality2_score
float32
0.5
1
quality2_prediction
int8
1
1
quality2_confidence
float32
0.5
1
wamekukyouzin/eratohoK
11,768
ERB/TRAIN/COMF/COMF8_アナル舐め.ERB
;クンニ ;------------------------------------------------- ;コマンド名称 ;------------------------------------------------- @COM_NAME8 LOCAL:0 = IS_RIDE(MPLY:0, MTAR:0) ;男性プレイヤーがターゲットに顔面騎乗中 IF LOCAL:0 && !HAS_VAGINA(MPLY:0) LOCALS:0 = 顔騎アナル舐め ;非男性プレイヤーがターゲットに顔面騎乗中 or ターゲットからプレイヤーにフェラ・クンニ・アナル舐め中 ELSEIF LOCAL:0 || SEARCH_EQUIP(11, MTAR:0, MPLY:0) >= 0 || SEARCH_EQUIP(2, MTAR:0, MPLY:0) >= 0 || SEARCH_EQUIP(8, MTAR:0, MPLY:0) >= 0 LOCALS:0 = Aシックスナイン ELSE LOCALS:0 = アナル舐め ENDIF RESULTS:0 = %LOCALS:0%する RESULTS:1 = %LOCALS:0%させられる RESULTS:2 = %LOCALS:0%させる RESULTS:3 = %LOCALS:0%される RESULTS:4 = %LOCALS:0%させる RESULTS:5 = %LOCALS:0%見せつけ ;------------------------------------------------- ;選択可否判定 ;------------------------------------------------- @COM_ABLE8 ;共通部分 CALL COM_ABLE_COMMON(8) SIF RESULT == 0 RETURN 0 ;プレイヤーは最大で1人まで SIF MPLY_NUM <= 0 || MPLY_NUM > 1 RETURN 0 ;ターゲットは最大で1人まで SIF MTAR_NUM <= 0 || MTAR_NUM > 1 RETURN 0 SIF !CAN_LICK_GROIN(MPLY:0 ,MTAR:0) RETURN 0 ;target already getting a rimjob SIF IS_EQUIP_TARGET(MTAR:0, 8) RETURN 0 ;vaginal facesitting is a special case SIF IS_EQUIP_PLAYER(MTAR:0, 101) RETURN 0 RETURN 1 ;------------------------------------------------- ;メイン処理 ;------------------------------------------------- @COM8 ;実行判定 CALL COM_ORDER_COMMON SIF RESULT == 0 RETURN 0 ;●プレイヤーについて処理 DOWNBASE:(MPLY:0):体力 += 120 EXP:(MPLY:0):性技経験値 += 1 SOURCE:(MPLY:0):奉仕 = SERVE_HOUSHI(MPLY:0, 300) SOURCE:(MPLY:0):接触 = 50 SOURCE:(MPLY:0):性行動 = 300 ;主導権に応じた優越・屈従のソース追加 CALL ADD_SOURCE_INITIATIVE_U(MPLY:0, 150, 100) ;奉仕経験値を得られるコマンドのフラグ TCVAR:(MPLY:0):4 = 1 ;膣口へのキス CALL KISS_COMMON(MPLY:0, @"%ANAME(MTAR:0)%のアナル", GET_SITUATION_BY_TRAIN_MODE()) ;●ターゲットについて処理 DOWNBASE:(MTAR:0):体力 += 60 SOURCE:(MTAR:0):液体追加 = 300 SOURCE:(MTAR:0):露出 = 150 SOURCE:(MTAR:0):逸脱 = 50 SOURCE:(MTAR:0):接触 = 50 SOURCE:(MTAR:0):快A = SENSE_HOUSHI(MPLY:0, MTAR:0, 1500) SOURCE:(MTAR:0):性行動 = 300 ;主導権に応じた優越・屈従のソース追加 CALL ADD_SOURCE_INITIATIVE_U(MTAR:0, 150, 0) IF TALENT:(MPLY:0):舌使い TIMES SOURCE:(MTAR:0):快A, 1.50 ENDIF ;主導度変化基準値 TFLAG:49 = 2 ;倒錯度変化基準値 TFLAG:50 = 0 ;レズ・BL経験基準値 TFLAG:51 = 3 RETURN 1 ;------------------------------------------------- ;継続コマンドかどうかを設定 ;------------------------------------------------- @COM_IS_EQUIP8 RETURN 1 ;------------------------------------------------- ;継続状態の処理 ;------------------------------------------------- @COM_EQUIP8(ARG:0) LOCAL:2 = MEQUIP_PLAYER:(ARG:0):0 LOCAL:3 = MEQUIP_TARGET:(ARG:0):0 ;●プレイヤーの処理 DOWNBASE:(LOCAL:2):体力 += 20 EXP:(LOCAL:2):性技経験値 += 1 SOURCE:(LOCAL:2):奉仕 += SERVE_HOUSHI(LOCAL:2, 100) SOURCE:(LOCAL:2):接触 += 25 SOURCE:(LOCAL:2):性行動 += 100 ;奉仕経験値を得られるコマンドのフラグ TCVAR:(LOCAL:2):4 = 1 ;●ターゲットの処理 DOWNBASE:(LOCAL:3):体力 += 10 SOURCE:(LOCAL:3):液体追加 += 150 SOURCE:(LOCAL:3):露出 += 75 SOURCE:(LOCAL:3):逸脱 += 25 SOURCE:(LOCAL:3):接触 += 25 SOURCE:(LOCAL:3):性行動 += 100 IF TALENT:(LOCAL:2):舌使い SOURCE:(LOCAL:3):快A += SENSE_HOUSHI(LOCAL:2, LOCAL:3, 1125) ELSE SOURCE:(LOCAL:3):快A += SENSE_HOUSHI(LOCAL:2, LOCAL:3, 750) ENDIF ;------------------------------------------------- ;継続中の表示 ;------------------------------------------------- @EQUIP_MESSAGE8(ARG:0) RESULTS = %EQUIP_PLAYER_ANAME(ARG:0)%が%EQUIP_TARGET_ANAME(ARG:0)%にアナル舐め中 ;------------------------------------------------- ;継続中の地の文(前文) ;------------------------------------------------- @COM_TEXT_BEFORE_EQUIP8(ARG:0) PRINTFORML %EQUIP_PLAYER_ANAME(ARG:0)%が%EQUIP_TARGET_ANAME(ARG:0)%のアナルを舌で舐めている… ;------------------------------------------------- ;継続を解除したときの地の文 ;------------------------------------------------- @COM_TEXT_RELEASE_EQUIP8(ARG:0) ;------------------------------------------------- ;固有の実行判定 ;------------------------------------------------- @COM_ORDER_PLAYER8(ARG:0) ;実行値の設定 TCVAR:(ARG:0):25 = 90 ;共通部分 CALL COM_ORDER(ARG:0) CALL COM_ORDER_ELEMENT(ARG:0, @"欲望Lv{ABL:(ARG:0):欲望}", ABL:(ARG:0):欲望 * 1) CALL COM_ORDER_ELEMENT(ARG:0, @"奉仕Lv{ABL:(ARG:0):奉仕}", ABL:(ARG:0):奉仕 * 4) LOCAL:0 = GET_PALAMLV(PALAM:(ARG:0):欲情) CALL COM_ORDER_ELEMENT(ARG:0, @"欲情Lv{LOCAL:0}", MIN(LOCAL:0 * 2, 20)) IF TCVAR:(ARG:0):60 CALL COM_ORDER_ELEMENT(ARG:0, "媚薬", 6) ENDIF IF TALENT:(ARG:0):恥じらい CALL COM_ORDER_ELEMENT(ARG:0, "恥じらい", -1) ENDIF IF TALENT:(ARG:0):汚臭鈍感 CALL COM_ORDER_ELEMENT(ARG:0, "汚臭鈍感", 1) ENDIF IF TALENT:(ARG:0):汚臭敏感 CALL COM_ORDER_ELEMENT(ARG:0, "汚臭敏感", -3) ENDIF IF TALENT:(ARG:0):献身的 CALL COM_ORDER_ELEMENT(ARG:0, "献身的", 6) ENDIF IF TALENT:(ARG:0):快感の否定 CALL COM_ORDER_ELEMENT(ARG:0, "快感の否定", -1) ENDIF ;合意 IF !TALENT:(ARG:0):合意 && !TALENT:(ARG:0):親友 CALL COM_ORDER_ELEMENT(ARG:0, "合意なし", -10) ENDIF RETURN 1 ;------------------------------------------------- ;地の文(前文) ;------------------------------------------------- @COM_TEXT_BEFORE8 LOCAL:5 = SEARCH_EQUIP(101, MPLY:0, MTAR:0) LOCAL:6 = SEARCH_EQUIP(102, MPLY:0, MTAR:0) LOCAL:7 = SEARCH_EQUIP(11, MTAR:0, MPLY:0) LOCAL:8 = SEARCH_EQUIP(2, MTAR:0, MPLY:0) LOCAL:9 = SEARCH_EQUIP(101, MTAR:0, MPLY:0) IF TALENT:(MTAR:0):美尻 LOCALS:2 = %STR_BODY("尻:尻肉:長:接触", MTAR:0)%を割り開き、 ELSEIF GET_HIPSIZE(MTAR:0) >= 1 LOCALS:2 = %STR_BODY("尻肉:長:接触", MTAR:0)%をかきわけ、 ELSE LOCALS:2 = ENDIF IF HAS_PENIS(MTAR:0) LOCALS:1 = 竿の付け根のあたりから ELSEIF TALENT:(MTAR:0):体格 == 体格_子供 LOCALS:1 = 色素も沈着していない ELSEIF ABL:(MTAR:0):A感 <= 1 LOCALS:1 = 未だ不慣れな ELSE LOCALS:1 = ENDIF IF GET_INMOU_LEVEL(MTAR:0) >= 2 LOCALS:3 = 菊座近くまで毛の繁った ELSE LOCALS:3 = ENDIF IF CUM_GET_AMOUNT:(MTAR:0):射精部位_アナル > 0 LOCALS:4 = 白濁をこぼしている ELSE LOCALS:4 = ENDIF ;プレイヤーがターゲットに顔面騎乗中かつ男の場合 IF LOCAL:5 >= 0 && !HAS_VAGINA(MPLY:0) SELECTCASE GET_COM_INITIATIVE() ;プレイヤーに主導権 CASE 0 PRINTFORMW %ANAME(MPLY:0)%は%ANAME(MTAR:0)%に自身の玉を舐めさせながら、%ANAME(MTAR:0)%の%LOCALS:2%%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを舐めほぐし%TARGET_STR("た", "てきた")%… ;ターゲットに主導権 CASE 1 PRINTFORMW %ANAME(MTAR:0)%は%ANAME(MPLY:0)%の玉を舐めながら、%LOCALS:2%%ANAME(MPLY:0)%に自身の%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを舐めさせた… ;第三者に主導権 CASEELSE PRINTFORML %ANAME(TFLAG:45)%は%ANAME(MPLY:0)%に%ANAME(MTAR:0)%の菊穴を舐めるように命令した PRINTFORMW %ANAME(MPLY:0)%は%ANAME(MTAR:0)%に自身の玉を舐めさせながら、%ANAME(MTAR:0)%の%LOCALS:2%%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを舐めほぐした… ENDSELECT ;顔面騎乗の地の文をカット IF LOCAL:5 >= 0 MEQUIP_CUT:(LOCAL:5) = 1 ENDIF ;非男性プレイヤーがターゲットに顔面騎乗中 or ターゲットからプレイヤーにフェラ・クンニ中 ELSEIF LOCAL:5 >= 0 || LOCAL:6 >= 0 || LOCAL:7 >= 0 || LOCAL:8 >= 0 IF LOCAL:6 >= 0 LOCALS:0 = アナル ELSEIF LOCAL:7 >= 0 LOCALS:0 = ペニス ELSE LOCALS:0 = 秘唇 ENDIF SELECTCASE GET_COM_INITIATIVE() ;プレイヤーに主導権 CASE 0 PRINTFORMW %ANAME(MPLY:0)%は%ANAME(MTAR:0)%に自身の%LOCALS:0%を舐めさせながら、%ANAME(MTAR:0)%の%LOCALS:2%%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを舐めほぐし%TARGET_STR("た", "てきた")%… ;ターゲットに主導権 CASE 1 PRINTFORMW %ANAME(MTAR:0)%は%ANAME(MPLY:0)%の%LOCALS:0%を舐めながら、%LOCALS:2%%ANAME(MPLY:0)%に自身の%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを舐めさせた… ;第三者に主導権 CASEELSE PRINTFORML %ANAME(TFLAG:45)%は%ANAME(MPLY:0)%と%ANAME(MTAR:0)%にシックスナインの体勢で絡み合うように命令した PRINTFORMW %ANAME(MPLY:0)%は%ANAME(MTAR:0)%に自身の%LOCALS:0%を舐めさせながら、%ANAME(MTAR:0)%の%LOCALS:2%%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを舐めほぐした… ENDSELECT ;顔面騎乗・フェラ・クンニの地の文をカット IF LOCAL:5 >= 0 MEQUIP_CUT:(LOCAL:5) = 1 ENDIF IF LOCAL:6 >= 0 MEQUIP_CUT:(LOCAL:6) = 1 ENDIF IF LOCAL:7 >= 0 MEQUIP_CUT:(LOCAL:7) = 1 ENDIF IF LOCAL:8 >= 0 MEQUIP_CUT:(LOCAL:8) = 1 ENDIF ;ターゲットからプレイヤーに顔面騎乗中 ELSEIF LOCAL:8 >= 0 SELECTCASE GET_COM_INITIATIVE() ;プレイヤーに主導権 CASE 0 PRINTFORMW %ANAME(MPLY:0)%は%ANAME(MTAR:0)%を顔の上に跨がらせたまま、下から%ANAME(MTAR:0)%の%LOCALS:2%%LOCALS:3%%LOCALS:4%アナルを貪るように舐め上げ%TARGET_STR("た", "てきた")%… ;ターゲットに主導権 CASE 1 PRINTFORMW %ANAME(MTAR:0)%は%ANAME(MPLY:0)%の顔に跨ったまま、%LOCALS:2%グリグリと腰を押し付けて自身の%LOCALS:3%%LOCALS:4%アナルを舐めさせた… ;第三者に主導権 CASEELSE PRINTFORML %ANAME(TFLAG:45)%は%ANAME(MPLY:0)%に%ANAME(MTAR:0)%の菊穴を舐めるように命令した PRINTFORMW %ANAME(MPLY:0)%は%ANAME(MTAR:0)%を顔の上に跨がらせたまま、下から%ANAME(MTAR:0)%の%LOCALS:2%%LOCALS:3%%LOCALS:4%アナルを舐め上げた… ENDSELECT ;顔面騎乗の地の文をカットする MEQUIP_CUT:(LOCAL:8) = 1 ;プレイヤーが拘束中 ELSEIF IS_BIND(MPLY:0) SELECTCASE GET_COM_INITIATIVE() ;プレイヤーに主導権 CASE 0 PRINTFORMW %ANAME(MPLY:0)%は%ANAME(MTAR:0)%の%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを顔に押し当てさせると、%LOCALS:2%舌で激しく舐め回し%TARGET_STR("た", "てきた")%… ;ターゲットに主導権 CASE 1 PRINTFORMW %ANAME(MTAR:0)%は%LOCALS:2%身動きの取れない%ANAME(MPLY:0)%の口に%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを押し付け、舐めさせ奉仕させた… ;第三者に主導権 CASEELSE PRINTFORML %ANAME(TFLAG:45)%は%ANAME(MTAR:0)%に対して、%ANAME(MPLY:0)%に菊穴を舐めさせるように命令した PRINTFORMW %ANAME(MTAR:0)%は%LOCALS:2%身動きの取れない%ANAME(MPLY:0)%の口に%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを押し付け、舐めさせた… ENDSELECT ELSE SELECTCASE GET_COM_INITIATIVE() ;プレイヤーに主導権 CASE 0 PRINTFORMW %ANAME(MPLY:0)%は%ANAME(MTAR:0)%の%LOCALS:2%%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを舌で舐め上げ%TARGET_STR("た", "てきた")%… ;ターゲットに主導権 CASE 1 IF GETBIT(TALENT:(MTAR:0):淫乱系, 素質_淫乱_サド) LOCALS:2 = サディステックな笑みを浮かべながら、 ELSEIF GETBIT(TALENT:(MTAR:0):淫乱系, 素質_淫乱_淫乱) LOCALS:2 = 恍惚とした表情を浮かべながら、 ENDIF PRINTFORMW %ANAME(MTAR:0)%は%LOCALS:2%%ANAME(MPLY:0)%の口に%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを押し付け、舐めさせ奉仕させた… ;第三者に主導権 CASEELSE PRINTFORML %ANAME(TFLAG:45)%は%ANAME(MPLY:0)%に%ANAME(MTAR:0)%の菊穴を舐めるように命令した PRINTFORMW %ANAME(MPLY:0)%は%ANAME(MTAR:0)%の%LOCALS:2%%LOCALS:1%%LOCALS:3%%LOCALS:4%アナルを舌で舐め上げた… ENDSELECT ENDIF IF CUM_CUR_AMOUNT:(MTAR:0):射精部位_アナル PRINTFORM %SPLIT_RAND("熱い/粘つく/濃厚な/新鮮な", 1)%精液が IF ABL:(MPLY:0):精愛 >= 4 PRINTFORML %SPLIT_RAND("精液好きの/精愛味覚を得た/精液に飢えた", 1)%%ANAME(MPLY:0)%の口に滴ると、%PRONOUN(MPLY:0)%は悦びの呻き声を漏らした… ELSE PRINTFORML %ANAME(MPLY:0)%の口に滴るが、%PRONOUN(MPLY:0)%は奉仕を余儀なくされた… ENDIF ;target eats 1/4th + 3 cum, up to 20 LOCAL = LIMIT(MIN(((CUM_CUR_AMOUNT:(MTAR:0):射精部位_アナル / 4) + 3), CUM_CUR_AMOUNT:(MTAR:0):射精部位_アナル) , 0, 20) CUM_CUR_AMOUNT:(MTAR:0):射精部位_アナル -= LOCAL CUM_CUR_AMOUNT:(MPLY:0):射精部位_口 += LOCAL SIF CUM_CUR_AMOUNT:(MTAR:0):射精部位_アナル == 0 PRINTFORML %ANAME(MTAR:0)%の%STR_BODY("アナル", MPLY:0)%の精液は全て%ANAME(MPLY:0)%が飲み干した ;Cumlove exp increases by amount of cum EXP:(MPLY:0):精愛経験値 += LOCAL ;Swallowing exp SIF ABL:(MPLY:0):精愛 >= 4 EXP:(MPLY:0):口内射精経験 ++ WAIT ENDIF ;-------------------------------------------------------- ;地の文(パラメータ・刻印変動後) ;-------------------------------------------------------- @COM_TEXT_LAST8 IF (MTAR:0 != MASTER || CONFIG:441) && !IS_ANIMAL(MTAR:0) LOCAL:2 = CUP:(MTAR:0):快A IF TCVAR:(MTAR:0):52 ;気絶中 PRINTFORML %ANAME(MTAR:0)%はアナルを舐め上げられるたびに、ビクビクと体を震わせている ELSEIF LOCAL:2 < 300 PRINTFORML %ANAME(MTAR:0)%のアナルは硬く閉じたままだ。快楽を感じるにはもう少しかかるかもしれない ELSEIF LOCAL:2 < 1000 PRINTFORML %ANAME(MTAR:0)%はアナル舐めの刺激にじっと耐えているものの、確実に感じてきているようだ ELSEIF LOCAL:2 < 3000 PRINTFORM 敏感な穴を舐められると感じるのか、%ANAME(MTAR:0)%は IF TALENT:(MTAR:0):恥じらい PRINT 羞恥に頬を赤く染め手で自分の口を抑えて声が出るのをこらえている ELSEIF TALENT:(MTAR:0):解放 || TALENT:(MTAR:0):快感に素直 PRINTL 熱い吐息を吐きながら快楽に身をゆだねている ELSEIF TALENT:(MTAR:0):抑圧 || TALENT:(MTAR:0):孤高 || TALENT:(MTAR:0):快感の否定 PRINTL 快楽を否定するように首を振って耐えている ELSE PRINTL 腰をくねらせながらわずかに小さく吐息を漏らした ENDIF ELSEIF LOCAL:2 < 6000 PRINTFORML %ANAME(MTAR:0)%の菊穴を舌でねぶり回してやると%ANAME(MTAR:0)%は可愛らしい声を漏らしながらがくがくと身体を揺らした ELSEIF LOCAL:2 < 10000 PRINTFORML %ANAME(MTAR:0)%は明らかな快楽の声をあげ、無意識にこちらの頭を手で押さえてさらにその部分を押し付けてきた ELSE IF TALENT:(MTAR:0):A敏感 PRINTFORML %ANAME(MTAR:0)%は敏感なアナルへの責めに激しく身もだえし、あられも無い声を張り上げ続けた ELSE PRINTFORML %ANAME(MTAR:0)%はアナルへの刺激に激しい喘ぎ声を上げながら悶え続けた ENDIF ENDIF IF TALENT:(MTAR:0):美尻 PRINTFORML %STR_BODY("尻肉:長:外見", MTAR:0)%がふるふると震えている…… ELSEIF GET_HIPSIZE(LOCAL:1) >= 1 PRINTFORML %STR_BODY("尻肉:長:外見", MTAR:0)%がふるふると震えている…… ENDIF ENDIF ;------------------------------------------------- ;コマンド区分 ;------------------------------------------------- @COM_AVAILABLE_WHEN8 RETURN コマンド_ウフフ ;-------------------- ;性嗜好用関数 ;-------------------- @COM_PREFERENCE_PLAYER_8() RETURN POWER(2, 性的嗜好_奉仕したい) @COM_PREFERENCE_TARGET_8() RETURN POWER(2, 性的嗜好_奉仕されたい) @COM_STACK_SPERM_MTAR_TO_MPLY_8() RETURN 射精部位_顔
0
0.717372
1
0.717372
game-dev
MEDIA
0.782256
game-dev
0.735807
1
0.735807
captainys/YSFLIGHT
7,278
src/sounddll/linux-pulseaudio/fsairsounddll.cpp
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include "../fsairsoundenum.h" #include "../yswavfile/yswavfile.h" #include "yspulseaudio.h" YsPulseAudioContext *ysPaContext=NULL; YsPulseAudioWavPlayer *ysPaEnginePlayer=NULL; YsPulseAudioWavPlayer *ysPaGunPlayer=NULL; YsPulseAudioWavPlayer *ysPaAlarmPlayer=NULL; YsPulseAudioWavPlayer *ysPaOneTimePlayer=NULL; // Make sure to call WriteData in FsSoundDllKeepPlaying(void) function and // call Stop in FsSoundDllStopAll(void) function. //////////////////////////////////////////////////////////// class FsSoundStatus { public: const char *vehicleName; FSSND_ENGINETYPE engineType; int numEngine; double enginePower; FSSND_MACHINEGUNTYPE machineGunType; FSSND_ALARMTYPE alarmType; FSSND_ONETIMETYPE oneTimeType; FsSoundStatus(); void Initialize(void); }; FsSoundStatus::FsSoundStatus() { Initialize(); } void FsSoundStatus::Initialize(void) { vehicleName=""; engineType=FSSND_ENGINE_SILENT; numEngine=0; enginePower=0.0; machineGunType=FSSND_MACHINEGUN_SILENT; alarmType=FSSND_ALARM_SILENT; oneTimeType=FSSND_ONETIME_SILENT; } //////////////////////////////////////////////////////////// static YSBOOL fsSoundMasterSwitch=YSTRUE; static YSBOOL fsSoundEnvironmentalSwitch=YSTRUE; static YSBOOL fsSoundOneTimeSwitch=YSTRUE; static YsWavFile jetWav[10],afterBurnerWav,propWav[10]; static YsWavFile machineGunWav[FSSND_NUM_MACHINEGUNTYPE]; static YsWavFile alarmWav[FSSND_NUM_ALARMTYPE]; static YsWavFile oneTimeWav[FSSND_NUM_ONETIMETYPE]; static FsSoundStatus sndStatus; extern "C" void FsSoundDllInitialize(void) { ysPaContext=new YsPulseAudioContext; ysPaEnginePlayer=new YsPulseAudioWavPlayer(ysPaContext,"YSFLIGHT_Engine_Sound"); ysPaGunPlayer=new YsPulseAudioWavPlayer(ysPaContext,"YSFLIGHT_Gun_Sound"); ysPaAlarmPlayer=new YsPulseAudioWavPlayer(ysPaContext,"YSFLIGHT_Alarm_Sound"); ysPaOneTimePlayer=new YsPulseAudioWavPlayer(ysPaContext,"YSFLIGHT_OneTime_Sound"); jetWav[0].LoadWav("sound/engine0.wav"); jetWav[1].LoadWav("sound/engine1.wav"); jetWav[2].LoadWav("sound/engine2.wav"); jetWav[3].LoadWav("sound/engine3.wav"); jetWav[4].LoadWav("sound/engine4.wav"); jetWav[5].LoadWav("sound/engine5.wav"); jetWav[6].LoadWav("sound/engine6.wav"); jetWav[7].LoadWav("sound/engine7.wav"); jetWav[8].LoadWav("sound/engine8.wav"); jetWav[9].LoadWav("sound/engine9.wav"); propWav[0].LoadWav("sound/prop0.wav"); propWav[1].LoadWav("sound/prop1.wav"); propWav[2].LoadWav("sound/prop2.wav"); propWav[3].LoadWav("sound/prop3.wav"); propWav[4].LoadWav("sound/prop4.wav"); propWav[5].LoadWav("sound/prop5.wav"); propWav[6].LoadWav("sound/prop6.wav"); propWav[7].LoadWav("sound/prop7.wav"); propWav[8].LoadWav("sound/prop8.wav"); propWav[9].LoadWav("sound/prop9.wav"); afterBurnerWav.LoadWav("sound/burner.wav"); machineGunWav[(int)FSSND_MACHINEGUN_MACHINEGUN].LoadWav("sound/gun.wav"); alarmWav[(int)FSSND_ALARM_STALL].LoadWav("sound/stallhorn.wav"); alarmWav[(int)FSSND_ALARM_MISSILE].LoadWav("sound/warning.wav"); alarmWav[(int)FSSND_ALARM_TERRAIN].LoadWav("sound/gearhorn.wav"); oneTimeWav[(int)FSSND_ONETIME_DAMAGE].LoadWav("sound/damage.wav"); oneTimeWav[(int)FSSND_ONETIME_MISSILE].LoadWav("sound/missile.wav"); oneTimeWav[(int)FSSND_ONETIME_BANG].LoadWav("sound/bang.wav"); oneTimeWav[(int)FSSND_ONETIME_BLAST].LoadWav("sound/blast.wav"); oneTimeWav[(int)FSSND_ONETIME_TOUCHDWN].LoadWav("sound/touchdwn.wav"); oneTimeWav[(int)FSSND_ONETIME_HIT].LoadWav("sound/hit.wav"); oneTimeWav[(int)FSSND_ONETIME_BLAST2].LoadWav("sound/blast2.wav"); oneTimeWav[(int)FSSND_ONETIME_GEARUP].LoadWav("sound/retractldg.wav"); oneTimeWav[(int)FSSND_ONETIME_GEARDOWN].LoadWav("sound/extendldg.wav"); oneTimeWav[(int)FSSND_ONETIME_BOMBSAWAY].LoadWav("sound/bombsaway.wav"); oneTimeWav[(int)FSSND_ONETIME_ROCKET].LoadWav("sound/rocket.wav"); oneTimeWav[(int)FSSND_ONETIME_NOTICE].LoadWav("sound/notice.wav"); sndStatus.Initialize(); } extern "C" void FsSoundDllTerminate(void) { delete ysPaEnginePlayer; delete ysPaGunPlayer; delete ysPaAlarmPlayer; delete ysPaOneTimePlayer; delete ysPaContext; } extern "C" void FsSoundDllSetMasterSwitch(YSBOOL sw) { fsSoundMasterSwitch=sw; } extern "C" void FsSoundDllSetEnvironmentalSwitch(YSBOOL sw) { fsSoundEnvironmentalSwitch=sw; } extern "C" void FsSoundDllSetOneTimeSwitch(YSBOOL sw) { fsSoundOneTimeSwitch=sw; } extern "C" void FsSoundDllStopAll(void) { ysPaEnginePlayer->Stop(); ysPaGunPlayer->Stop(); ysPaAlarmPlayer->Stop(); ysPaOneTimePlayer->Stop(); } extern "C" void FsSoundDllSetVehicleName(const char vehicleName[]) { sndStatus.vehicleName=vehicleName; } extern "C" void FsSoundDllSetEngine(FSSND_ENGINETYPE engineType,int numEngine,const double power) { sndStatus.engineType=engineType; sndStatus.numEngine=numEngine; sndStatus.enginePower=power; } extern "C" void FsSoundDllSetMachineGun(FSSND_MACHINEGUNTYPE machineGunType) { sndStatus.machineGunType=machineGunType; } extern "C" void FsSoundDllSetAlarm(FSSND_ALARMTYPE alarmType) { sndStatus.alarmType=alarmType; } extern "C" void FsSoundDllSetOneTime(FSSND_ONETIMETYPE oneTimeType) { if(YSTRUE==fsSoundMasterSwitch && YSTRUE==fsSoundOneTimeSwitch && NULL!=ysPaOneTimePlayer) { if(FSSND_ONETIME_SILENT!=oneTimeType) { ysPaOneTimePlayer->Stop(); } ysPaOneTimePlayer->Play(&oneTimeWav[(int)oneTimeType]); sndStatus.oneTimeType=oneTimeType; } } extern "C" void FsSoundDllKeepPlaying(void) { if(YSTRUE==fsSoundMasterSwitch && NULL!=ysPaContext) { ysPaContext->KeepPlaying(); } if(YSTRUE==fsSoundMasterSwitch && YSTRUE==fsSoundOneTimeSwitch) { // Write data for all streams >> if(NULL!=ysPaOneTimePlayer) { ysPaOneTimePlayer->WriteData(YSFALSE); } // << Write data for all streams } if(YSTRUE==fsSoundMasterSwitch && YSTRUE==fsSoundEnvironmentalSwitch) { // Write data for all streams >> if(NULL!=ysPaEnginePlayer) { ysPaEnginePlayer->WriteData(YSTRUE); } if(NULL!=ysPaGunPlayer) { ysPaGunPlayer->WriteData(YSTRUE); } if(NULL!=ysPaAlarmPlayer) { ysPaAlarmPlayer->WriteData(YSTRUE); } // << Write data for all streams if(FSSND_MACHINEGUN_SILENT!=sndStatus.machineGunType) { ysPaGunPlayer->Play(&machineGunWav[(int)sndStatus.machineGunType]); } else { ysPaGunPlayer->Stop(); } if(FSSND_ALARM_SILENT!=sndStatus.alarmType) { ysPaAlarmPlayer->Play(&alarmWav[(int)sndStatus.alarmType]); } else { ysPaAlarmPlayer->Stop(); } if(FSSND_ENGINE_SILENT!=sndStatus.engineType) { YsWavFile *wavToPlay=NULL; int level=(int)(sndStatus.enginePower*10.0); if(level<0) { level=0; } else if(9<level) { level=9; } switch(sndStatus.engineType) { case FSSND_ENGINE_SILENT: ysPaEnginePlayer->Stop(); break; case FSSND_ENGINE_CAR: case FSSND_ENGINE_SHIP: break; case FSSND_ENGINE_JETNORMAL: wavToPlay=&jetWav[level]; break; case FSSND_ENGINE_JETAFTERBURNER: wavToPlay=&afterBurnerWav; break; case FSSND_ENGINE_PROPELLER: case FSSND_ENGINE_TURBOPROP: case FSSND_ENGINE_HELICOPTER: wavToPlay=&propWav[level]; break; } if(NULL!=wavToPlay) { ysPaEnginePlayer->Play(wavToPlay); } } } }
0
0.558403
1
0.558403
game-dev
MEDIA
0.869862
game-dev,audio-video-media
0.872069
1
0.872069
JasonTheKitten/ocreloaded
2,635
projects/Minecraft/src/main/java/li/cil/ocreloaded/minecraft/client/renderer/entity/AmbientOcclusionCalculator.java
package li.cil.ocreloaded.minecraft.client.renderer.entity; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.BlockAndTintGetter; import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.block.state.BlockState; public class AmbientOcclusionCalculator { final float[] brightness = new float[4]; final int[] lightmap = new int[4]; public void calculate(BlockAndTintGetter blockView, BlockState state, BlockPos pos, Direction face) { BlockPos[] cornerOffsets = getCornerOffsets(face); for (int i = 0; i < 4; i++) { BlockPos cornerPos = pos.offset(cornerOffsets[i]); BlockState neighborState = blockView.getBlockState(cornerPos); float cornerBrightness = getShadeBrightness(blockView, neighborState, cornerPos); int cornerLightmap = getLightColor(blockView, neighborState, cornerPos); brightness[i] = cornerBrightness; lightmap[i] = cornerLightmap; } } private BlockPos[] getCornerOffsets(Direction face) { return switch (face) { case UP -> new BlockPos[]{ new BlockPos(-1, 0, -1), new BlockPos(1, 0, -1), new BlockPos(1, 0, 1), new BlockPos(-1, 0, 1) }; case DOWN -> new BlockPos[]{ new BlockPos(-1, 0, -1), new BlockPos(1, 0, -1), new BlockPos(1, 0, 1), new BlockPos(-1, 0, 1) }; case NORTH -> new BlockPos[]{ new BlockPos(-1, -1, 0), new BlockPos(1, -1, 0), new BlockPos(1, 1, 0), new BlockPos(-1, 1, 0) }; case SOUTH -> new BlockPos[]{ new BlockPos(-1, -1, 0), new BlockPos(1, -1, 0), new BlockPos(1, 1, 0), new BlockPos(-1, 1, 0) }; case EAST -> new BlockPos[]{ new BlockPos(0, -1, -1), new BlockPos(0, -1, 1), new BlockPos(0, 1, 1), new BlockPos(0, 1, -1) }; case WEST -> new BlockPos[]{ new BlockPos(0, -1, -1), new BlockPos(0, -1, 1), new BlockPos(0, 1, 1), new BlockPos(0, 1, -1) }; default -> new BlockPos[]{}; }; } private float getShadeBrightness(BlockAndTintGetter blockView, BlockState state, BlockPos pos) { if (state.isSolidRender(blockView, pos)) { return 0.2f; } int lightBlocking = state.getLightBlock(blockView, pos); if (lightBlocking > 0) { return 1.0f - (lightBlocking / 15.0f); } return 1.0f; } private int getLightColor(BlockAndTintGetter blockView, BlockState state, BlockPos pos) { return blockView.getBrightness(LightLayer.BLOCK, pos) << 20 | blockView.getBrightness(LightLayer.SKY, pos) << 4; } }
0
0.922367
1
0.922367
game-dev
MEDIA
0.729346
game-dev,graphics-rendering
0.944387
1
0.944387
tgstation/TerraGov-Marine-Corps
1,568
code/modules/mob/living/carbon/xenomorph/castes/crusher/crusher.dm
/mob/living/carbon/xenomorph/crusher caste_base_type = /datum/xeno_caste/crusher name = "Crusher" desc = "A huge alien with an enormous armored head crest." icon = 'icons/Xeno/castes/crusher.dmi' icon_state = "Crusher Walking" bubble_icon = "alienleft" health = 300 maxHealth = 300 plasma_stored = 200 tier = XENO_TIER_THREE upgrade = XENO_UPGRADE_NORMAL drag_delay = 6 //pulling a big dead xeno is hard mob_size = MOB_SIZE_BIG buckle_flags = CAN_BUCKLE pixel_x = -16 pixel_y = -3 /mob/living/carbon/xenomorph/crusher/handle_special_state() if(is_charging >= CHARGE_ON) icon_state = "[xeno_caste.caste_name][(xeno_flags & XENO_ROUNY) ? " rouny" : ""] Charging" return TRUE return FALSE /mob/living/carbon/xenomorph/crusher/handle_special_wound_states(severity) . = ..() if(is_charging >= CHARGE_ON) return "wounded_charging_[severity]" /mob/living/carbon/xenomorph/crusher/buckle_mob(mob/living/buckling_mob, force = FALSE, check_loc = TRUE, lying_buckle = FALSE, hands_needed = 0, target_hands_needed = 0, silent) if(!force)//crushers should be overriden by runners return FALSE return ..() /mob/living/carbon/xenomorph/crusher/can_mount(mob/living/user, target_mounting = FALSE) . = ..() if(!target_mounting) user = pulling if(!isxeno(user)) return FALSE var/mob/living/carbon/xenomorph/grabbed = user if(grabbed.incapacitated() || !(grabbed.xeno_caste.can_flags & CASTE_CAN_RIDE_CRUSHER)) return FALSE return TRUE /mob/living/carbon/xenomorph/crusher/resisted_against(datum/source) user_unbuckle_mob(source, source)
0
0.932556
1
0.932556
game-dev
MEDIA
0.994148
game-dev
0.918844
1
0.918844
Ayfri/Kore
1,587
kore/src/main/kotlin/io/github/ayfri/kore/features/itemmodifiers/functions/ExplorationMap.kt
package io.github.ayfri.kore.features.itemmodifiers.functions import io.github.ayfri.kore.arguments.types.TaggedResourceLocationArgument import io.github.ayfri.kore.features.itemmodifiers.ItemModifier import io.github.ayfri.kore.features.predicates.PredicateAsList import io.github.ayfri.kore.generated.Tags import io.github.ayfri.kore.generated.arguments.types.MapDecorationTypeArgument import kotlinx.serialization.Serializable /** * Converts an empty map into an explorer map leading to a nearby structure. Mirrors * vanilla `minecraft:exploration_map`. * * Docs: https://kore.ayfri.com/docs/item-modifiers */ @Serializable data class ExplorationMap( override var conditions: PredicateAsList? = null, @Serializable(TaggedResourceLocationArgument.TaggedResourceLocationUnPrefixedSerializer::class) var destination: Tags.Worldgen.Structure? = null, var decoration: MapDecorationTypeArgument? = null, var zoom: Int? = null, var searchRadius: Int? = null, var skipExistingChunks: Boolean? = null, ) : ItemFunction() fun ItemModifier.explorationMap( destination: Tags.Worldgen.Structure, decoration: MapDecorationTypeArgument? = null, zoom: Int? = null, searchRadius: Int? = null, skipExistingChunks: Boolean? = null, block: ExplorationMap.() -> Unit = {}, ) { modifiers += ExplorationMap( destination = destination, decoration = decoration, zoom = zoom, searchRadius = searchRadius, skipExistingChunks = skipExistingChunks ).apply(block) } fun ItemModifier.explorationMap(block: ExplorationMap.() -> Unit) { modifiers += ExplorationMap().apply(block) }
0
0.807103
1
0.807103
game-dev
MEDIA
0.895439
game-dev
0.825644
1
0.825644
cryfs/cryfs
1,246
src/cryfs/impl/config/CryConfigConsole.h
#pragma once #ifndef MESSMER_CRYFS_SRC_CONFIG_CRYCONFIGCONSOLE_H #define MESSMER_CRYFS_SRC_CONFIG_CRYCONFIGCONSOLE_H #include <cpp-utils/pointer/unique_ref.h> #include <cpp-utils/io/Console.h> #include <boost/optional.hpp> namespace cryfs { class CryConfigConsole final { public: CryConfigConsole(std::shared_ptr<cpputils::Console> console); CryConfigConsole(CryConfigConsole &&rhs) = default; std::string askCipher(); uint32_t askBlocksizeBytes(); bool askMissingBlockIsIntegrityViolation(); static constexpr const char *DEFAULT_CIPHER = "xchacha20-poly1305"; static constexpr uint32_t DEFAULT_BLOCKSIZE_BYTES = 16 * 1024; // 16KB static constexpr uint32_t DEFAULT_MISSINGBLOCKISINTEGRITYVIOLATION = false; private: bool _checkUseDefaultSettings(); std::string _askCipher() const; bool _showWarningForCipherAndReturnIfOk(const std::string &cipherName) const; uint32_t _askBlocksizeBytes() const; bool _askMissingBlockIsIntegrityViolation() const; std::shared_ptr<cpputils::Console> _console; boost::optional<bool> _useDefaultSettings; DISALLOW_COPY_AND_ASSIGN(CryConfigConsole); }; } #endif
0
0.708226
1
0.708226
game-dev
MEDIA
0.619216
game-dev
0.541326
1
0.541326
TeamWizardry/Wizardry
4,629
src/main/java/com/teamwizardry/wizardry/common/world/trickery/ChunkGeneratorTorikki.java
package com.teamwizardry.wizardry.common.world.trickery; import com.teamwizardry.wizardry.api.util.RandUtil; import com.teamwizardry.wizardry.common.entity.EntityFairy; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Blocks; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.IChunkGenerator; import net.minecraft.world.gen.NoiseGeneratorOctaves; import net.minecraft.world.gen.NoiseGeneratorPerlin; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.*; /** * Created by Demoniaque44 */ public class ChunkGeneratorTorikki implements IChunkGenerator { protected static final IBlockState AIR = Blocks.AIR.getDefaultState(); protected static final IBlockState DIRT = Blocks.DIRT.getDefaultState(); protected static final IBlockState BEDROCK = Blocks.BEDROCK.getDefaultState(); //protected static final IBlockState TOR_CRYSTAL = figure out how to do this.getDefaultState(); private NoiseGeneratorPerlin noise; private NoiseGeneratorOctaves lperlinNoise1; private NoiseGeneratorOctaves lperlinNoise2; private World world; private final Random rand; public ChunkGeneratorTorikki(World worldIn) { this.world = worldIn; this.rand= new Random(world.getSeed()); this.noise = new NoiseGeneratorPerlin(RandUtil.random,4); this.lperlinNoise1 = new NoiseGeneratorOctaves(this.rand, 16); this.lperlinNoise2 = new NoiseGeneratorOctaves(this.rand, 16); } public ChunkGeneratorTorikki(World world, long seed) { this.world = world; rand = new Random(world.getSeed()); noise = new NoiseGeneratorPerlin(rand, 4); } private boolean isChunkCenter(int chunkX, int chunkZ) { long s2 = ((chunkX + world.getSeed() + 337) * 947) + chunkZ * 719L; Random rand = new Random(s2); rand.nextFloat(); return rand.nextFloat() < .3f; } private Random getRandomForChunk(int chunkX, int chunkZ) { long s2 = ((chunkX + world.getSeed() + 13) * 314) + chunkZ * 17L; Random rand = new Random(s2); rand.nextFloat(); return rand; } /** * ok so * this is supposed to work by genning everything below 128 * and then mirroring it over y - 128 * y = y > 128 ? 256 - y : y is the gud code * idk how to make it work */ //0-15 for local, 16*chunk + 0-15 for noise private void generate(int chunkX, int chunkZ, ChunkPrimer primer) { //go through x for (int locX = 0; locX < 16; locX++) { //go through y (irrelevant of chunk location) for (int locY = 0; locY < 256; locY++) { //and now for z for (int locZ = 0; locZ < 16; locZ++) { if ((locY <= 64 && locY > 1) || (locY > 192 && locY < 255)) { primer.setBlockState(locX, locY, locZ, DIRT); } else if (locY == 1 || locY == 255) { primer.setBlockState(locX, locY, locZ, BEDROCK); } } //if the noise <1, air, else torikki Grass? } } //mirroring! for (int locX = 0; locX < 16; locX++) { for (int locY = 65; locY < 128; locY++) { for (int locZ = 0; locZ < 16; locZ++) { if(.5 <noise.getValue(chunkZ, chunkX)){ primer.setBlockState(locX,locY,locZ,DIRT); } } } } } @Nonnull @Override public Chunk generateChunk(int x, int z) { this.rand.setSeed((long)x * 341873128712L + (long)z * 132897987541L); ChunkPrimer chunkprimer = new ChunkPrimer(); generate(x, z, chunkprimer); Chunk chunk = new Chunk(world, chunkprimer, x, z); byte[] biomeArray = chunk.getBiomeArray(); for (int i = 0; i < biomeArray.length; ++i) { biomeArray[i] = (byte) 42; } chunk.generateSkylightMap(); return chunk; } @Override public void populate(int x, int z) { } @Override public boolean generateStructures(@Nonnull Chunk chunkIn, int x, int z) { return false; } @Nonnull @Override public List<Biome.SpawnListEntry> getPossibleCreatures(@Nonnull EnumCreatureType creatureType, @Nonnull BlockPos pos) { ArrayList<Biome.SpawnListEntry> list = new ArrayList<>(); list.add(new Biome.SpawnListEntry(EntityFairy.class, 1, 1, 3)); return list; } @Nullable @Override public BlockPos getNearestStructurePos(@Nonnull World worldIn, @Nonnull String structureName, @Nonnull BlockPos position, boolean findUnexplored) { return null; } @Override public void recreateStructures(@Nonnull Chunk chunkIn, int x, int z) { } @Override public boolean isInsideStructure(@Nonnull World worldIn, @Nonnull String structureName, @Nonnull BlockPos pos) { return false; } }
0
0.915236
1
0.915236
game-dev
MEDIA
0.994572
game-dev
0.912894
1
0.912894
spartanoah/acrimony-client
8,915
Acrimony/module/impl/player/Antivoid.java
/* * Decompiled with CFR 0.153-SNAPSHOT (d6f6758-dirty). */ package Acrimony.module.impl.player; import Acrimony.Acrimony; import Acrimony.event.Listener; import Acrimony.event.impl.MotionEvent; import Acrimony.event.impl.PacketReceiveEvent; import Acrimony.event.impl.TickEvent; import Acrimony.module.Category; import Acrimony.module.Module; import Acrimony.module.impl.movement.Fly; import Acrimony.module.impl.movement.Longjump; import Acrimony.setting.impl.BooleanSetting; import Acrimony.setting.impl.DoubleSetting; import Acrimony.setting.impl.ModeSetting; import Acrimony.util.ModuleUtil; import Acrimony.util.world.WorldUtil; import net.minecraft.init.Blocks; import net.minecraft.network.play.server.S08PacketPlayerPosLook; import net.minecraft.util.BlockPos; public class Antivoid extends Module { private final ModeSetting mode = new ModeSetting("Mode", "Flag", "Flag", "Collision flag", "Blink", "Bounce"); private final BooleanSetting stopHorizontalMove = new BooleanSetting("Stop horizontal move", () -> this.mode.is("Blink"), false); private final DoubleSetting bounceMotion = new DoubleSetting("Bounce motion", () -> this.mode.is("Bounce"), 1.5, 0.4, 3.0, 0.1); private final DoubleSetting minFallDist = new DoubleSetting("Min fall dist", 3.5, 2.0, 10.0, 0.25); private PlayerInfo lastSafePos; private BlockPos collisionBlock; private boolean blinking; private Fly flyModule; private Longjump longjumpModule; private boolean receivedLagback; public Antivoid() { super("Antivoid", Category.PLAYER); this.addSettings(this.mode, this.stopHorizontalMove, this.bounceMotion, this.minFallDist); } @Override public void onEnable() { this.collisionBlock = null; this.lastSafePos = new PlayerInfo(Antivoid.mc.thePlayer.posX, Antivoid.mc.thePlayer.posY, Antivoid.mc.thePlayer.posZ, Antivoid.mc.thePlayer.motionX, Antivoid.mc.thePlayer.motionY, Antivoid.mc.thePlayer.motionZ, Antivoid.mc.thePlayer.rotationYaw, Antivoid.mc.thePlayer.rotationPitch, Antivoid.mc.thePlayer.onGround, Antivoid.mc.thePlayer.fallDistance, Antivoid.mc.thePlayer.inventory.currentItem); } @Override public void onDisable() { if (this.blinking) { ModuleUtil.getBlink().stopBlinking(); this.blinking = false; } this.receivedLagback = false; } @Override public void onClientStarted() { this.flyModule = ModuleUtil.getFly(); this.longjumpModule = ModuleUtil.getLongjump(); } @Listener(value=0) public void onTick(TickEvent event) { if (Antivoid.mc.thePlayer.ticksExisted < 10) { this.collisionBlock = null; return; } switch (this.mode.getMode()) { case "Bounce": { if (!this.shouldSetback() || !(Antivoid.mc.thePlayer.motionY < -0.1)) break; Antivoid.mc.thePlayer.motionY = this.bounceMotion.getValue(); break; } case "Collision flag": { if (this.shouldSetback()) { if (this.collisionBlock != null) { Antivoid.mc.theWorld.setBlockToAir(this.collisionBlock); } this.collisionBlock = new BlockPos(Antivoid.mc.thePlayer.posX, Antivoid.mc.thePlayer.posY - 1.0, Antivoid.mc.thePlayer.posZ); Antivoid.mc.theWorld.setBlockState(this.collisionBlock, Blocks.barrier.getDefaultState()); break; } if (this.collisionBlock == null) break; Antivoid.mc.theWorld.setBlockToAir(this.collisionBlock); this.collisionBlock = null; break; } case "Blink": { if (this.isSafe()) { this.lastSafePos = new PlayerInfo(Antivoid.mc.thePlayer.posX, Antivoid.mc.thePlayer.posY, Antivoid.mc.thePlayer.posZ, Antivoid.mc.thePlayer.motionX, Antivoid.mc.thePlayer.motionY, Antivoid.mc.thePlayer.motionZ, Antivoid.mc.thePlayer.rotationYaw, Antivoid.mc.thePlayer.rotationPitch, Antivoid.mc.thePlayer.onGround, Antivoid.mc.thePlayer.fallDistance, Antivoid.mc.thePlayer.inventory.currentItem); this.receivedLagback = false; if (!this.blinking) break; ModuleUtil.stopBlinking(); this.blinking = false; break; } if (this.receivedLagback) break; if (this.shouldSetback()) { if (!this.blinking) break; Antivoid.mc.thePlayer.setPosition(this.lastSafePos.x, this.lastSafePos.y, this.lastSafePos.z); if (this.stopHorizontalMove.isEnabled()) { Antivoid.mc.thePlayer.motionX = 0.0; Antivoid.mc.thePlayer.motionZ = 0.0; } else { Antivoid.mc.thePlayer.motionX = this.lastSafePos.motionX; Antivoid.mc.thePlayer.motionZ = this.lastSafePos.motionZ; } Antivoid.mc.thePlayer.motionY = this.lastSafePos.motionY; Antivoid.mc.thePlayer.rotationYaw = this.lastSafePos.yaw; Antivoid.mc.thePlayer.rotationPitch = this.lastSafePos.pitch; Antivoid.mc.thePlayer.onGround = this.lastSafePos.onGround; Antivoid.mc.thePlayer.fallDistance = this.lastSafePos.fallDist; Antivoid.mc.thePlayer.inventory.currentItem = this.lastSafePos.itemSlot; Antivoid.mc.playerController.currentPlayerItem = this.lastSafePos.itemSlot; Acrimony.instance.getPacketBlinkHandler().releasePingPackets(); Acrimony.instance.getPacketBlinkHandler().clearPackets(); break; } if (this.blinking) break; ModuleUtil.startBlinking(this, false); this.blinking = true; } } } @Listener(value=4) public void onMotion(MotionEvent event) { switch (this.mode.getMode()) { case "Flag": { if (!this.shouldSetback()) break; event.setY(event.getY() + 8.0 + Math.random()); } } } @Listener public void onReceive(PacketReceiveEvent event) { if (event.getPacket() instanceof S08PacketPlayerPosLook) { S08PacketPlayerPosLook packet = (S08PacketPlayerPosLook)event.getPacket(); if (this.mode.is("Blink") && this.blinking) { Antivoid.mc.thePlayer.onGround = false; Antivoid.mc.thePlayer.fallDistance = this.lastSafePos.fallDist; Antivoid.mc.thePlayer.inventory.currentItem = this.lastSafePos.itemSlot; Antivoid.mc.playerController.currentPlayerItem = this.lastSafePos.itemSlot; Acrimony.instance.getPacketBlinkHandler().releasePingPackets(); Acrimony.instance.getPacketBlinkHandler().clearPackets(); ModuleUtil.stopBlinking(); this.lastSafePos = new PlayerInfo(packet.getX(), packet.getY(), packet.getZ(), 0.0, 0.0, 0.0, packet.getYaw(), packet.getPitch(), false, Antivoid.mc.thePlayer.fallDistance, Antivoid.mc.thePlayer.inventory.currentItem); this.blinking = false; this.receivedLagback = true; } } } private boolean shouldSetback() { return (double)Antivoid.mc.thePlayer.fallDistance >= this.minFallDist.getValue() && !WorldUtil.isBlockUnder() && Antivoid.mc.thePlayer.ticksExisted >= 100; } private boolean isSafe() { return WorldUtil.isBlockUnder() || this.flyModule.isEnabled() || this.longjumpModule.isEnabled(); } public boolean isBlinking() { return this.blinking; } private class PlayerInfo { private final double x; private final double y; private final double z; private final double motionX; private final double motionY; private final double motionZ; private final float yaw; private final float pitch; private final boolean onGround; private final float fallDist; private final int itemSlot; private PlayerInfo(double x, double y, double z, double motionX, double motionY, double motionZ, float yaw, float pitch, boolean onGround, float fallDist, int itemSlot) { this.x = x; this.y = y; this.z = z; this.motionX = motionX; this.motionY = motionY; this.motionZ = motionZ; this.yaw = yaw; this.pitch = pitch; this.onGround = onGround; this.fallDist = fallDist; this.itemSlot = itemSlot; } } }
0
0.736543
1
0.736543
game-dev
MEDIA
0.870794
game-dev
0.946145
1
0.946145
apoguita/Py4GW
7,330
DEMO/DEMO_PySkill.py
# Import all req# Necessary Imports import Py4GW #Miscelanious functions and classes import PyImGui #ImGui wrapper import PyMap #Map functions and classes import PyAgent #Agent functions and classes import PyPlayer #Player functions and classes import PyParty #Party functions and classes import PyItem #Item functions and classes import PyInventory #Inventory functions and classes import PySkill #Skill functions and classes import PySkillbar #Skillbar functions and classes import PyMerchant #Merchant functions and classes import traceback #traceback to log stack traces # End Necessary Imports module_name = "PySkill_DEMO" input_skill_id = 0 def DrawWindow(): global module_name global input_skill_id if PyImGui.begin(module_name): # Input field for Skill ID input_skill_id = PyImGui.input_int("Skill ID", input_skill_id) PyImGui.separator() if input_skill_id != 0: # Create Skill instance based on input skill_instance = PySkill.Skill(input_skill_id) # Basic skill information # Basic skill information PyImGui.text(f"Skill ID: {skill_instance.id.id}") PyImGui.text(f"Skill Name: {skill_instance.id.GetName()}") PyImGui.text(f"Skill Type: {skill_instance.type.GetName()}") PyImGui.text(f"Profession: {skill_instance.profession.GetName()}") PyImGui.text(f"Attribute: {skill_instance.attribute.GetName()}") PyImGui.separator() # Skill Costs and Timers PyImGui.text(f"Energy Cost: {skill_instance.energy_cost}") PyImGui.text(f"Health Cost: {skill_instance.health_cost}") PyImGui.text(f"Adrenaline Cost: {skill_instance.adrenaline}") PyImGui.text(f"Overcast: {skill_instance.overcast}") PyImGui.text(f"Activation Time: {skill_instance.activation}") PyImGui.text(f"Aftercast Time: {skill_instance.aftercast}") PyImGui.text(f"Recharge Time: {skill_instance.recharge}") PyImGui.separator() # Skill Flags and Range PyImGui.text(f"Is Touch Range: {'Yes' if skill_instance.is_touch_range else 'No'}") PyImGui.text(f"Is Elite: {'Yes' if skill_instance.is_elite else 'No'}") PyImGui.text(f"Is Half Range: {'Yes' if skill_instance.is_half_range else 'No'}") PyImGui.text(f"Is PvP: {'Yes' if skill_instance.is_pvp else 'No'}") PyImGui.text(f"Is PvE: {'Yes' if skill_instance.is_pve else 'No'}") PyImGui.text(f"Is Playable: {'Yes' if skill_instance.is_playable else 'No'}") PyImGui.text(f"AoE Range: {skill_instance.aoe_range}") PyImGui.separator() # Duration and Scaling Information if PyImGui.collapsing_header("Duration and Scaling"): PyImGui.text(f"Duration (0 points): {skill_instance.duration_0pts}") PyImGui.text(f"Duration (15 points): {skill_instance.duration_15pts}") PyImGui.text(f"Scale (0 points): {skill_instance.scale_0pts}") PyImGui.text(f"Scale (15 points): {skill_instance.scale_15pts}") PyImGui.text(f"Bonus Scale (0 points): {skill_instance.bonus_scale_0pts}") PyImGui.text(f"Bonus Scale (15 points): {skill_instance.bonus_scale_15pts}") PyImGui.separator() # Combo and Skill Arguments if PyImGui.collapsing_header("Combo and Arguments"): PyImGui.text(f"Combo Requirement: {skill_instance.combo_req}") PyImGui.text(f"Combo Effect: {skill_instance.combo}") PyImGui.text(f"Skill Arguments: {skill_instance.skill_arguments}") PyImGui.text(f"Target: {skill_instance.target}") PyImGui.separator() # Weapon and Condition Requirements if PyImGui.collapsing_header("Weapon and Condition Requirements"): PyImGui.text(f"Weapon Requirement: {skill_instance.weapon_req}") PyImGui.text(f"Condition: {skill_instance.condition}") PyImGui.text(f"Effect 1: {skill_instance.effect1}") PyImGui.text(f"Effect 2: {skill_instance.effect2}") PyImGui.text(f"Special: {skill_instance.special}") PyImGui.separator() # Campaign, Titles, and Skill Information if PyImGui.collapsing_header("Campaign, Titles, and Skill Info"): PyImGui.text(f"Campaign: {skill_instance.campaign.GetName()}") PyImGui.text(f"Title ID: {skill_instance.title}") PyImGui.text(f"PvP Skill ID: {skill_instance.id_pvp}") PyImGui.separator() # Animations and Icon Information if PyImGui.collapsing_header("Animations and Icons"): PyImGui.text(f"Caster Overhead Animation ID: {skill_instance.caster_overhead_animation_id}") PyImGui.text(f"Caster Body Animation ID: {skill_instance.caster_body_animation_id}") PyImGui.text(f"Target Body Animation ID: {skill_instance.target_body_animation_id}") PyImGui.text(f"Target Overhead Animation ID: {skill_instance.target_overhead_animation_id}") PyImGui.text(f"Projectile Animation 1 ID: {skill_instance.projectile_animation1_id}") PyImGui.text(f"Projectile Animation 2 ID: {skill_instance.projectile_animation2_id}") PyImGui.text(f"Icon File ID: {skill_instance.icon_file_id}") PyImGui.text(f"Icon File ID 2: {skill_instance.icon_file2_id}") PyImGui.separator() # Skill Descriptions if PyImGui.collapsing_header("Skill Descriptions"): PyImGui.text(f"Skill Name ID: {skill_instance.name_id}") PyImGui.text(f"Concise Description ID: {skill_instance.concise}") PyImGui.text(f"Full Description ID: {skill_instance.description_id}") PyImGui.separator() # Additional Flags and Miscellaneous if PyImGui.collapsing_header("Additional Flags and Miscellaneous"): PyImGui.text(f"Is Stacking: {'Yes' if skill_instance.is_stacking else 'No'}") PyImGui.text(f"Is Non-Stacking: {'Yes' if skill_instance.is_non_stacking else 'No'}") PyImGui.text(f"Is Unused: {'Yes' if skill_instance.is_unused else 'No'}") PyImGui.separator() PyImGui.end() # main() must exist in every script and is the entry point for your plugin's execution. def main(): try: DrawWindow() # Handle specific exceptions to provide detailed error messages except ImportError as e: Py4GW.Console.Log("PySkill_DEMO", f"ImportError encountered: {str(e)}") except ValueError as e: Py4GW.Console.Log("PySkill_DEMO", f"ValueError encountered: {str(e)}") except Exception as e: Py4GW.Console.Log("PySkill_DEMO", f"Unexpected error encountered: {str(e)}") finally: pass # Replace with your actual code # This ensures that main() is called when the script is executed directly. if __name__ == "__main__": main()
0
0.549872
1
0.549872
game-dev
MEDIA
0.979339
game-dev
0.915576
1
0.915576
ProjectSkyfire/SkyFire.406a
6,735
src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp
/* * Copyright (C) 2008-2019 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptPCH.h" #include "azjol_nerub.h" #define MAX_ENCOUNTER 3 /* Azjol Nerub encounters: 0 - Krik'thir the Gatewatcher 1 - Hadronox 2 - Anub'arak */ class instance_azjol_nerub : public InstanceMapScript { public: instance_azjol_nerub() : InstanceMapScript("instance_azjol_nerub", 601) { } struct instance_azjol_nerub_InstanceScript : public InstanceScript { instance_azjol_nerub_InstanceScript(Map* map) : InstanceScript(map) {} uint64 uiKrikthir; uint64 uiHadronox; uint64 uiAnubarak; uint64 uiWatcherGashra; uint64 uiWatcherSilthik; uint64 uiWatcherNarjil; uint64 uiAnubarakDoor[3]; uint64 uiKrikthirDoor; uint32 auiEncounter[MAX_ENCOUNTER]; void Initialize() { memset(&auiEncounter, 0, sizeof(auiEncounter)); memset(&uiAnubarakDoor, 0, sizeof(uiAnubarakDoor)); uiKrikthir = 0; uiHadronox = 0; uiAnubarak = 0; uiWatcherGashra = 0; uiWatcherSilthik = 0; uiWatcherNarjil = 0; uiKrikthirDoor = 0; } bool IsEncounterInProgress() const { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (auiEncounter[i] == IN_PROGRESS) return true; return false; } void OnCreatureCreate(Creature* creature) { switch (creature->GetEntry()) { case 28684: uiKrikthir = creature->GetGUID(); break; case 28921: uiHadronox = creature->GetGUID(); break; case 29120: uiAnubarak = creature->GetGUID(); break; case 28730: uiWatcherGashra = creature->GetGUID(); break; case 28731: uiWatcherSilthik = creature->GetGUID(); break; case 28729: uiWatcherNarjil = creature->GetGUID(); break; } } void OnGameObjectCreate(GameObject* go) { switch (go->GetEntry()) { case 192395: uiKrikthirDoor = go->GetGUID(); if (auiEncounter[0] == DONE) HandleGameObject(0, true, go); break; case 192396: uiAnubarakDoor[0] = go->GetGUID(); break; case 192397: uiAnubarakDoor[1] = go->GetGUID(); break; case 192398: uiAnubarakDoor[2] = go->GetGUID(); break; } } uint64 GetData64(uint32 identifier) { switch (identifier) { case DATA_KRIKTHIR_THE_GATEWATCHER: return uiKrikthir; case DATA_HADRONOX: return uiHadronox; case DATA_ANUBARAK: return uiAnubarak; case DATA_WATCHER_GASHRA: return uiWatcherGashra; case DATA_WATCHER_SILTHIK: return uiWatcherSilthik; case DATA_WATCHER_NARJIL: return uiWatcherNarjil; } return 0; } void SetData(uint32 type, uint32 data) { switch (type) { case DATA_KRIKTHIR_THE_GATEWATCHER_EVENT: auiEncounter[0] = data; if (data == DONE) HandleGameObject(uiKrikthirDoor, true); break; case DATA_HADRONOX_EVENT: auiEncounter[1] = data; break; case DATA_ANUBARAK_EVENT: auiEncounter[2] = data; if (data == IN_PROGRESS) for (uint8 i = 0; i < 3; ++i) HandleGameObject(uiAnubarakDoor[i], false); else if (data == NOT_STARTED || data == DONE) for (uint8 i = 0; i < 3; ++i) HandleGameObject(uiAnubarakDoor[i], true); break; } if (data == DONE) { SaveToDB(); } } uint32 GetData(uint32 type) { switch (type) { case DATA_KRIKTHIR_THE_GATEWATCHER_EVENT: return auiEncounter[0]; case DATA_HADRONOX_EVENT: return auiEncounter[1]; case DATA_ANUBARAK_EVENT: return auiEncounter[2]; } return 0; } std::string GetSaveData() { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << "A N " << auiEncounter[0] << ' ' << auiEncounter[1] << ' ' << auiEncounter[2]; OUT_SAVE_INST_DATA_COMPLETE; return saveStream.str(); } void Load(const char* in) { if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); char dataHead1, dataHead2; uint16 data0, data1, data2; std::istringstream loadStream(in); loadStream >> dataHead1 >> dataHead2 >> data0 >> data1 >> data2; if (dataHead1 == 'A' && dataHead2 == 'N') { auiEncounter[0] = data0; auiEncounter[1] = data1; auiEncounter[2] = data2; for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) if (auiEncounter[i] == IN_PROGRESS) auiEncounter[i] = NOT_STARTED; } else OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; } }; InstanceScript* GetInstanceScript(InstanceMap* map) const { return new instance_azjol_nerub_InstanceScript(map); } }; void AddSC_instance_azjol_nerub() { new instance_azjol_nerub(); }
0
0.948348
1
0.948348
game-dev
MEDIA
0.743871
game-dev
0.98733
1
0.98733
AlizaMedicalImaging/AlizaMS
5,499
b/LinearMath/btQuickprof.h
/*************************************************************************************************** ** ** Real-Time Hierarchical Profiling for Game Programming Gems 3 ** ** by Greg Hjelstrom & Byon Garrabrant ** ***************************************************************************************************/ // Credits: The Clock class was inspired by the Timer classes in // Ogre (www.ogre3d.org). #ifndef BT_QUICK_PROF_H #define BT_QUICK_PROF_H #include "btScalar.h" #define USE_BT_CLOCK 1 #ifdef USE_BT_CLOCK ///The btClock is a portable basic clock that measures accurate time in seconds, use for profiling. class btClock { public: btClock(); btClock(const btClock& other); btClock& operator=(const btClock& other); ~btClock(); /// Resets the initial reference time. void reset(); /// Returns the time in ms since the last call to reset or since /// the btClock was created. unsigned long long int getTimeMilliseconds(); /// Returns the time in us since the last call to reset or since /// the Clock was created. unsigned long long int getTimeMicroseconds(); unsigned long long int getTimeNanoseconds(); /// Returns the time in s since the last call to reset or since /// the Clock was created. btScalar getTimeSeconds(); private: struct btClockData* m_data; }; #endif //USE_BT_CLOCK typedef void(btEnterProfileZoneFunc)(const char* msg); typedef void(btLeaveProfileZoneFunc)(); btEnterProfileZoneFunc* btGetCurrentEnterProfileZoneFunc(); btLeaveProfileZoneFunc* btGetCurrentLeaveProfileZoneFunc(); void btSetCustomEnterProfileZoneFunc(btEnterProfileZoneFunc* enterFunc); void btSetCustomLeaveProfileZoneFunc(btLeaveProfileZoneFunc* leaveFunc); #ifndef BT_ENABLE_PROFILE #define BT_NO_PROFILE 1 #endif //BT_NO_PROFILE const unsigned int BT_QUICKPROF_MAX_THREAD_COUNT = 64; //btQuickprofGetCurrentThreadIndex will return -1 if thread index cannot be determined, //otherwise returns thread index in range [0..maxThreads] unsigned int btQuickprofGetCurrentThreadIndex2(); #ifndef BT_NO_PROFILE #include <stdio.h> //@todo remove this, backwards compatibility #include "btAlignedAllocator.h" #include <new> ///A node in the Profile Hierarchy Tree class CProfileNode { public: CProfileNode(const char* name, CProfileNode* parent); ~CProfileNode(void); CProfileNode* Get_Sub_Node(const char* name); CProfileNode* Get_Parent(void) { return Parent; } CProfileNode* Get_Sibling(void) { return Sibling; } CProfileNode* Get_Child(void) { return Child; } void CleanupMemory(); void Reset(void); void Call(void); bool Return(void); const char* Get_Name(void) { return Name; } int Get_Total_Calls(void) { return TotalCalls; } float Get_Total_Time(void) { return TotalTime; } void* GetUserPointer() const { return m_userPtr; } void SetUserPointer(void* ptr) { m_userPtr = ptr; } protected: const char* Name; int TotalCalls; float TotalTime; unsigned long int StartTime; int RecursionCounter; CProfileNode* Parent; CProfileNode* Child; CProfileNode* Sibling; void* m_userPtr; }; ///An iterator to navigate through the tree class CProfileIterator { public: // Access all the children of the current parent void First(void); void Next(void); bool Is_Done(void); bool Is_Root(void) { return (CurrentParent->Get_Parent() == 0); } void Enter_Child(int index); // Make the given child the new parent void Enter_Largest_Child(void); // Make the largest child the new parent void Enter_Parent(void); // Make the current parent's parent the new parent // Access the current child const char* Get_Current_Name(void) { return CurrentChild->Get_Name(); } int Get_Current_Total_Calls(void) { return CurrentChild->Get_Total_Calls(); } float Get_Current_Total_Time(void) { return CurrentChild->Get_Total_Time(); } void* Get_Current_UserPointer(void) { return CurrentChild->GetUserPointer(); } void Set_Current_UserPointer(void* ptr) { CurrentChild->SetUserPointer(ptr); } // Access the current parent const char* Get_Current_Parent_Name(void) { return CurrentParent->Get_Name(); } int Get_Current_Parent_Total_Calls(void) { return CurrentParent->Get_Total_Calls(); } float Get_Current_Parent_Total_Time(void) { return CurrentParent->Get_Total_Time(); } protected: CProfileNode* CurrentParent; CProfileNode* CurrentChild; CProfileIterator(CProfileNode* start); friend class CProfileManager; }; ///The Manager for the Profile system class CProfileManager { public: static void Start_Profile(const char* name); static void Stop_Profile(void); static void CleanupMemory(void); // { // Root.CleanupMemory(); // } static void Reset(void); static void Increment_Frame_Counter(void); static int Get_Frame_Count_Since_Reset(void) { return FrameCounter; } static float Get_Time_Since_Reset(void); static CProfileIterator* Get_Iterator(void); // { // // return new CProfileIterator( &Root ); // } static void Release_Iterator(CProfileIterator* iterator) { delete (iterator); } static void dumpRecursive(CProfileIterator* profileIterator, int spacing); static void dumpAll(); private: static int FrameCounter; static unsigned long int ResetTime; }; #endif //#ifndef BT_NO_PROFILE ///ProfileSampleClass is a simple way to profile a function's scope ///Use the BT_PROFILE macro at the start of scope to time class CProfileSample { public: CProfileSample(const char* name); ~CProfileSample(void); }; #define BT_PROFILE(name) CProfileSample __profile(name) #endif //BT_QUICK_PROF_H
0
0.962634
1
0.962634
game-dev
MEDIA
0.78793
game-dev
0.896007
1
0.896007
ss14Starlight/space-station-14
6,175
Content.Shared/Timing/UseDelaySystem.cs
using System.Diagnostics.CodeAnalysis; using Robust.Shared.GameStates; using Robust.Shared.Timing; namespace Content.Shared.Timing; public sealed class UseDelaySystem : EntitySystem { [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly MetaDataSystem _metadata = default!; public const string DefaultId = "default"; public override void Initialize() { base.Initialize(); SubscribeLocalEvent<UseDelayComponent, MapInitEvent>(OnMapInit); SubscribeLocalEvent<UseDelayComponent, EntityUnpausedEvent>(OnUnpaused); SubscribeLocalEvent<UseDelayComponent, ComponentGetState>(OnDelayGetState); SubscribeLocalEvent<UseDelayComponent, ComponentHandleState>(OnDelayHandleState); } private void OnDelayHandleState(Entity<UseDelayComponent> ent, ref ComponentHandleState args) { if (args.Current is not UseDelayComponentState state) return; ent.Comp.Delays.Clear(); // At time of writing sourcegen networking doesn't deep copy so this will mispredict if you try. foreach (var (key, delay) in state.Delays) { ent.Comp.Delays[key] = new UseDelayInfo(delay.Length, delay.StartTime, delay.EndTime); } } private void OnDelayGetState(Entity<UseDelayComponent> ent, ref ComponentGetState args) { args.State = new UseDelayComponentState() { Delays = ent.Comp.Delays }; } private void OnMapInit(Entity<UseDelayComponent> ent, ref MapInitEvent args) { // Set default delay length from the prototype // This makes it easier for simple use cases that only need a single delay SetLength((ent, ent.Comp), ent.Comp.Delay, DefaultId); } private void OnUnpaused(Entity<UseDelayComponent> ent, ref EntityUnpausedEvent args) { // We have to do this manually, since it's not just a single field. foreach (var entry in ent.Comp.Delays.Values) { entry.EndTime += args.PausedTime; } } /// <summary> /// Sets the length of the delay with the specified ID. /// </summary> /// <remarks> /// This will add a UseDelay component to the entity if it doesn't have one. /// </remarks> public bool SetLength(Entity<UseDelayComponent?> ent, TimeSpan length, string id = DefaultId) { EnsureComp<UseDelayComponent>(ent.Owner, out var comp); if (comp.Delays.TryGetValue(id, out var entry)) { if (entry.Length == length) return true; entry.Length = length; } else { comp.Delays.Add(id, new UseDelayInfo(length)); } Dirty(ent); return true; } /// <summary> /// Returns true if the entity has a currently active UseDelay with the specified ID. /// </summary> public bool IsDelayed(Entity<UseDelayComponent?> ent, string id = DefaultId) { if (!Resolve(ent.Owner, ref ent.Comp, false)) return false; if (!ent.Comp.Delays.TryGetValue(id, out var entry)) return false; return entry.EndTime >= _gameTiming.CurTime; } /// <summary> /// Cancels the delay with the specified ID. /// </summary> public void CancelDelay(Entity<UseDelayComponent> ent, string id = DefaultId) { if (!ent.Comp.Delays.TryGetValue(id, out var entry)) return; entry.EndTime = _gameTiming.CurTime; Dirty(ent); } /// <summary> /// Tries to get info about the delay with the specified ID. See <see cref="UseDelayInfo"/>. /// </summary> /// <param name="ent"></param> /// <param name="info"></param> /// <param name="id"></param> /// <returns></returns> public bool TryGetDelayInfo(Entity<UseDelayComponent?> ent, [NotNullWhen(true)] out UseDelayInfo? info, string id = DefaultId) { if (!Resolve(ent.Owner, ref ent.Comp, false)) { info = null; return false; } return ent.Comp.Delays.TryGetValue(id, out info); } /// <summary> /// Returns info for the delay that will end farthest in the future. /// </summary> public UseDelayInfo GetLastEndingDelay(Entity<UseDelayComponent> ent) { if (!ent.Comp.Delays.TryGetValue(DefaultId, out var last)) return new UseDelayInfo(TimeSpan.Zero); foreach (var entry in ent.Comp.Delays) { if (entry.Value.EndTime > last.EndTime) last = entry.Value; } return last; } /// <summary> /// Resets the delay with the specified ID for this entity if possible. /// </summary> /// <param name="checkDelayed">Check if the entity has an ongoing delay with the specified ID. /// If it does, return false and don't reset it. /// Otherwise reset it and return true.</param> public bool TryResetDelay(Entity<UseDelayComponent> ent, bool checkDelayed = false, string id = DefaultId) { if (checkDelayed && IsDelayed((ent.Owner, ent.Comp), id)) return false; if (!ent.Comp.Delays.TryGetValue(id, out var entry)) return false; var curTime = _gameTiming.CurTime; entry.StartTime = curTime; entry.EndTime = curTime - _metadata.GetPauseTime(ent) + entry.Length; Dirty(ent); return true; } public bool TryResetDelay(EntityUid uid, bool checkDelayed = false, UseDelayComponent? component = null, string id = DefaultId) { if (!Resolve(uid, ref component, false)) return false; return TryResetDelay((uid, component), checkDelayed, id); } /// <summary> /// Resets all delays on the entity. /// </summary> public void ResetAllDelays(Entity<UseDelayComponent> ent) { var curTime = _gameTiming.CurTime; foreach (var entry in ent.Comp.Delays.Values) { entry.StartTime = curTime; entry.EndTime = curTime - _metadata.GetPauseTime(ent) + entry.Length; } Dirty(ent); } }
0
0.905183
1
0.905183
game-dev
MEDIA
0.922782
game-dev
0.896794
1
0.896794
josh-m/RW-Decompile
1,241
RimWorld/Dialog_NamePlayerSettlement.cs
using RimWorld.Planet; using System; using Verse; namespace RimWorld { public class Dialog_NamePlayerSettlement : Dialog_GiveName { private Settlement settlement; public Dialog_NamePlayerSettlement(Settlement settlement) { this.settlement = settlement; if (settlement.HasMap && settlement.Map.mapPawns.FreeColonistsSpawnedCount != 0) { this.suggestingPawn = settlement.Map.mapPawns.FreeColonistsSpawned.RandomElement<Pawn>(); } this.nameGenerator = (() => NameGenerator.GenerateName(Faction.OfPlayer.def.settlementNameMaker, new Predicate<string>(this.IsValidName), false, null, null)); this.curName = this.nameGenerator(); this.nameMessageKey = "NamePlayerFactionBaseMessage"; this.gainedNameMessageKey = "PlayerFactionBaseGainsName"; this.invalidNameMessageKey = "PlayerFactionBaseNameIsInvalid"; } public override void PostOpen() { base.PostOpen(); if (this.settlement.Map != null) { Current.Game.CurrentMap = this.settlement.Map; } } protected override bool IsValidName(string s) { return NamePlayerSettlementDialogUtility.IsValidName(s); } protected override void Named(string s) { NamePlayerSettlementDialogUtility.Named(this.settlement, s); } } }
0
0.783656
1
0.783656
game-dev
MEDIA
0.771799
game-dev
0.582702
1
0.582702
magefree/mage
1,729
Mage.Sets/src/mage/cards/f/FrostfistStrider.java
package mage.cards.f; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.EntersBattlefieldTriggeredAbility; import mage.abilities.costs.mana.ManaCostsImpl; import mage.abilities.effects.common.TapTargetEffect; import mage.abilities.effects.common.counter.AddCountersTargetEffect; import mage.abilities.keyword.WardAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.counters.CounterType; import mage.target.common.TargetOpponentsCreaturePermanent; import java.util.UUID; /** * @author TheElk801 */ public final class FrostfistStrider extends CardImpl { public FrostfistStrider(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{U}{U}"); this.subtype.add(SubType.ELEMENTAL); this.subtype.add(SubType.GIANT); this.power = new MageInt(4); this.toughness = new MageInt(4); // Ward {2} this.addAbility(new WardAbility(new ManaCostsImpl<>("{2}"))); // When Frostfist Strider enters the battlefield, tap target creature an opponent controls and put a stun counter on it. Ability ability = new EntersBattlefieldTriggeredAbility(new TapTargetEffect()); ability.addEffect(new AddCountersTargetEffect(CounterType.STUN.createInstance()).setText("and put a stun counter on it")); ability.addTarget(new TargetOpponentsCreaturePermanent()); this.addAbility(ability); } private FrostfistStrider(final FrostfistStrider card) { super(card); } @Override public FrostfistStrider copy() { return new FrostfistStrider(this); } }
0
0.912846
1
0.912846
game-dev
MEDIA
0.944151
game-dev
0.994104
1
0.994104
ScilabOrg/scilab
2,080
scilab/modules/graphics/src/c/getHandleProperty/set_mark_mode_property.c
/* * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab * Copyright (C) 2004-2006 - INRIA - Fabrice Leray * Copyright (C) 2006 - INRIA - Allan Cornet * Copyright (C) 2006 - INRIA - Jean-Baptiste Silvy * Copyright (C) 2010 - DIGITEO - Manuel Juliachs * * Copyright (C) 2012 - 2016 - Scilab Enterprises * * This file is hereby licensed under the terms of the GNU GPL v2.0, * pursuant to article 5.3.4 of the CeCILL v.2.1. * This file was originally licensed under the terms of the CeCILL v2.1, * and continues to be available under such terms. * For more information, see the COPYING file which you should have received * along with this program. * */ /*------------------------------------------------------------------------*/ /* file: set_mark_mode_property.c */ /* desc : function to modify in Scilab the mark_mode field of */ /* a handle */ /*------------------------------------------------------------------------*/ #include "setHandleProperty.h" #include "SetProperty.h" #include "getPropertyAssignedValue.h" #include "Scierror.h" #include "localization.h" #include "SetPropertyStatus.h" #include "setGraphicObjectProperty.h" #include "graphicObjectProperties.h" /*------------------------------------------------------------------------*/ int set_mark_mode_property(void* _pvCtx, int iObjUID, void* _pvData, int valueType, int nbRow, int nbCol) { BOOL status = FALSE; int b = tryGetBooleanValueFromStack(_pvData, valueType, nbRow, nbCol, "mark_mode"); if (b == NOT_A_BOOLEAN_VALUE) { return SET_PROPERTY_ERROR; } status = setGraphicObjectProperty(iObjUID, __GO_MARK_MODE__, &b, jni_bool, 1); if (status == TRUE) { return SET_PROPERTY_SUCCEED; } else { Scierror(999, _("'%s' property does not exist for this handle.\n"), "mark_mode"); return SET_PROPERTY_ERROR; } } /*------------------------------------------------------------------------*/
0
0.767554
1
0.767554
game-dev
MEDIA
0.269977
game-dev
0.805438
1
0.805438
RevereInc/alley-practice
1,369
src/main/java/dev/revere/alley/feature/ffa/command/impl/admin/manage/FFAListCommand.java
package dev.revere.alley.feature.ffa.command.impl.admin.manage; import dev.revere.alley.common.text.CC; import dev.revere.alley.feature.ffa.FFAService; import dev.revere.alley.library.command.BaseCommand; import dev.revere.alley.library.command.CommandArgs; import dev.revere.alley.library.command.annotation.CommandData; import org.bukkit.entity.Player; /** * @author Remi * @project Alley * @date 5/27/2024 */ public class FFAListCommand extends BaseCommand { @CommandData( name = "ffa.list", isAdminOnly = true, usage = "ffa list", description = "Sends a list of all FFA matches." ) @Override public void onCommand(CommandArgs command) { Player player = command.getPlayer(); FFAService ffaService = this.plugin.getService(FFAService.class); player.sendMessage(""); player.sendMessage(CC.translate(" &6&lFFA Match List &f(" + ffaService.getMatches().size() + "&f)")); if (ffaService.getMatches().isEmpty()) { player.sendMessage(CC.translate(" &f◆ &cNo Matches available.")); } ffaService.getMatches().forEach(match -> player.sendMessage(CC.translate(" &f◆ &6" + match.getKit().getDisplayName() + " &f(" + (match.getPlayers().size() + "/" + match.getMaxPlayers()) + "&f)"))); player.sendMessage(""); } }
0
0.780309
1
0.780309
game-dev
MEDIA
0.774733
game-dev
0.953831
1
0.953831
giuspen/cherrytree
1,951
src/7za/CPP/7zip/UI/Common/SetProperties.cpp
// SetProperties.cpp #include "StdAfx.h" #include "../../../Common/MyCom.h" #include "../../../Common/MyString.h" #include "../../../Common/StringToInt.h" #include "../../../Windows/PropVariant.h" #include "../../Archive/IArchive.h" #include "SetProperties.h" using namespace NWindows; using namespace NCOM; static void ParseNumberString(const UString &s, NCOM::CPropVariant &prop) { const wchar_t *end; UInt64 result = ConvertStringToUInt64(s, &end); if (*end != 0 || s.IsEmpty()) prop = s; else if (result <= (UInt32)0xFFFFFFFF) prop = (UInt32)result; else prop = result; } HRESULT SetProperties(IUnknown *unknown, const CObjectVector<CProperty> &properties) { if (properties.IsEmpty()) return S_OK; CMyComPtr<ISetProperties> setProperties; unknown->QueryInterface(IID_ISetProperties, (void **)&setProperties); if (!setProperties) return S_OK; UStringVector realNames; CPropVariant *values = new CPropVariant[properties.Size()]; try { unsigned i; for (i = 0; i < properties.Size(); i++) { const CProperty &property = properties[i]; NCOM::CPropVariant propVariant; UString name = property.Name; if (property.Value.IsEmpty()) { if (!name.IsEmpty()) { wchar_t c = name.Back(); if (c == L'-') propVariant = false; else if (c == L'+') propVariant = true; if (propVariant.vt != VT_EMPTY) name.DeleteBack(); } } else ParseNumberString(property.Value, propVariant); realNames.Add(name); values[i] = propVariant; } CRecordVector<const wchar_t *> names; for (i = 0; i < realNames.Size(); i++) names.Add((const wchar_t *)realNames[i]); RINOK(setProperties->SetProperties(&names.Front(), values, names.Size())); } catch(...) { delete []values; throw; } delete []values; return S_OK; }
0
0.960746
1
0.960746
game-dev
MEDIA
0.474496
game-dev
0.958492
1
0.958492
OwlGamingCommunity/MTA
1,146
mods/deathmatch/resources/pd-system/s_policeshotgun.lua
function beanbagFired(x, y, z, target) local px, py, pz = getElementPosition(source) local distance = getDistanceBetweenPoints3D(x, y, z, px, py, pz) if (distance<35) then if (isElement(target) and getElementType(target)=="player") then exports.anticheat:changeProtectedElementDataEx(target, "tazed", true, false) toggleAllControls(target, false, true, false) exports.global:applyAnimation(target, "ped", "FLOOR_hit_f", -1, false, false, true, true) setTimer(removeAnimationX, 10005, 1, target) end end end addEvent("beanbagFired", true ) addEventHandler("beanbagFired", getRootElement(), beanbagFired) function removeAnimationX(thePlayer) if (isElement(thePlayer) and getElementType(thePlayer)=="player") then exports.global:removeAnimation(thePlayer, true) --toggleAllControls(thePlayer, true, true, true) end end function updateShotgunMode(mode) if ( tonumber(mode) and (tonumber(mode) >= 0 and tonumber(mode) <= 1) ) then exports.anticheat:changeProtectedElementDataEx(client, "shotgunmode", mode, true) end end addEvent("shotgunmode", true) addEventHandler("shotgunmode", getRootElement(), updateShotgunMode)
0
0.957977
1
0.957977
game-dev
MEDIA
0.947577
game-dev
0.900874
1
0.900874
confluentinc/ksql
4,929
ksqldb-functional-tests/src/main/java/io/confluent/ksql/test/tools/exceptions/KsqlExpectedException.java
/* * Copyright 2019 Confluent Inc. * * Licensed under the Confluent Community License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at * * http://www.confluent.io/confluent-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package io.confluent.ksql.test.tools.exceptions; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.confluent.ksql.util.KsqlStatementException; import java.util.ArrayList; import java.util.List; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; /** * Helper class for testing exceptions. */ @SuppressFBWarnings("NM_CLASS_NOT_EXCEPTION") public class KsqlExpectedException { public final List<Matcher<?>> matchers = new ArrayList<>(); private Matcher<Throwable> expectedCause; private Matcher<String> expectedCauseMessage; public static KsqlExpectedException none() { return new KsqlExpectedException(); } public void expect(final Class<? extends Throwable> type) { matchers.add(instanceOf(type)); } public void expect(final Matcher<?> matcher) { matchers.add(matcher); } public void expectMessage(final String substring) { expectMessage(containsString(substring)); } public void expectMessage(final Matcher<String> matcher) { matchers.add(UnloggedMessageMatcher.hasMessage(matcher)); } public void expectCause(final Matcher<Throwable> causeMatcher) { this.expectedCause = causeMatcher; } public void expectCauseMessage(final String substring) { expectCauseMessage(containsString(substring)); } public void expectCauseMessage(final Matcher<String> matcher) { this.expectedCauseMessage = matcher; } /** * Matcher that matches the message of a {@link KsqlStatementException} or its unlogged message. * @param <T> the type of the exception */ public static class UnloggedMessageMatcher<T extends Throwable> extends TypeSafeMatcher<T> { private final Matcher<String> matcher; public UnloggedMessageMatcher(final Matcher<String> matcher) { this.matcher = matcher; } public void describeTo(final Description description) { description.appendText("exception with message or unloggedDetails "); description.appendDescriptionOf(this.matcher); } protected boolean matchesSafely(final T item) { final boolean matches = this.matcher.matches(item.getMessage()); return matches || ( item instanceof KsqlStatementException && this.matcher.matches(((KsqlStatementException) item).getUnloggedMessage()) ); } protected void describeMismatchSafely(final T item, final Description description) { description.appendText("message "); this.matcher.describeMismatch(item.getMessage(), description); if (item instanceof KsqlStatementException) { description.appendText("unloggedDetails "); this.matcher.describeMismatch( ((KsqlStatementException) item).getUnloggedMessage(), description ); } } @Factory public static <T extends Throwable> Matcher<T> hasMessage(final Matcher<String> matcher) { return new UnloggedMessageMatcher<>(matcher); } } @SuppressWarnings("unchecked") public Matcher<Throwable> build() { final List<Matcher<?>> allMatchers = new ArrayList<>(matchers); if (expectedCause != null) { allMatchers.add(new TypeSafeMatcher<Throwable>() { @Override protected boolean matchesSafely(final Throwable item) { return expectedCause.matches(item.getCause()); } @Override public void describeTo(final Description description) { description.appendText("exception with cause "); expectedCause.describeTo(description); } }); } if (expectedCauseMessage != null) { allMatchers.add(new TypeSafeMatcher<Throwable>() { @Override protected boolean matchesSafely(final Throwable item) { return item.getCause() != null && expectedCauseMessage.matches(item.getCause().getMessage()); } @Override public void describeTo(final Description description) { description.appendText("exception with cause message "); expectedCauseMessage.describeTo(description); } }); } return allOf((List) allMatchers); } }
0
0.909904
1
0.909904
game-dev
MEDIA
0.336449
game-dev
0.965055
1
0.965055
StygianTheBest/AzerothCore-Content
19,466
Modules/mod-vasautobalance/src/mod_vasautobalance.cpp
/* # Modifications by [StygianTheBest](https://github.com/StygianTheBest/AzerothCore-Content/tree/master/Modules) - v2017.08.23 - Updated module announce, Updated strings --- * Copyright (C) 2012 CVMagic <http://www.trinitycore.org/f/topic/6551-vas-autobalance/> * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * Copyright (C) 1985-2010 {VAS} KalCorp <http://vasserver.dyndns.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Script Name: AutoBalance * Original Authors: KalCorp and Vaughner * Maintainer(s): CVMagic * Original Script Name: VAS.AutoBalance * Description: This script is intended to scale based on number of players, instance mobs & world bosses' health, mana, and damage. */ #include "Configuration/Config.h" #include "Unit.h" #include "Chat.h" #include "Creature.h" #include "Player.h" #include "ObjectMgr.h" #include "MapManager.h" #include "World.h" #include "Map.h" #include "ScriptMgr.h" #include <vector> struct AutoBalanceCreatureInfo { uint32 instancePlayerCount; float DamageMultiplier; }; static std::map<uint32, AutoBalanceCreatureInfo> CreatureInfo; // A hook should be added to remove the mapped entry when the creature is dead or this should be added into the creature object static std::map<int, int> forcedCreatureIds; // The map values correspond with the VAS.AutoBalance.XX.Name entries in the configuration file. static int8 PlayerCountDifficultyOffset; //cheaphack for difficulty server-wide. Another value TODO in player class for the party leader's value to determine dungeon difficulty. int GetValidDebugLevel() { int debugLevel = sConfigMgr->GetIntDefault("VASAutoBalance.DebugLevel", 2); if ((debugLevel < 0) || (debugLevel > 3)) { return 1; } return debugLevel; } void LoadForcedCreatureIdsFromString(std::string creatureIds, int forcedPlayerCount) // Used for reading the string from the configuration file to for those creatures who need to be scaled for XX number of players. { std::string delimitedValue; std::stringstream creatureIdsStream; creatureIdsStream.str(creatureIds); while (std::getline(creatureIdsStream, delimitedValue, ',')) // Process each Creature ID in the string, delimited by the comma - "," { int creatureId = atoi(delimitedValue.c_str()); if (creatureId >= 0) { forcedCreatureIds[creatureId] = forcedPlayerCount; } } } int GetForcedCreatureId(int creatureId) { if (forcedCreatureIds.find(creatureId) == forcedCreatureIds.end()) // Don't want the forcedCreatureIds map to blowup to a massive empty array { return 0; } return forcedCreatureIds[creatureId]; } class VAS_AutoBalance_WorldScript : public WorldScript { public: VAS_AutoBalance_WorldScript() : WorldScript("VAS_AutoBalance_WorldScript") { } void OnBeforeConfigLoad(bool reload) override { /* from skeleton module */ if (!reload) { std::string conf_path = _CONF_DIR; std::string cfg_file = conf_path + "/VASAutoBalance.conf"; #ifdef WIN32 cfg_file = "VASAutoBalance.conf"; #endif std::string cfg_def_file = cfg_file + ".dist"; sConfigMgr->LoadMore(cfg_def_file.c_str()); sConfigMgr->LoadMore(cfg_file.c_str()); } /* end from skeleton module */ } void OnStartup() { } void SetInitialWorldSettings() { forcedCreatureIds.clear(); LoadForcedCreatureIdsFromString(sConfigMgr->GetStringDefault("VASAutoBalance.ForcedID40", ""), 40); LoadForcedCreatureIdsFromString(sConfigMgr->GetStringDefault("VASAutoBalance.ForcedID25", ""), 25); LoadForcedCreatureIdsFromString(sConfigMgr->GetStringDefault("VASAutoBalance.ForcedID10", ""), 10); LoadForcedCreatureIdsFromString(sConfigMgr->GetStringDefault("VASAutoBalance.ForcedID5", ""), 5); LoadForcedCreatureIdsFromString(sConfigMgr->GetStringDefault("VASAutoBalance.ForcedID2", ""), 2); PlayerCountDifficultyOffset = 0; } }; class VAS_AutoBalance_PlayerScript : public PlayerScript { public: VAS_AutoBalance_PlayerScript() : PlayerScript("VAS_AutoBalance_PlayerScript") { } void OnLogin(Player *Player) { if (sConfigMgr->GetBoolDefault("VAS.Announce", true)) { //ChatHandler(Player->GetSession()).PSendSysMessage("This server is running a VAS_AutoBalance Module."); ChatHandler(Player->GetSession()).SendSysMessage("This server is running the |cff4CFF00VASAutobalance |rmodule."); } } }; class VAS_AutoBalance_UnitScript : public UnitScript { public: VAS_AutoBalance_UnitScript() : UnitScript("VAS_AutoBalance_UnitScript", true) { } uint32 DealDamage(Unit* AttackerUnit, Unit *playerVictim, uint32 damage, DamageEffectType damagetype) { if ((AttackerUnit->GetMap()->IsDungeon() && playerVictim->GetMap()->IsDungeon()) || sConfigMgr->GetIntDefault("VASAutoBalance.DungeonsOnly", 1) < 1) if (AttackerUnit->GetTypeId() != TYPEID_PLAYER) { damage = VAS_Modifer_DealDamage(AttackerUnit, damage); } return damage; } uint32 HandlePeriodicDamageAurasTick(Unit *target, Unit *caster, int32 damage) { if ((caster->GetMap()->IsDungeon() && target->GetMap()->IsDungeon()) || sConfigMgr->GetIntDefault("VASAutoBalance.DungeonsOnly", 1) < 1) if (caster->GetTypeId() != TYPEID_PLAYER) { if (!((caster->IsHunterPet() || caster->IsPet() || caster->IsSummon()) && caster->IsControlledByPlayer())) damage = (float)damage * (float)CreatureInfo[caster->GetGUID()].DamageMultiplier; } return damage; } void CalculateSpellDamageTaken(SpellNonMeleeDamage *damageInfo, int32 damage, SpellInfo const *spellInfo, WeaponAttackType attackType, bool crit) { if (sConfigMgr->GetIntDefault("VASAutoBalance.DungeonsOnly", 1) < 1 || (damageInfo->attacker->GetMap()->IsDungeon() && damageInfo->target->GetMap()->IsDungeon()) || (damageInfo->attacker->GetMap()->IsBattleground() && damageInfo->target->GetMap()->IsBattleground())) { if (damageInfo->attacker->GetTypeId() != TYPEID_PLAYER) { if ((damageInfo->attacker->IsHunterPet() || damageInfo->attacker->IsPet() || damageInfo->attacker->IsSummon()) && damageInfo->attacker->IsControlledByPlayer()) return; damageInfo->damage = (float)damageInfo->damage * (float)CreatureInfo[damageInfo->attacker->GetGUID()].DamageMultiplier; } } return; } void CalculateMeleeDamage(Unit *playerVictim, uint32 damage, CalcDamageInfo *damageInfo, WeaponAttackType attackType) { // Make sure the Attacker and the Victim are in the same location, in addition that the attacker is not player. if ((sConfigMgr->GetIntDefault("VASAutoBalance.DungeonsOnly", 1) < 1 || (damageInfo->attacker->GetMap()->IsDungeon() && damageInfo->target->GetMap()->IsDungeon()) || (damageInfo->attacker->GetMap()->IsBattleground() && damageInfo->target->GetMap()->IsBattleground())) && (damageInfo->attacker->GetTypeId() != TYPEID_PLAYER)) if (!((damageInfo->attacker->IsHunterPet() || damageInfo->attacker->IsPet() || damageInfo->attacker->IsSummon()) && damageInfo->attacker->IsControlledByPlayer())) // Make sure that the attacker Is not a Pet of some sort { damageInfo->damage = (float)damageInfo->damage * (float)CreatureInfo[damageInfo->attacker->GetGUID()].DamageMultiplier; } return; } uint32 VAS_Modifer_DealDamage(Unit* AttackerUnit, uint32 damage) { if ((AttackerUnit->IsHunterPet() || AttackerUnit->IsPet() || AttackerUnit->IsSummon()) && AttackerUnit->IsControlledByPlayer()) return damage; float damageMultiplier = CreatureInfo[AttackerUnit->GetGUID()].DamageMultiplier; return damage * damageMultiplier; } }; class VAS_AutoBalance_AllMapScript : public AllMapScript { public: VAS_AutoBalance_AllMapScript() : AllMapScript("VAS_AutoBalance_AllMapScript") { } void OnPlayerEnterAll(Map* map, Player* player) { if (sConfigMgr->GetIntDefault("VASAutoBalance.PlayerChangeNotify", 1) > 0) { if ((map->GetEntry()->IsDungeon()) && !player->IsGameMaster()) { Map::PlayerList const &playerList = map->GetPlayers(); if (!playerList.isEmpty()) { for (Map::PlayerList::const_iterator playerIteration = playerList.begin(); playerIteration != playerList.end(); ++playerIteration) { if (Player* playerHandle = playerIteration->GetSource()) { ChatHandler chatHandle = ChatHandler(playerHandle->GetSession()); chatHandle.PSendSysMessage("|cffFF0000[AutoBalance]|cffFF8000 %s entered %s - # of Players: %u - Difficulty Offset: %u. |r", player->GetName().c_str(), map->GetMapName(), map->GetPlayersCountExceptGMs() + PlayerCountDifficultyOffset, PlayerCountDifficultyOffset); } } } } } } void OnPlayerLeaveAll(Map* map, Player* player) { int instancePlayerCount = map->GetPlayersCountExceptGMs() - 1; if (instancePlayerCount >= 1) { if (sConfigMgr->GetIntDefault("VASAutoBalance.PlayerChangeNotify", 1) > 0) { if ((map->GetEntry()->IsDungeon()) && !player->IsGameMaster()) { Map::PlayerList const &playerList = map->GetPlayers(); if (!playerList.isEmpty()) { for (Map::PlayerList::const_iterator playerIteration = playerList.begin(); playerIteration != playerList.end(); ++playerIteration) { if (Player* playerHandle = playerIteration->GetSource()) { ChatHandler chatHandle = ChatHandler(playerHandle->GetSession()); chatHandle.PSendSysMessage("|cffFF0000[AutoBalance]|cffFF8000 %s exited to %s - # of Players: %u - Difficulty Offset = %u. |r", player->GetName().c_str(), map->GetMapName(), instancePlayerCount, PlayerCountDifficultyOffset); } } } } } } } }; class VAS_AutoBalance_AllCreatureScript : public AllCreatureScript { public: VAS_AutoBalance_AllCreatureScript() : AllCreatureScript("VAS_AutoBalance_AllCreatureScript") { } void Creature_SelectLevel(const CreatureTemplate *creatureTemplate, Creature* creature) { if (creature->GetMap()->IsDungeon() || sConfigMgr->GetIntDefault("VASAutoBalance.DungeonsOnly", 1) < 1) { ModifyCreatureAttributes(creature); CreatureInfo[creature->GetGUID()].instancePlayerCount = creature->GetMap()->GetPlayersCountExceptGMs() + PlayerCountDifficultyOffset; } } void OnAllCreatureUpdate(Creature* creature, uint32 diff) { if (!(CreatureInfo[creature->GetGUID()].instancePlayerCount == (creature->GetMap()->GetPlayersCountExceptGMs() + PlayerCountDifficultyOffset))) { if (creature->GetMap()->IsDungeon() || creature->GetMap()->IsBattleground() || sConfigMgr->GetIntDefault("VASAutoBalance.DungeonsOnly", 1) < 1) ModifyCreatureAttributes(creature); CreatureInfo[creature->GetGUID()].instancePlayerCount = creature->GetMap()->GetPlayersCountExceptGMs() + PlayerCountDifficultyOffset; } } void ModifyCreatureAttributes(Creature* creature) { if (((creature->IsHunterPet() || creature->IsPet() || creature->IsSummon()) && creature->IsControlledByPlayer()) || (creature->GetMap()->IsDungeon() && sConfigMgr->GetIntDefault("VASAutoBalance.Instances", 1) < 1) || creature->GetMap()->GetPlayersCountExceptGMs() <= 0) { return; } CreatureTemplate const *creatureTemplate = creature->GetCreatureTemplate(); CreatureBaseStats const* creatureStats = sObjectMgr->GetCreatureBaseStats(creature->getLevel(), creatureTemplate->unit_class); float damageMultiplier = 1.0f; float healthMultiplier = 1.0f; uint32 baseHealth = creatureStats->GenerateHealth(creatureTemplate); uint32 baseMana = creatureStats->GenerateMana(creatureTemplate); uint32 instancePlayerCount = creature->GetMap()->GetPlayersCountExceptGMs() + PlayerCountDifficultyOffset; uint32 maxNumberOfPlayers = ((InstanceMap*)sMapMgr->FindMap(creature->GetMapId(), creature->GetInstanceId()))->GetMaxPlayers(); uint32 scaledHealth = 0; uint32 scaledMana = 0; // VAS SOLO - By MobID if (GetForcedCreatureId(creatureTemplate->Entry) > 0) { maxNumberOfPlayers = GetForcedCreatureId(creatureTemplate->Entry); // Force maxNumberOfPlayers to be changed to match the Configuration entry. } // (tanh((X-2.2)/1.5) +1 )/2 // 5 Man formula X = Number of Players // (tanh((X-5)/2) +1 )/2 // 10 Man Formula X = Number of Players // (tanh((X-16.5)/6.5) +1 )/2 // 25 Man Formula X = Number of players // // Note: The 2.2, 5, and 16.5 are the number of players required to get 50% health. // It's not required this be a whole number, you'd adjust this to raise or lower // the hp modifier for per additional player in a non-whole group. These // values will eventually be part of the configuration file once I finalize the mod. // // The 1.5, 2, and 6.5 modify the rate of percentage increase between // number of players. Generally the closer to the value of 1 you have this // the less gradual the rate will be. For example in a 5 man it would take 3 // total players to face a mob at full health. // // The +1 and /2 values raise the TanH function to a positive range and make // sure the modifier never goes above the value or 1.0 or below 0. // // Lastly this formula has one side effect on full groups Bosses and mobs will // never have full health, this can be tested against by making sure the number // of players match the maxNumberOfPlayers variable. switch (maxNumberOfPlayers) { case 40: healthMultiplier = (float)instancePlayerCount / (float)maxNumberOfPlayers; // 40 Man Instances oddly enough scale better with the old formula break; case 25: healthMultiplier = (tanh((instancePlayerCount - 16.5f) / 1.5f) + 1.0f) / 2.0f; break; case 10: healthMultiplier = (tanh((instancePlayerCount - 4.5f) / 1.5f) + 1.0f) / 2.0f; break; case 2: healthMultiplier = (float)instancePlayerCount / (float)maxNumberOfPlayers; // Two Man Creatures are too easy if handled by the 5 man formula, this would only break; // apply in the situation where it's specified in the configuration file. default: healthMultiplier = (tanh((instancePlayerCount - 2.2f) / 1.5f) + 1.0f) / 2.0f; // default to a 5 man group } // VAS SOLO - Map 0,1 and 530 ( World Mobs ) // This may be where VAS_AutoBalance_CheckINIMaps might have come into play. None the less this is if ((creature->GetMapId() == 0 || creature->GetMapId() == 1 || creature->GetMapId() == 530) && (creature->isElite() || creature->isWorldBoss())) // specific to World Bosses and elites in those Maps, this is going to use the entry XPlayer in place of instancePlayerCount. { if (baseHealth > 800000) { healthMultiplier = (tanh((sConfigMgr->GetFloatDefault("VASAutoBalance.numPlayer", 1.0f) - 5.0f) / 1.5f) + 1.0f) / 2.0f; } else { healthMultiplier = (tanh((sConfigMgr->GetFloatDefault("VASAutoBalance.numPlayer", 1.0f) - 2.2f) / 1.5f) + 1.0f) / 2.0f; // Assuming a 5 man configuration, as World Bosses have been relatively retired since BC so unless the boss has some substantial baseHealth } } // Ensure that the healthMultiplier is not lower than the configuration specified value. -- This may be Deprecated later. if (healthMultiplier <= sConfigMgr->GetFloatDefault("VASAutoBalance.MinHPModifier", 0.1f)) { healthMultiplier = sConfigMgr->GetFloatDefault("VASAutoBalance.MinHPModifier", 0.1f); } //Getting the list of Classes in this group - this will be used later on to determine what additional scaling will be required based on the ratio of tank/dps/healer //GetPlayerClassList(creature, playerClassList); // Update playerClassList with the list of all the participating Classes scaledHealth = uint32((baseHealth * healthMultiplier) + 1.0f); // Now adjusting Mana, Mana is something that can be scaled linearly if (maxNumberOfPlayers == 0) { scaledMana = uint32((baseMana * healthMultiplier) + 1.0f); // Now Adjusting Damage, this too is linear for now .... this will have to change I suspect. damageMultiplier = healthMultiplier; } else { scaledMana = ((baseMana / maxNumberOfPlayers) * instancePlayerCount); // Now Adjusting Damage, this too is linear for now .... this will have to change I suspect. damageMultiplier = (float)instancePlayerCount / (float)maxNumberOfPlayers; } // Can not be less then Min_D_Mod if (damageMultiplier <= sConfigMgr->GetFloatDefault("VASAutoBalance.MinDamageModifier", 0.1f)) { damageMultiplier = sConfigMgr->GetFloatDefault("VASAutoBalance.MinDamageModifier", 0.1f); } creature->SetCreateHealth(scaledHealth); creature->SetMaxHealth(scaledHealth); creature->ResetPlayerDamageReq(); creature->SetCreateMana(scaledMana); creature->SetMaxPower(POWER_MANA, scaledMana); creature->SetPower(POWER_MANA, scaledMana); creature->SetModifierValue(UNIT_MOD_HEALTH, BASE_VALUE, (float)scaledHealth); creature->SetModifierValue(UNIT_MOD_MANA, BASE_VALUE, (float)scaledMana); CreatureInfo[creature->GetGUID()].DamageMultiplier = damageMultiplier; } }; class VAS_AutoBalance_CommandScript : public CommandScript { public: VAS_AutoBalance_CommandScript() : CommandScript("VAS_AutoBalance_CommandScript") { } std::vector<ChatCommand> GetCommands() const { static std::vector<ChatCommand> vasCommandTable = { { "setoffset", SEC_GAMEMASTER, true, &HandleVasSetOffsetCommand, "" }, { "getoffset", SEC_GAMEMASTER, true, &HandleVasGetOffsetCommand, "" }, }; static std::vector<ChatCommand> commandTable = { { "vas", SEC_GAMEMASTER, false, NULL, "", vasCommandTable }, }; return commandTable; } static bool HandleVasSetOffsetCommand(ChatHandler* handler, const char* args) { if (!*args) { handler->PSendSysMessage(".vas setoffset #"); handler->PSendSysMessage("Sets the Player Difficulty Offset for instances. Example: (You + offset(1) = 2 player difficulty)."); return false; } char* offset = strtok((char*)args, " "); int32 offseti = -1; if (offset) { offseti = (uint32)atoi(offset); handler->PSendSysMessage("Changing Player Difficulty Offset to %i.", offseti); PlayerCountDifficultyOffset = offseti; return true; } else handler->PSendSysMessage("Error changing Player Difficulty Offset! Please try again."); return false; } static bool HandleVasGetOffsetCommand(ChatHandler* handler, const char* /*args*/) { handler->PSendSysMessage("Current Player Difficulty Offset = %i", PlayerCountDifficultyOffset); return true; } }; void AddVASAutoBalanceScripts() { new VAS_AutoBalance_WorldScript; new VAS_AutoBalance_PlayerScript; new VAS_AutoBalance_UnitScript; new VAS_AutoBalance_AllCreatureScript; new VAS_AutoBalance_AllMapScript; new VAS_AutoBalance_CommandScript; }
0
0.939884
1
0.939884
game-dev
MEDIA
0.985278
game-dev
0.967692
1
0.967692
mir-diablo-ii-tools/SlashGaming-Diablo-II-Free-Resolution
4,712
SlashGaming-Diablo-II-Free-Resolution/src/patches/required/d2client/set_tile_culling_bound/patch_1_11.cpp
/** * SlashGaming Diablo II Free Resolution * Copyright (C) 2019-2024 Mir Drualga * * This file is part of SlashGaming Diablo II Free Resolution. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Additional permissions under GNU Affero General Public License version 3 * section 7 * * If you modify this Program, or any covered work, by linking or combining * it with Diablo II (or a modified version of that game and its * libraries), containing parts covered by the terms of Blizzard End User * License Agreement, the licensors of this Program grant you additional * permission to convey the resulting work. This additional permission is * also extended to any combination of expansions, mods, and remasters of * the game. * * If you modify this Program, or any covered work, by linking or combining * it with any Graphics Device Interface (GDI), DirectDraw, Direct3D, * Glide, OpenGL, or Rave wrapper (or modified versions of those * libraries), containing parts not covered by a compatible license, the * licensors of this Program grant you additional permission to convey the * resulting work. * * If you modify this Program, or any covered work, by linking or combining * it with any library (or a modified version of that library) that links * to Diablo II (or a modified version of that game and its libraries), * containing parts not covered by a compatible license, the licensors of * this Program grant you additional permission to convey the resulting * work. */ #include "patch_1_11.hpp" #include <stddef.h> #include <sgd2mapi.hpp> #include "../../../../helper/abstract_version_patch.hpp" #include "../../../../helper/patch_address_and_size.hpp" #include "patch_1_11_shim.h" namespace sgd2fr { namespace d2client { namespace { using ::d2::DefaultLibrary; using ::d2::GameVersion; using ::d2::game_version::GetRunning; using ::mapi::BranchType; using ::mapi::GameAddress; using ::mapi::GamePatch; using ::sgd2fr::PatchAddressAndSize; } // namespace SetTileCullingBoundPatch_1_11::SetTileCullingBoundPatch_1_11() : AbstractVersionPatch(this->patches_, kPatchesCount) { PatchAddressAndSize patch_address_and_size_01 = GetPatchAddressAndSize01(); GamePatch patch_01 = GamePatch::MakeGameBranchPatch( patch_address_and_size_01.first, BranchType::kJump, &D2Client_SetTileCullingBoundPatch_1_11_InterceptionFunc01, patch_address_and_size_01.second); this->patches_[0].Swap(patch_01); } PatchAddressAndSize SetTileCullingBoundPatch_1_11::GetPatchAddressAndSize01() { /* * How to find patch locations: * 1. Start a game with any character. * 2. Search for the address of the string "Perspective" in * D2Client.dll. * 3. Search for all usages of the string "Perspective". If there is * more than one string, try all of them. * 3. Go to the code location where the string is used. * 4. Enter the first called function that is in D2Client.dll * address space. That is the target address. */ GameVersion running_game_version = GetRunning(); ptrdiff_t offset; size_t size; switch (running_game_version) { case GameVersion::k1_11: { offset = 0x5B560; size = 0x5B565 - 0x5B560; break; } case GameVersion::k1_11B: { offset = 0x927A0; size = 0x927A5 - 0x927A0; break; } case GameVersion::k1_12A: { offset = 0xBA990; size = 0xBA995 - 0xBA990; break; } case GameVersion::k1_13ABeta: { offset = 0x3F490; size = 0x3F495 - 0x3F490; break; } case GameVersion::k1_13C: { offset = 0x8A4D0; size = 0x8A4D5 - 0x8A4D0; break; } case GameVersion::k1_13D: { offset = 0xB5330; size = 0xB5335 - 0xB5330; break; } case GameVersion::kLod1_14A: { offset = 0xB5330; size = 0xB5335 - 0xB5330; break; } } return PatchAddressAndSize( GameAddress::FromOffset(DefaultLibrary::kD2Client, offset), size); } } // namespace sgd2fr } // namespace d2client
0
0.624441
1
0.624441
game-dev
MEDIA
0.86941
game-dev
0.722447
1
0.722447
pablushaa/AllahClientRecode
3,476
net/minecraft/world/chunk/storage/RegionFileCache.java
package net.minecraft.world.chunk.storage; import com.google.common.collect.Maps; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.Map; public class RegionFileCache { private static final Map<File, RegionFile> REGIONS_BY_FILE = Maps.<File, RegionFile>newHashMap(); public static synchronized RegionFile createOrLoadRegionFile(File worldDir, int chunkX, int chunkZ) { File file1 = new File(worldDir, "region"); File file2 = new File(file1, "r." + (chunkX >> 5) + "." + (chunkZ >> 5) + ".mca"); RegionFile regionfile = REGIONS_BY_FILE.get(file2); if (regionfile != null) { return regionfile; } else { if (!file1.exists()) { file1.mkdirs(); } if (REGIONS_BY_FILE.size() >= 256) { clearRegionFileReferences(); } RegionFile regionfile1 = new RegionFile(file2); REGIONS_BY_FILE.put(file2, regionfile1); return regionfile1; } } public static synchronized RegionFile func_191065_b(File p_191065_0_, int p_191065_1_, int p_191065_2_) { File file1 = new File(p_191065_0_, "region"); File file2 = new File(file1, "r." + (p_191065_1_ >> 5) + "." + (p_191065_2_ >> 5) + ".mca"); RegionFile regionfile = REGIONS_BY_FILE.get(file2); if (regionfile != null) { return regionfile; } else if (file1.exists() && file2.exists()) { if (REGIONS_BY_FILE.size() >= 256) { clearRegionFileReferences(); } RegionFile regionfile1 = new RegionFile(file2); REGIONS_BY_FILE.put(file2, regionfile1); return regionfile1; } else { return null; } } /** * clears region file references */ public static synchronized void clearRegionFileReferences() { for (RegionFile regionfile : REGIONS_BY_FILE.values()) { try { if (regionfile != null) { regionfile.close(); } } catch (IOException ioexception) { ioexception.printStackTrace(); } } REGIONS_BY_FILE.clear(); } /** * Gets an input stream for the chunk at the specified location. */ public static DataInputStream getChunkInputStream(File worldDir, int chunkX, int chunkZ) { RegionFile regionfile = createOrLoadRegionFile(worldDir, chunkX, chunkZ); return regionfile.getChunkDataInputStream(chunkX & 31, chunkZ & 31); } /** * Gets an output stream for the specified chunk. */ public static DataOutputStream getChunkOutputStream(File worldDir, int chunkX, int chunkZ) { RegionFile regionfile = createOrLoadRegionFile(worldDir, chunkX, chunkZ); return regionfile.getChunkDataOutputStream(chunkX & 31, chunkZ & 31); } public static boolean func_191064_f(File p_191064_0_, int p_191064_1_, int p_191064_2_) { RegionFile regionfile = func_191065_b(p_191064_0_, p_191064_1_, p_191064_2_); return regionfile != null ? regionfile.isChunkSaved(p_191064_1_ & 31, p_191064_2_ & 31) : false; } }
0
0.643342
1
0.643342
game-dev
MEDIA
0.84273
game-dev
0.733183
1
0.733183
druhasu/UnrealMvvm
3,522
UnrealMvvm/Source/UnrealMvvmUbt/UhtMvvmProperty.cs
// Copyright Andrei Sudarikov. All Rights Reserved. using System; using EpicGames.UHT.Parsers; using EpicGames.UHT.Tables; using EpicGames.UHT.Tokenizer; using EpicGames.UHT.Types; using EpicGames.UHT.Utils; namespace UnrealMvvm; public class UhtMvvmProperty : UhtType { #if UE_5_6_OR_LATER public UhtTypeTokens PropertyTypeTokens { get; set; } #else public ReadOnlyMemory<UhtToken> PropertyTypeTokens { get; set; } #endif public bool AutoSetter { get; set; } = false; public bool AutoGetter { get; set; } = false; public bool AutoField { get; set; } = false; public bool HasSetter { get; set; } = false; public string GetterAccess { get; set; } = "public"; public string SetterAccess { get; set; } = "private"; public override UhtEngineType EngineType => UhtEngineType.Property; public override string EngineClassName => "ViewModelProperty"; public UhtClass Class => (Outer as UhtClass)!; #if UE_5_5_OR_LATER public UhtMvvmProperty(UhtModule module) : base(module) { } public UhtMvvmProperty(UhtHeaderFile headerFile, UhtType outer, int lineNumber, UhtMetaData? metaData = null) : base(headerFile, outer, lineNumber, metaData) { } #else public UhtMvvmProperty(UhtSession session) : base(session) { } public UhtMvvmProperty(UhtType outer, int lineNumber, UhtMetaData? metaData = null) : base(outer, lineNumber, metaData) { } #endif protected override bool ResolveSelf(UhtResolvePhase phase) { bool bResult = base.ResolveSelf(phase); if (phase == UhtResolvePhase.Properties) { // we only want to resolve properties containing UObjects to trigger builtin TObjectPtr validation, when it is enabled // all other properties do not have to be valid according to UhtParser rules, so we skip them if (TypeMayContainUObject()) { UhtPropertySettings propertySettings = new() { Outer = Outer!, SourceName = SourceName, EngineName = SourceName, PropertyCategory = UhtPropertyCategory.Member, #if UE_5_6_OR_LATER TypeTokens = new(PropertyTypeTokens, 0), #endif }; // ask default property parser to do all the heavy work #if UE_5_6_OR_LATER using UhtTokenReplayReaderBorrower borrowedReader = new(Class.HeaderFile, Class.HeaderFile.Data.Memory, PropertyTypeTokens.AllTokens, UhtTokenType.EndOfType); UhtPropertyResolveArgs args = new(UhtPropertyResolvePhase.Resolving, propertySettings, borrowedReader.Reader); args.ResolveProperty(); #else UhtPropertyParser.ResolveProperty(UhtPropertyResolvePhase.Resolving, propertySettings, Class.HeaderFile.Data.Memory, PropertyTypeTokens); #endif } } return bResult; } private bool TypeMayContainUObject() { #if UE_5_6_OR_LATER ReadOnlySpan<UhtToken> tokensSpan = PropertyTypeTokens.AllTokens.Span; #else ReadOnlySpan<UhtToken> tokensSpan = PropertyTypeTokens.Span; #endif for (int i = 0; i < tokensSpan.Length; i++) { ref readonly var token = ref tokensSpan[i]; if (token.IsIdentifier() && (token.ValueStartsWith("U") || token.ValueStartsWith("A"))) { return true; } } return false; } }
0
0.874808
1
0.874808
game-dev
MEDIA
0.879545
game-dev
0.895389
1
0.895389
the-grue/OpenDOS
42,616
IBMDOS/PROCESS.A86
; File : $PROCESS.A86$ ; ; Description : ; ; Original Author : DIGITAL RESEARCH ; ; Last Edited By : $CALDERA$ ; ;-----------------------------------------------------------------------; ; Copyright Work of Caldera, Inc. All Rights Reserved. ; ; THIS WORK IS A COPYRIGHT WORK AND CONTAINS CONFIDENTIAL, ; PROPRIETARY AND TRADE SECRET INFORMATION OF CALDERA, INC. ; ACCESS TO THIS WORK IS RESTRICTED TO (I) CALDERA, INC. EMPLOYEES ; WHO HAVE A NEED TO KNOW TO PERFORM TASKS WITHIN THE SCOPE OF ; THEIR ASSIGNMENTS AND (II) ENTITIES OTHER THAN CALDERA, INC. WHO ; HAVE ACCEPTED THE CALDERA OPENDOS SOURCE LICENSE OR OTHER CALDERA LICENSE ; AGREEMENTS. EXCEPT UNDER THE EXPRESS TERMS OF THE CALDERA LICENSE ; AGREEMENT NO PART OF THIS WORK MAY BE USED, PRACTICED, PERFORMED, ; COPIED, DISTRIBUTED, REVISED, MODIFIED, TRANSLATED, ABRIDGED, ; CONDENSED, EXPANDED, COLLECTED, COMPILED, LINKED, RECAST, ; TRANSFORMED OR ADAPTED WITHOUT THE PRIOR WRITTEN CONSENT OF ; CALDERA, INC. ANY USE OR EXPLOITATION OF THIS WORK WITHOUT ; AUTHORIZATION COULD SUBJECT THE PERPETRATOR TO CRIMINAL AND ; CIVIL LIABILITY. ;-----------------------------------------------------------------------; ; ; *** Current Edit History *** ; *** End of Current Edit History *** ; $Log$ ; PROCESS.A86 1.25 94/07/13 16:15:27 ; Int21/26 (create PSP) copies 1st 20 entries of parental XFT ; PROCESS.A86 1.24 94/06/28 11:15:28 ; Don't issue an int 21 to get curret psp while within int21/4B load overlay ; PROCESS.A86 1.20 93/09/28 19:44:03 ; Don't lose 8th character of name in DMD during exec ; PROCESS.A86 1.14 93/06/18 21:00:57 ; Support for Int 21/4B05 added ; PROCESS.A86 1.13 93/06/11 02:11:20 ; GateA20 disabled on EXEC for EXEPACKED apps ; Fix termination code ; ENDLOG ; include pcmode.equ include fdos.def include i:psp.def include i:mserror.equ include vectors.def include i:msdos.equ include i:exe.def include i:char.def include i:redir.equ include i:doshndl.def HILOAD equ TRUE PCM_CODE CSEG BYTE extrn check_dmd_id:near extrn dbcs_lead:near extrn error_exit:near extrn fdos_nocrit:near extrn free_all:near extrn get_dseg:near ; Get the PCMODE Data Segment extrn int21_exit:near extrn invalid_function:near extrn dos_entry:near extrn return_AX_CLC:near extrn set_owner:near extrn strlen:near extrn toupper:near extrn valid_drive:near ; ; ;PC-DOS PSP Creation Update and Maintance routines ; ; ***************************** ; *** DOS Function 55 *** ; *** Create New PSP *** ; ***************************** ; ; entry: DX = New PSP Segment ; SI = Top of Available ; ; This function copies the existing PSP and generates a new Process ; environment. The file table is updated and dos_SI is used to determine ; the process' memory size. The PSP is then made the CURRENT_PSP Public func55 func55: mov cx,PSPLEN/2 ; copy whole PSP call create_psp mov al,0F0h ret create_psp: mov ax,current_psp ; All based on the Current PSP call copy_psp ; Do the Basic Copy mov ax,current_psp ; get the Current PSP address mov PSP_PARENT,ax ; and save it in child's psp cmp ax,dx ; Is this the ROOT level DOS process jz create_psp10 ; Yes because Current PSP == New PSP ; therefore skip the EXEC function ; because this is done by P_CREATE mov FD_FUNC,FD_EXEC ; Must Update the Open Counts ETC. mov FD_PSPSEG,dx ; New PSP address call fdos_nocrit create_psp10: mov current_psp,es ; set the New PSP address ret ; ; ***************************** ; *** DOS Function 26 *** ; *** Create New PSP *** ; ***************************** ; ; entry: DX = New PSP Segment ; Public func26 func26: les di,int21regs_ptr ; Get pointer to INT 21 structure of mov es,es:reg_CS[di] ; IP/CS/Flags and get the USER CS this mov si,PSP_MEMORY ; is used as the PSP for this function mov ax,es ; call and NOT current_psp mov cx,PSPLEN/2 ; copy whole PSP push dx call copy_psp pop es mov cx,20 ; default XFT table has twenty files mov di,offset PSP_XFT ; and is in the PSP at this offset mov PSP_XFNMAX,cx ; say we have 20 files max mov PSP_XFTOFF,di mov PSP_XFTSEG,es push ds mov ds,current_psp ; we copy 1st 20 entries of current lds si,ds:PSP_XFTPTR ; XFT to the child PSP rep movsb ; we do not update file handle use pop ds ; counts, unlike Int21/55 ret copy_psp: ; copy CX words from AX:0 to DX:0, SI = memory top push si ; Save the Memory TOP push ds mov es,dx ; Point ES to the New PSP mov ds,ax ; Get the current PSP for this function xor ax,ax mov di,ax ! mov si,ax rep movsw ; Copy into New PSP mov ds,ax ; Copy the current Terminate, Critical mov si,INT22_OFFSET ; Error and Control Break Handlers mov di,offset PSP_TERM_IP ; into the new PSP mov cl,6 rep movsw ; BREAK,TERM, CRIT ERR SAVED HERE pop ds pop PSP_MEMORY mov PSP_INT20,020CDh ; Interrupt 20h Terminate mov PSP_RES1,0FFFFh mov PSP_RES2,0FFFFh mov PSP_DOSCALL,021CDh ; INT 21h Function Call mov PSP_DOSRETF,0CBh ; RETF mov PSP_LONGCALL,09Ah ; CALLF AnySeg:MemSize mov ax,PSP_MEMORY ; Get the Top of Memory sub ax,dx ; Convert it to Memory Size cmp ax,1000h ; Check for Over 64Kb mov bx,0FEF0h ; Assume Over 64Kb jae sce_10 mov bx,ax ; Convert the Paragragh Length mov cl,4 ; to a Byte Length shl bx,cl sub bx,110h ; Reserve 110h Bytes for .COM Stack sce_10: push dx mov PSP_LONGOFF,bx ; Save the Byte Length xor dx,dx ; Call 5 Entry Segment mov ax,INT30_OFFSET ; Call 5 Entry Offset mov cl,4 shr ax,cl ; Entry Offset/16 => EO shr bx,cl ; Jump Offset/16 => JO add ax,dx ; EO + ES sub ax,bx ; EO + ES - JO => JS mov PSP_LONGSEG,ax pop dx ret ; ; ***************************** ; *** DOS Function 50 *** ; *** Set Current PSP *** ; ***************************** ; Public func50 ; WARNING - called on USER stack func50: mov current_psp,bx ret ; ***************************** ; *** DOS Function 51/62 *** ; *** Get Current PSP *** ; ***************************** ; Public func51, func62 ; WARNING - called on USER stack func51: func62: mov bx,current_psp mov reg_BX[bp],bx ret eject ;************************************************** ;************************************************** ;*** *** ;*** Process Control Functions *** ;*** *** ;************************************************** ;************************************************** ; ***************************** ; *** DOS Function 31 *** ; *** Terminate and Keep *** ; ***************************** ; Public func31 func31: mov ax,6 ; make 6 paragraphs our minimum size cmp ax,dx ; Are we at our minimum size ? jb func31_05 xchg ax,dx ; no, enforce 6 paragraphs func31_05: mov exit_type,TERM_RESIDENT ; Exit by Terminate and Stay Resident mov bx,current_psp ; and set the termination PSP to mov term_psp,bx ; be the Current PSP push ds ; Attempt to modify the memory mov ds,bx ; partition size to that given in DX mov bx,dx ; Remember DS and ES are swapped for call mem_setblock ; the internal function. mov ax,ds ; Now update the PSP_MEMORY field to add ax,bx ; reflect the memory available to mov ds:PSP_MEMORY,ax ; to the application now. Required by pop ds ; MicroPro WordFinder mov load_psp,0000 ; Do not free PSP memory jmp f31_term ; Common terminate handler ; ; ***************************** ; *** DOS Function 4B *** ; *** Load or Execute Prog *** ; ***************************** ; ; An extra sub-function has been defined which is used by the ; ROOT DOS process loader to ensure compatibility between the ; Initial Register conditions for the ROOT DOS process and that ; of any child process. ; ; 4B80h - GO Sub-Function expects all the internal and ; external data areas to have been setup by a ; previous 4B01h function. Never Fails ! ; ; Undocumented feature: ; AX=4B03 returns SETVER version in AX, or zero ; Public func4B func4B: cmp al,80h ; Is this the special GO sub-function jnz f4B_01 ; No Process Normally jmp start_child ; Go for It every thing else OK f4B_01: cmp al,5 ! je f4B05 ; Sub-Func 5:- Exec Hook cmp al,3 ! je f4B_02 ; Sub-Func 3:- Load Overlay cmp al,1 ! jbe f4B_02 ; Sub-Func 1:- Load and No Execute ; Sub-Func 0:- Load and Execute f4B_invalid: jmp invalid_function ; Otherwise illegal Sub-Function f4B05: ;----- ; On Entry: ; ES:DX -> ExecState esReserved equ word ptr 0 ; reserved, must be zero esFlags equ word ptr 2 ; type flags esProgName equ dword ptr 4 ; points to ASCIIZ name esPSP equ word ptr 8 ; PSP of new program esStartAddress equ dword ptr 10 ; CS:IP of new program esProgSize equ dword ptr 14 ; program size, including PSP ; ; type flags ES_EXE equ 0001h ES_OVERLAY equ 0002h ; ; On Exit: ; None (A20 gate disabled) ; mov di,dx ; ES:DI -> ExecState test es:esFlags[di],not ES_EXE jnz f4B_invalid ; only COM or EXE supported call return_AX_CLC ; assume success lds si,es:esProgName[di] ; DS:SI -> ASIIZ name mov es,es:esPSP[di] ; ES = PSP push es ; save for DX on exit call SetPspNameAndVersion ; set up the name/version fields pop dx ; DX = PSP push ss pop ds ; DS = pcmode data again cli ; Stop anybody interfering les bp,int21regs_ptr ; point to user stack mov es:reg_AX[bp],0 ; return successful and es:reg_FLAGS[bp],not CARRY_FLAG mov ax,prev_int21regs_off mov int21regs_off,ax mov ax,prev_int21regs_seg mov int21regs_seg,ax dec indos_flag ; no longer in DOS jmpf func4B05_stub ; exit via stub code f4B_02: xor ax,ax mov load_env,ax ; Load environment NOT allocated mov load_psp,ax ; Load memory NOT allocated dec ax mov load_handle,ax ; Mark Load file as CLOSED push es ! push dx ; expand the filename to a call get_filename ; full path to be inherited pop dx ! pop es ; in the environment jc f4B_10 ; Exit on error mov ax,(MS_X_OPEN*256)+20h ; Open File ; mov al,0$010$0$000B ; ReadOnly & DenyWrite call dos_entry jnc f4B_05 ; Save Handle if No Error cmp ax,ED_SHAREFAIL ; Check for a Sharing Error or Access jz f4B_04 ; Denied if neither error codes then cmp ax,ED_ACCESS ; Don't retry the Open function jnz f4B_10 ; in compatibility f4B_04: mov ax,(MS_X_OPEN*256)+0 ; retry the open in read-only ; mov al,0$000$0$000B ; compatibility mode call dos_entry jc f4B_10 ; Stop On error f4B_05: push ds ! pop es ; ES local again mov load_handle,ax ; Save for Error Handling xchg ax,bx ; Get the File Handle mov si,offset exe_buffer call get_execdata jc f4B_10 call point_param_block ; CL = subfunc, ES:DI -> param block cmp cl,3 ; Sub-Func 3:- Load Overlay jne f4B_go ; Sub-Func 0:- Load and Execute ; Sub-Func 1:- Load and No Execute mov si,es:2[di] ; si = Relocation Factor mov di,es:[di] ; di = Load Segment call loadimage ; load and relocate image jc f4B_10 ; f4B_error - Return with an error if DOS5 mov si,offset load_file ; Copy the process name into the DMD call FindName ; DS:SI -> start of name call GetVersion ; AX = version to return mov es,current_psp ; poke the current psp mov PSP_VERSION,ax ; with the version number endif jmp return_AX_CLC ; All done f4b_10: jmp f4B_error ; ; F4B_GO loads and executes the file whose handle is in BX. ; This routine corresponds to sub-functions 0 and 1. ; f4B_go: xor ax,ax mov si,offset exe_buffer ; .COM and .EXE file loading mov exe_loadhigh,al ; Reset the Load High Flag cmp ax,EXE_MAXPARA[si] jnz f4B_g15 ; Load High Flag (MAXPARA == 0) dec ax mov exe_loadhigh,al ; Set the internal LOADHIGH flag mov EXE_MAXPARA[si],ax ; and allocate all memory f4B_g15: mov ax,es:[di] ; get ENV pointer from param block call build_env ; Build the environment jc f4B_error ; Stop on error call calc_psp ; calculate new psp jc f4B_error ; Stop on error call pblk_to_psp ; Copy parameters into PSP mov si,load_image ; read the Load image mov di,si ; to previously calculated address call loadimage ; load in com file jc f4B_error ; quit if no memory call set_up_psp ; build child's psp mov dx,load_psp ; point at PSP seg mov exit_type,TERM_NORMAL ; Initialise the Return code type mov si,offset exe_buffer ; to normal an go call check_exe jc f4B_go_com mov dx,load_image ; Get the Load Paragraph add EXE_CS[si],dx ; bias the code segment add EXE_SS[si],dx ; and the stack segment too jmp start_child ; goodbye! ; f4B_go_com: ; Go for it .COM ; mov dx,load_psp ; based at PSP seg mov EXE_CS[si],dx ; set up initial cs:ip mov EXE_IP[si],100h ; and ss:sp for child mov EXE_SS[si],dx mov es,dx mov bx,PSP_LONGOFF ; ax = segment size in bytes add bx,110h - 2 ; Initialise stack in reserved area mov EXE_SP[si],bx ; save as stack ptr mov es:word ptr[bx],0 ; put one zero on the stack jmp start_child ; goodbye! ; ; Function 4B Error Handler. This exit routine will free all ; resources allocated to a process during the EXEC function and ; exit to the standard error handler with the original error code ; if any further errors occur they are ignored. ; f4B_error: push ax ; Save the return Code mov bx,load_handle ; Is the load file still open ? inc bx ; (FFFF = closed) jz f4B_e10 ; YES then Close dec bx mov ah,MS_X_CLOSE call dos_entry f4B_e10: ; Now Free any memory allocated mov cx,load_psp ; during the execution of FUNC4B call conditional_mem_free ; firstly free PSP/code/data memory mov cx,load_env ; Secondly free the memory allocated call conditional_mem_free ; to hold the ENVIRONMENT pop ax ; Restore the return code and exit mov valid_flg,OK_RF ; fiddle to resume func 4B if we get mov retry_sp,sp ; a critical error mov retry_off,offset func4B call error_exit ; call the standard error handler cmp ax,-ED_FORMAT ; errors less than ED_FORMAT are OK. jb f4B_e20 ; (eg. ED_MEMORY, ED_FILE) mov ax,load_handle ; if we didn't manage to open exec file inc ax ; load_handle=FFFF and we want to mov al,-ED_PATH ; return ED_PATH jz f4B_e20 ; else we had an error during the load mov al,-ED_FORMAT ; and should return ED_FORMAT f4B_e20: ret eject start_child: mov es,current_psp ; ds -> psp mov dx,0080h ; default dma offset mov ah,MS_F_DMAOFF ; Set the DMA address call dos_entry ; set child's dma address mov si,offset exe_buffer ; Get EXE Buffer Offset call point_param_block ; CL = subfunc, ES:DI -> param block cmp cl,1 jne start_child_go ; load restisters and go ; ; The following code updates the Extended parameter block ; used with the LOAD for DEBUG sub-function. ; add di,DWORD*3+WORD ; skip user supplied info mov ax,EXE_SP[si] dec ax ! dec ax ; return ss:sp-2 stosw xchg ax,bx ; save SP for later mov ax,EXE_SS[si] stosw push ds mov ds,ax mov word ptr [bx],0 ; zero on user stack pop ds lea si,EXE_IP[si] ; point at IP lodsw ! stosw ; copy it, and get in AX for return movsw ; copy EXE_CS too jmp return_AX_CLC ; all went OK start_child_go: ;-------------- ; ; Set the initial registers conditions for a DOS process ; Check the validity of the drives specified in FCB 1 and FCB 2 ; of the loading PSP and initialise the AX register accordingly. ; xor dx,dx ; start with valid drives mov es,current_psp ; Get the PSP Address and check push dx mov al,PSP_FCB1 ; if the drive specifier for FCB1 call valid_drive ; is invalid set AL to FF pop dx jz reg_s10 mov dl,0FFh reg_s10: push dx mov al,PSP_FCB2 ; if the drive specifier for FCB2 call valid_drive ; is invalid set AH to FF pop dx jz reg_s20 mov dh,0FFh reg_s20: mov di,EXE_SP[si] ; Get the new stack address push di ; save it mov cl,4 shr di,cl ; convert SP to para's jnz reg_s30 mov di,1000h ; if 0k make it 64k reg_s30: mov ax,load_max ; find top of prog area sub ax,EXE_SS[si] ; find para's left for stack cmp di,ax ; SP too high ? pop di ; assume OK jb reg_s40 mov di,ax ; no, so lower SP shl di,cl ; convert to bytes reg_s40: mov cx,EXE_SS[si] ; CX:DI -> initial stack les si,dword ptr EXE_IP[si] ; get initial CS:IP cli mov ax,current_psp ; AX = PSP we are going to use xchg ax,dx mov indos_flag,0 ; zap the indos flag if 0 mov ss,cx ; switch to new USER stack mov sp,di push es push si ; CS:IP on USER stack mov ds,dx ; DS = ES = PSP we are exec'ing mov es,dx xor bx,bx ; BX = zero, set flags sti retf ; lets go! else jmpf exec_stub endif eject ; ***************************** ; *** DOS Function 00 *** ; *** Terminate Process *** ; ***************************** ; ; This code is executed for both INT 20 and INT 21/00 and they both ; implicitly set the current PSP to the users calling CODE segment. ; This overwrites the correct value held in CURRENT_PSP. ; Public func00 func00: mov byte ptr int21AX,0 ; force return code of zero les di,int21regs_ptr mov bx,es:reg_CS[di] ; normally users CS is current_psp mov ax,current_psp ; but application call here cmp ax,bx ; with an Int 20 at funny moments je func4c ; (I have "NOW!" in mind) mov es,bx ; fiddle CS PSP parent so we return to mov PSP_PARENT,ax ; current_psp then fiddle current_psp mov current_psp,bx ; to be user CS ; ***************************** ; *** DOS Function 4C *** ; *** Terminate Process *** ; ***************************** ; Public func4C func4c: mov ax,current_psp ; the current PSP is terminating mov term_psp,ax ; so set term_psp and load_psp mov load_psp,ax ; to that value f31_term: ; INT27 and INT21/31 Entry Point push ds mov ds,term_psp xor ax,ax mov es,ax ; Copy the Three interrupt vectors mov si,offset PSP_TERM_IP ; saved on process creation from the mov di,INT22_OFFSET ; termination PSP to the interrupt mov cx,6 ; vector table. rep movsw mov ax,8200h ; call the REDIR hooks to clean up int 2ah ; first the server hook mov ax,I2F_PTERM ; then call cleanup code int 2fh ; via magic INT 2F call pop ds ; back to PCMODE data mov al,byte ptr int21AX ; Get the User Return Code mov user_retcode,al ; Save the User Ret Code and Set the mov al,TERM_NORMAL ; Now get the Termination Type xchg al,exit_type ; and exchange with the default value mov system_retcode,al ; EXIT_TYPE is set so Non-Zero values ; when a Special Form of termination ; takes place. ie INT 27h ; But thence came VTERM, and it looked upon terminating the ROOT process, ; and saw that it was good. ; ; VTERM gives access to the cmdline by doing func31 and becoming a TSR. You can ; then re-invoke it with a hot-key but the next time you invoke the cmdline ; option does a func4C in whatever context it was re-invoked in. This will ; either blow away an application, or try and terminate the ROOT process. mov es,term_psp ; make the terminating PSP's mov ax,es:PSP_PARENT ; parental PSP into the mov bx,current_psp cmp ax,bx ; Is the user trying to terminate jz f4C_20 ; the ROOT DOS process if YES then ; skip freeing resources (VTERM) mov cx,load_psp ; if we are TSR'ing jcxz f4C_20 ; skip the free push ax ; save parental PSP mov es,bx ; ES = current PSP xor bx,bx ; start with handle zero f4C_10: mov ah,MS_X_CLOSE ; close this handle call dos_entry ; so freeing up PSP entry inc bx ; onto next handle cmp bx,PSP_XFNMAX ; done them all yet? jb f4C_10 mov FD_FUNC,FD_EXIT ; Must Close all Open FCB's call fdos_nocrit push ds ; We have already closed all the pop es ; open MSNET files we know about mov ax,I2F_PCLOSE ; but we will call the MSNET int 2fh ; extention's cleanup code anyway push ss ! pop ds ; reload DS with data segment mov bx,current_psp ; free all memory associated call free_all ; with this PSP pop ax ; recover parental PSP f4C_20: mov current_psp,ax ; make current PSP = parental PSP ; ; Function 4C requires a different termination technique. It needs ; to return to the parent process on the stack that was used on the ; function 4B. The interrupt structure has been forced to contain ; the interrupt 22 vector. Therefore all registers will contain ; their original values unless the stack has been overlayed ; ; cli ; Stop anybody interfering mov indos_flag,0 ; Force the INDOS_FLAG to 0 for PCTOOLS mov error_flag,0 ; and SideKick Plus. mov ax,retcode mov ds,current_psp mov ss,ds:PSP_USERSS ; Retrieve the entry SS and SP from mov sp,ds:PSP_USERSP ; the PSP and return with all mov bp,sp ; registers as on user entry mov ss:reg_AX[bp],ax ; Set AX to the Process RETCODE xor ax,ax mov ds,ax mov ax,ds:word ptr .INT22_OFFSET mov ss:reg_IP[bp],ax ; PSP_TERM_IP mov ax,ds:word ptr .INT22_OFFSET+WORD mov ss:reg_CS[bp],ax ; PSP_TERM_CS mov ss:reg_FLAGS[bp],0b202h ; force flags to 0F202h ; ie Interrupts enabled and ; NEC processor Mode Switch SET ; changed to B202 to have clear ; NT flag (DPMS doesn't like it) jmp int21_exit ; Jump to the Exit routine eject ; ***************************** ; *** DOS Function 4D *** ; *** Get Sub-Func Ret-Code *** ; ***************************** ; Public func4D func4D: xor ax,ax ; Zero the return code for xchg ax,retcode ; subsequent calls and return the jmp return_AX_CLC ; saved value to the caller eject ;**************************************** ;* * ;* Process Control Subroutines * ;* * ;**************************************** ; ; We need a full pathname for the application to inherit in it's environment. ; MS_X_EXPAND can't do the job - it returns a PHYSICAL path which may be ; unreachable (bug circa DRDOS 3.41). ; On Entry: ; ES:DX Points to the Original FileName ; On Exit: ; None ; get_filename: push ds push es ; swap ES and DS pop ds pop es mov si,dx ; DS:SI -> filename mov di,offset load_file ; ES:DI -> local buffer mov cx,MAX_PATHLEN-4 ; max length (allow for d:\,NUL) lodsw ; get 1st two chars in filename cmp ah,':' ; is a drive specified ? je get_filename10 dec si ! dec si ; forget we looked mov al,ss:current_dsk ; and use the default drive add al,'A' get_filename10: stosb ; put in the drive and al,1fh ; convert from ASCII to 1 based xchg ax,dx ; keep in DL for ms_x_curdir mov ax,':'+256*'\' ; make it "d:\" stosw lodsb ; do we start at the root ? cmp al,'\' je get_filename20 cmp al,'/' je get_filename20 dec si ; forget we looked for a root push si ; save where we were mov ah,MS_X_CURDIR mov si,di ; ES:SI -> buffer call dos_entry ; get current directory xor ax,ax repne scasb ; look for NUL xchg ax,si ; AX = start of path pop si ; recover pointer to source jne get_filename30 dec di ; point at NUL cmp ax,di ; are we at the root ? je get_filename20 mov al,'\' stosb ; no, append a '\' get_filename20: rep movsb ; copy the remainder of the string get_filename30: xor ax,ax stosb ; ensure we are terminated push es pop ds ; DS back to nornal ret ; ; BUILD_ENV determines the size of the Source environment and ; allocates memory and finally copies it. ; ; ON entry AX contains the segment address of the environment ; to be used or zero if the parents is to be copied. build_env: mov es,ax ; Assume user has specified the or ax,ax ; environment to be used. If AX is jnz b_e10 ; 0000 then use the current environment mov es,current_psp mov cx,PSP_ENVIRON ; Current Environment Segment mov es,cx ; If the current environment segment mov di,cx ; is zero then return a size of jcxz b_e35 ; zero bytes b_e10: xor ax,ax ; Now determine the Environment size mov cx,32*1024 ; CX is maximum size mov di,ax b_e20: repnz scasb ; Look for two zero bytes which jcxz b_e40 ; mark the end of the environment cmp al,es:byte ptr [di] ; continue search till the end is found jnz b_e20 dec di ; DI == Environment Size - 2 b_e30: mov si,offset load_file ; Get the Load pathname length call strlen ; String length returned in CX inc cx ; Add in the terminator push bx mov bx,cx ; Get the String Length add bx,di ; Add the environment size add bx,15 + 4 ; and convert to paragraphs shr bx,1 ! shr bx,1 shr bx,1 ! shr bx,1 mov load_envsize,bx ; Save the Environment Size call mem_alloc ; allocate the memory pop bx jc b_e50 mov load_env,ax ; Save the Environment location push cx ! push di ; Save STRLEN and Offset push ds ; Save DS push es mov es,ax ; Point ES at the NEW environment pop ds ; Point DS at the Old environment mov cx,di ; Get the environment size xor si,si ! mov di,si ; Initialize the pointers rep movsb ; and copy. Nothing moves if CX == 0 pop ds pop di ! pop cx ; Get the string pointers xor ax,ax ! stosw ; Add terminating zeros inc ax ! stosw ; Initialise the String COUNT field mov si,offset load_file ; and size information and rep movsb ; copy the load filename. b_e35: clc ; Return with no errors ret b_e40: mov ax,ED_ENVIRON ; Invalid environment b_e50: stc ret ; Calculate the new program segment prefix ; save: bx -> Handle calc_psp: push bx mov si,offset exe_buffer ; Calculate the Minimum and Maximum ; amount of memory required to load call image_size ; the program image (Returned in DX) add dx,PSPLEN/16 ; Do not forget the PSP mov cx,dx ; Save the Load Image Size mov bx,dx ; BX will be memory required mov ax,ED_MEMORY add dx,EXE_MINPARA[si] ; force DX to be the minimum and if jc cp_exit ; more than 1 MByte exit with error add bx,EXE_MAXPARA[si] ; add the maximum amount of memory jnc c_p10 ; to the load image size mov bx,0FFFFh ; clipping to 1 MByte c_p10: if HILOAD test mem_strategy,80h ; HILOAD ON ? jz c_p15 mov bx,dx ; use minimum amount of memory add bx,40h ; add 1 K extra for luck (stack etc) call mem_alloc ; Allocate the requested block jc cp_exit ; if alloc fails exit with error push ds mov ds,ax mov bx,0ffffh ; find how much we can grow this block call mem_setblock call mem_setblock ; then grow it to that size mov ax,ds ; ax = base of the block again pop ds jmps c_p20 c_p15: endif call mem_alloc ; allocate size and if error occurs jnc c_p20 ; then the maximum size is greater cmp bx,dx ; than the minimum required jc cp_exit ; if not exit with error call mem_alloc ; Allocate what we've got jc cp_exit ; Exit on error c_p20: mov load_psp,ax ; Save the load paragraph == PSP add bx,ax ; Save the block top mov load_top,bx mov load_max,bx ; save top of block for SP adjust add ax,PSPLEN/16 ; Set AX to be the Relocation Paragraph cmp exe_loadhigh,0 ; Should the Load Image be jz c_p30 ; forced into to High Memory with the mov ax,bx ; data area and PSP loaded low. sub ax,cx ; Subtract the Load Image Size from mov cx,PSPLEN/16 ; the top of allocated memory and add ax,cx ; load at that address. c_p30: mov load_image,ax ; Save the Address of the Load Image cp_exit: pop bx ret eject ;LOADIMAGE: ; ; This function reads in the load image of the file into memory ; (Paragraph DI) asserting the relocation factor (SI) if any relocation ; items exist in the file. The size of the load image is calculated ; using the EXE_SIZE and EXE_FINAL fields enough memory exists at DI ; to load the image. The valid .EXE header has been moved to exe_buffer. ; ; Read in and relocate the EXE image ; entry: bx -> handle ; di = load segment ; si = reloc segment ; exit: cf = 1, ax = Error Code if load fails ; loadimage: ;--------- call readfile ; Read the load image into memory jc load_error ; Exit if error mov cx,exe_buffer+EXE_RELCNT ; get number of reloc entries jcxz load_done ; if none there, forget it .COM's ; drop out here because RELCNT is zero push cx ; seek to 1st relocation entry xor cx,cx ; in the file mov dx,exe_buffer+EXE_RELOFF mov ax,(MS_X_LSEEK*256)+0 call dos_entry pop cx jc load_error ; stop on error xchg ax,cx ; AX = # items to relocate call reloc_image ; relocate the image jc load_error load_done: mov load_handle,-1 mov ah,MS_X_CLOSE ; and close the loadfile jmp dos_entry ; close the com file load_error: ; Error exit from relocation push ax ; save error code call load_done ; close the file pop ax ; recover error code stc ; say we had an error ret ; ; The following code will relocate CX items from the open handle BX ; reloc_image: ; On Entry: ; BX = handle ; AX = # items to relocate ; SI = relocation segment ; DI = relocation fixup ; ; On Exit: ; CY clear if OK, else AX = error code push ds ! pop es ; ES -> Local Buffer Segment mov dx,offset reloc_buf ; DX -> Local Buffer Offset mov cx,RELOC_CNT ; AX -> Buffer Size shl cx,1 ; convert reloc size from paras shl cx,1 ; to an item count sub ax,cx ; buffer. which contains a maximum jnc reloc_i10 ; of RELOC_SIZE items. add cx,ax ; CX contains # of items to Read xor ax,ax ; AX contains # left to read reloc_i10: push ax ; save # items left to read push cx ; and # reloc to read shl cx,1 ! shl cx,1 ; calculate # byte to read mov ah,MS_X_READ ; relocation buffer. call dos_entry pop cx jnc reloc_i20 ; Exit on Error pop cx ; clean up stack ret ; return with error reloc_i20: push bx ; save handle xchg ax,di ; AX = reloc fixup mov bx,dx ; Get buffer offset reloc_i30: add word ptr 2[bx],ax ; Correct segment to Load Seg les di,dword ptr [bx] ; es:di = reloc entry add es:[di],si ; add reloc seg into image add bx,4 ; and update for next entry loop reloc_i30 xchg ax,di ; restore fixup to DI pop bx ; recover handle pop ax ; recover # left to do test ax,ax jnz reloc_image ; keep going until all done ret ;READFILE ; ; This function reads in the load image of the file into memory ; (Paragraph DI) the size of the load image is calculated using ; the EXE_SIZE and EXE_FINAL fields enough memory exists at DI ; to load the image. The valid .EXE header has been moved to ; exe_buffer. ; ; Read in a Binary Image .COM or .EXE ; entry: bx -> handle ; di = load segment ; ; exit: bx, si, di Preserved ; cf = 1, ax = Error Code if load fails ; MAX_READPARA equ 3200 ; Maximum Number of Paragraphs to ; read in one command 50Kb readfile: push si ! push di mov si,offset exe_buffer ; Get the .EXE header mov dx,EXE_HEADER[si] ; get the header size in paragraphs mov cx,4 ; and seek to that offset in the rol dx,cl ; file before reading any data mov cl,dl and cx,0Fh ! and dx,not 0Fh mov ax,(MS_X_LSEEK*256)+0 call dos_entry ; Execute LSEEK Function jc rf_error call image_size ; Get the Load Image Sizes in Paras mov si,dx ; Returned in DX save in SI rf_10: mov es,di ; Set the Buffer address sub dx,dx ; es:dx -> load segment cmp si,MAX_READPARA ; Can we read the rest of the file jbe rf_20 ; in one command jif YES sub si,MAX_READPARA ; Decrement the Image Size mov cx,MAX_READPARA * 16 ; Number of bytes to read add di,MAX_READPARA ; Number of Paragraphs Read mov ah,MS_X_READ ; Read the Block into the call dos_entry ; buffer Exit if Error jc rf_error jmps rf_10 ; Else go for the next bit rf_20: ; Now reading the last part of mov cl,4 ; the image so convert remainder shl si,cl ; in SI to bytes and Read File mov cx,si mov ah,MS_X_READ ; Read data into the buffer call dos_entry jc rf_error ; Stop on Error xor ax,ax ; Reset the carry Flag and Zero AX rf_error: ; Error exit Carry Flag Set and AX pop di ! pop si ; contains the error code. ret ; Copy old PSP contents to new PSP. ; Parameter block supplied by user contains command line ; and default FCB's - copy these into the load_psp. ; save: bx -> Handle pblk_to_psp: push ds ; Save the PcMode Data Segment push bx ; and file handle mov dx,load_psp call point_param_block ; ES:DI -> users parameter block push es ! push di lds si,es:dword ptr 2[di] ; Get the Source Pointer mov cx,128 ; Copy the complete command line mov di,offset PSP_COMLEN ; because BASCOM places a segment value mov es,dx ; after the CR which was not previously rep movsb ; copied. pop di ! pop es lds si,es:dword ptr 6[di] ; get 1st FCB address mov ax,offset PSP_FCB1 ; First FCB Offset call copy_fcb ; copy FCB lds si,es:dword ptr 10[di] ; Get the Source Pointer mov ax,offset PSP_FCB2 ; Second FCB Offset call copy_fcb ; copy FCB pop bx ; file handle back again pop ds ; Restore PcMode Data Segment ret copy_fcb: ;-------- ; On Entry: ; DS:SI -> source ; DX:AX -> destination ; On Exit: ; None ; ES:DI, DX preserved ; push es push di mov es,dx xchg ax,di ; ES:DI -> destination mov cx,12 ; Copy Drive, Name and Extension rep movsb ; and copy it xchg ax,cx ; AX = 0 stosw ! stosw ; zero last 4 bytes pop di pop es ret ; Set up a new psp for the child ; set_up_psp: mov ax,load_psp ; Change the ownership of the mov bx,load_env ; Environment and Load Memory call set_owner ; partitions. mov ax,load_psp mov bx,ax call set_owner cmp current_psp,1 ; Is This the ROOT DOS process jnz setup_psp10 ; No! Continue as Normal mov ax,load_psp ; Force the LOAD_PSP to mov current_psp,ax ; to be the current PSP mov es,ax ; Now Zero Fill the New PSP mov cx,(offset PSP_FCB1)/2 ; up to user supplied parameters xor ax,ax ! mov di,ax rep stosw jmps setup_psp20 ; and skip the INT22 Fudge setup_psp10: ; Get the Function return address xor di,di ! mov es,di ; and force into INT 22 mov di,INT22_OFFSET ; Set Interrupt Vectors 22 push ds lds si,int21regs_ptr lea si,reg_IP[si] ; DS:SI -> callers IP movsw ; Save User IP movsw ; Save User CS pop ds setup_psp20: mov dx,load_psp ; Get the new PSP address mov si,load_top ; Get the last paragraph allocated mov cx,(offset PSP_FCB1)/2 ; Copy PSP up to user supplied bits ; ; CREATE_PSP is a local function called by the DOS EXEC function (4B) ; to create a new PSP and initialize it as a new process. ; ; The PSP_MEMORY field was original calculated as the highest memory ; location that could be allocated to a process. However this caused ; Carbon Copy Plus to Fail so the routine now uses the LOAD_TOP ; value calculated by the CALC_PSP function. This is the last ; paragraph allocated to the current PSP. ; call create_psp ; Create the New Process mov ax,load_env ; Now Update the Environment mov PSP_ENVIRON,ax mov si,offset load_file ; Copy the process name into the DMD ; jmp SetPspNameAndVersion SetPspNameAndVersion: ;--------------------- ; On Entry: ; ES = PSP ; DS:SI -> pathaname (nb. DS need not be dos data seg!) ; On Exit: ; None ; mov bx,es dec bx mov es,bx ; ES points at DMD (We Hope) call check_dmd_id ; Check for a valid DMD jc SetPspNameAndVersion10 ; bail out now if none if DOS5 inc bx ; BX -> PSP again push bx ; keep it on the stack endif call FindName ; DS:SI -> start of name push si call SetName ; update the name field pop si if DOS5 call GetVersion ; AX = version to return pop es ; ES = PSP mov PSP_VERSION,ax ; set version number endif SetPspNameAndVersion10: ret FindName: ;-------- ; On Entry: ; DS:SI -> pathname of file ; On Exit: ; DS:SI -> final leaf name of file ; CX = length of leaf name ; mov cx,si ; remember start of leaf FindName10: lodsb cmp al,' ' ; end of the name ? jbe FindName30 call dbcs_lead ; is it a double byte pair ? jne FindName20 lodsb ; include the second byte jmps FindName10 FindName20: cmp al,'\' ; is it a seperator ? je FindName cmp al,'/' je FindName jmps FindName10 FindName30: xchg cx,si ; SI -> start of leaf name sub cx,si dec cx ; CX = length ret SetName: ;------- ; On Entry: ; DS:SI -> leaf name to update ; ES = DMD to update ; On Exit: ; CX preserved ; mov di,offset DMD_NAME ; point at the owners name field SetName10: lodsb cmp al,' ' ; end of the name ? jbe SetName30 call dbcs_lead ; is it a double byte pair ? jne SetName20 stosb ; copy 1st byte of pair cmp di,(offset DMD_NAME)+DMD_NAME_LEN jae SetName30 ; don't overflow if name too long movsb ; and the second jmps SetName10 SetName20: stosb cmp al,'.' ; discard all following '.' je SetName30 cmp di,(offset DMD_NAME)+DMD_NAME_LEN jb SetName10 ; don't overflow if name too long ret SetName30: dec di xor ax,ax SetName40: stosb ; zero the '.' cmp di,(offset DMD_NAME)+DMD_NAME_LEN jb SetName40 ; zero the rest of the name ret if DOS5 GetVersion: ;---------- ; On Entry: ; DS:SI -> start of name ; CX = length ; On Exit: ; AX = dos version to return ; les di,ss:setverPtr mov ax,es or ax,di ; check for a setver list jnz GetVersion30 GetVersion10: mov ax,ss:dos_version ; better use default version ret GetVersion20: mov al,es:0FFFFh[di] ; skip the name cbw inc ax ! inc ax ; skip the version add di,ax ; try the next entry GetVersion30: mov al,es:byte ptr [di] ; get length field test al,al ; end of the list ? jz GetVersion10 inc di ; point at potential name cmp al,cl ; do the lengths match ? jne GetVersion20 xor bx,bx ; start scan with 1st character GetVersion40: mov ax,ds:[bx+si] ; get a character from filename call dbcs_lead ; is it a DBCS character ? jne GetVersion50 inc bx ; we will skip 2 characters cmp ax,es:[bx+di] ; do both character match ? jmps GetVersion60 GetVersion50: call toupper ; upper case it mov ah,al ; save it mov al,es:[bx+di] ; get a character from setver list call toupper ; upper case it cmp al,ah ; do we match ? GetVersion60: jne GetVersion20 ; no, try next name in list inc bx ; we match, have we done them all ? cmp bx,cx ; check against length jb GetVersion40 mov ax,es:[bx+di] ; get version number from setver list ret endif eject ; ; GET_DATA reads the EXE header using the handle passed in BX ; get_execdata: ; On Entry: ; BX = handle ; ES:SI = buffer ; On Exit: ; CY set if error, AX = error code ; BX/SI preserved mov ah,MS_X_READ mov cx,EXE_LENGTH ; read the exe header mov dx,si ; ES:DX -> buffer call dos_entry ; try and read the data jc gd_exit ; Error Exit mov EXE_FINAL[si],0200h ; Force value to Full Page call check_exe ; all done if it's an .EXE jnc gd_exit mov ax,(MS_X_LSEEK*256)+2 ; it's a .COM xor cx,cx ; seek to end of file xor dx,dx call dos_entry ; get file length in DX:AX jc gd_exit xchg al,ah ! mov ah,dl ; DX:AX / 512 shr dx,1 ! rcr ax,1 inc ax ; Handle Final Partial Page mov EXE_SIZE[si],ax ; No. of 512 Byte Pages xor ax,ax mov EXE_HEADER[si],ax ; Load Image starts a 0000 mov EXE_RELCNT[si],ax ; No Relocation Items dec ax ; Force Maximum Memory Allocation mov EXE_MAXPARA[si],ax ; to the .COM mov EXE_MINPARA[si],0010h ; give it at least an extra 100h ; bytes for the Default Stack gd_exit: ret eject ; ; Determine if the file to be loaded is a DOS EXE format file ; if YES then return with the carry flag reset. Assume that the ; header has already been read into EXE_HEADER ; public check_exe check_exe: cmp EXE_SIGNATURE[si],'ZM' ; look for exe signature jz check_e10 cmp EXE_SIGNATURE[si],'MZ' ; look for exe signature jz check_e10 stc ; flag the error check_e10: ret ; ; IMAGE_SIZE assumes SI points to a valid EXE header and from this ; it calculates the size of the load image and returns this value ; in paragraphs in DX. AX and CX are corrupted. ; Public image_size image_size: mov dx,EXE_SIZE[si] ; No of 512 pages in System Image dec dx ; Adjust for Final Partial Page mov cl,5 ! shl dx,cl ; No. 512 Byte Blocks to Para sub dx,EXE_HEADER[si] ; Remove the Header Size mov ax,EXE_FINAL[si] add ax,15 dec cl ! shr ax,cl ; AX is Partial Block in PARA add dx,ax ; DX is Image Size in PARA's ret mem_alloc: mov ah,MS_M_ALLOC ; call DOS to allocate jmp dos_entry ; some memory mem_setblock: mov ah,MS_M_SETBLOCK ; call DOS to ajust jmp dos_entry ; a memory block conditional_mem_free: ; On Entry: ; CX = para to free ; (0 = none to free) ; On Exit: ; None ; jcxz cmem_free10 ; only free up allocated push ds ; memory mov ds,cx mov ah,MS_M_FREE ; free up a memory block call dos_entry pop ds cmem_free10: ret point_param_block: ;----------------- ; On Entry: ; None ; On Exit: ; CL = subfunction number (callers AL) ; ES:DI -> parameter block (callers ES:BX) ; AX corrupted ; les di,int21regs_ptr ; point at callers registers mov cl,es:reg_AL[di] ; CL = subfunction# (range-checked) mov ax,es:reg_BX[di] mov es,es:reg_ES[di] ; callers ES:BX -> parameter block xchg ax,di ; ES:DI -> parameter block ret PCMODE_DATA DSEG WORD extrn current_dsk:byte extrn current_psp:word extrn retcode:word ; Complete return code passed to F4B extrn user_retcode:byte ; User retcode set by funcs 4C and 31 extrn system_retcode:byte ; System retcode returns the cause of extrn switch_char:byte extrn mem_strategy:byte ; memory allocation strategy extrn int21AX:word ; Int 21's AX extrn indos_flag:byte extrn int21regs_ptr:dword extrn int21regs_off:word extrn int21regs_seg:word extrn prev_int21regs_off:word extrn prev_int21regs_seg:word extrn error_flag:byte extrn exe_buffer:word extrn valid_flg:byte extrn retry_off:word extrn retry_sp:word extrn last_drv:byte extrn exec_stub:dword extrn func4B05_stub:dword if DOS5 extrn dos_version:word extrn setverPtr:dword endif eject ; To improve Network performance the EXE relocation items are ; now read into the following buffer. All the data items contained ; between RELOC_BUF and RELOC_SIZE are destroyed by the LOADIMAGE ; sub-routine when it relocates a DOS .EXE file. ; ; Only variables which are unused after the LOADIMAGE function can ; be placed in this buffer. ; ; ******** Start of .EXE Relocation Buffer ******** ; ; We can re-use the MSNET pathname buffers during an EXEC extrn reloc_buf:byte extrn load_file:byte extrn RELOC_CNT:abs ; ; ******** End of .EXE Relocation Buffer ******** ; extrn exit_type:byte extrn term_psp:word extrn load_handle:word extrn load_env:word ; Paragraph of the new environment extrn load_envsize:word ; Size of new environment extrn load_psp:word ; Paragraph of the new PSP. extrn load_image:word ; Paragraph of the Load Image. extrn load_top:word ; Last paragraph of Allocated Memory extrn load_max:word ; ditto, but not messed with extrn exe_loadhigh:byte ; load high flag end
0
0.925939
1
0.925939
game-dev
MEDIA
0.40109
game-dev
0.986982
1
0.986982
SwagSoftware/KisakCOD
51,962
src/game/g_items.cpp
#include "game_public.h" #include <server/sv_game.h> #include <server/sv_world.h> #include <script/scr_vm.h> #include <script/scr_const.h> #ifdef KISAK_MP #include <game_mp/g_utils_mp.h> #elif KISAK_SP #include <server/sv_public.h> #include "g_local.h" #include "g_main.h" #include <qcommon/ent.h> #endif //Line 53050: 0006 : 0053ff60 int32_t *itemRegistered 82ceff60 g_items.obj void __cdecl Fill_Clip(playerState_s *ps, uint32_t weapon) { int32_t ammomove; // [esp+0h] [ebp-18h] int32_t iClipIndex; // [esp+8h] [ebp-10h] int32_t iAmmoIndex; // [esp+Ch] [ebp-Ch] int32_t inclip; // [esp+14h] [ebp-4h] iAmmoIndex = BG_AmmoForWeapon(weapon); iClipIndex = BG_ClipForWeapon(weapon); if (weapon && weapon < BG_GetNumWeapons()) { inclip = ps->ammoclip[iClipIndex]; ammomove = BG_GetWeaponDef(weapon)->iClipSize - inclip; if (ammomove > ps->ammo[iAmmoIndex]) ammomove = ps->ammo[iAmmoIndex]; if (ammomove) { ps->ammo[iAmmoIndex] -= ammomove; ps->ammoclip[iClipIndex] += ammomove; } } } int32_t __cdecl Add_Ammo(gentity_s *ent, uint32_t weaponIndex, uint8_t weaponModel, int32_t count, int32_t fillClip) { int32_t ammoIndex; // [esp+0h] [ebp-20h] int32_t oldClip; // [esp+4h] [ebp-1Ch] int32_t clipIndex; // [esp+8h] [ebp-18h] bool clipOnly; // [esp+Fh] [ebp-11h] int32_t maxWeaponAmmo; // [esp+10h] [ebp-10h] int32_t oldAmmo; // [esp+14h] [ebp-Ch] gclient_s *ps; // [esp+18h] [ebp-8h] WeaponDef *weapDef; // [esp+1Ch] [ebp-4h] int32_t counta; // [esp+34h] [ebp+14h] if (!ent) MyAssertHandler(".\\game\\g_items.cpp", 82, 0, "%s", "ent"); if (!ent->client) MyAssertHandler(".\\game\\g_items.cpp", 83, 0, "%s", "ent->client"); ps = ent->client; if (!ps) MyAssertHandler("c:\\trees\\cod3\\src\\bgame\\../bgame/bg_weapons.h", 229, 0, "%s", "ps"); if (!Com_BitCheckAssert(ps->ps.weapons, weaponIndex, 16) && !BG_PlayerHasCompatibleWeapon(&ps->ps, weaponIndex)) return 0; clipOnly = 0; weapDef = BG_GetWeaponDef(weaponIndex); ammoIndex = BG_AmmoForWeapon(weaponIndex); clipIndex = BG_ClipForWeapon(weaponIndex); oldAmmo = ps->ps.ammo[ammoIndex]; oldClip = ps->ps.ammoclip[clipIndex]; maxWeaponAmmo = BG_GetAmmoPlayerMax(&ps->ps, weaponIndex, 0); ps->ps.ammo[ammoIndex] += count; if (BG_WeaponIsClipOnly(weaponIndex)) { G_GivePlayerWeapon(&ps->ps, weaponIndex, weaponModel); clipOnly = 1; } if (fillClip || clipOnly) Fill_Clip(&ps->ps, weaponIndex); if (clipOnly) { ps->ps.ammo[ammoIndex] = 0; } else if (ps->ps.ammo[ammoIndex] > maxWeaponAmmo) { ps->ps.ammo[ammoIndex] = maxWeaponAmmo; } if (ps->ps.ammoclip[clipIndex] > weapDef->iClipSize) ps->ps.ammoclip[clipIndex] = weapDef->iClipSize; if (BG_GetWeaponDef(weaponIndex)->iSharedAmmoCapIndex >= 0) { counta = BG_GetMaxPickupableAmmo(&ps->ps, weaponIndex); if (counta < 0) { if (BG_WeaponIsClipOnly(weaponIndex)) { ps->ps.ammoclip[clipIndex] += counta; if (ps->ps.ammoclip[clipIndex] <= 0) { BG_TakePlayerWeapon(&ps->ps, weaponIndex, 1); return 0; } } else { ps->ps.ammo[ammoIndex] += counta; if (ps->ps.ammo[ammoIndex] < 0) ps->ps.ammo[ammoIndex] = 0; } } } return ps->ps.ammoclip[clipIndex] - oldClip + ps->ps.ammo[ammoIndex] - oldAmmo; } void __cdecl Touch_Item_Auto(gentity_s *ent, gentity_s *other, int32_t bTouched) { ent->active = 1; Touch_Item(ent, other, bTouched); } void __cdecl Touch_Item(gentity_s *ent, gentity_s *other, int32_t touched) { char *Guid; // eax int32_t number; // [esp-Ch] [ebp-68h] const char *szInternalName; // [esp-4h] [ebp-60h] gitem_s *item; // [esp+0h] [ebp-5Ch] char cleanname[68]; // [esp+4h] [ebp-58h] BYREF int32_t pickupEvent; // [esp+50h] [ebp-Ch] BYREF int32_t pickedUp; // [esp+54h] [ebp-8h] int32_t weapIndex; // [esp+58h] [ebp-4h] if (ent->active) { pickupEvent = 0; ent->active = 0; if (other->client) { if (other->health >= 1 && !level.clientIsSpawning) { weapIndex = ent->s.index.brushmodel % 128; item = &bg_itemlist[ent->s.index.brushmodel]; if (BG_CanItemBeGrabbed(&ent->s, &other->client->ps, touched)) { #ifdef KISAK_MP I_strncpyz(cleanname, other->client->sess.cs.name, 64); I_CleanStr(cleanname); szInternalName = BG_GetWeaponDef(weapIndex)->szInternalName; number = other->s.number; Guid = SV_GetGuid(other->s.number); G_LogPrintf("Weapon;%s;%d;%s;%s\n", Guid, number, cleanname, szInternalName); #endif iassert(item); iassert(item->giType == IT_WEAPON); pickedUp = WeaponPickup(ent, other, &pickupEvent, touched); #ifdef KISAK_MP if (pickupEvent) { if (other->client->sess.predictItemPickup) G_AddPredictableEvent(other, pickupEvent, weapIndex); else G_AddEvent(other, pickupEvent, weapIndex); } if (pickedUp) { if (ent->s.eType == ET_MISSILE) Scr_Notify(ent, scr_const.death, 0); G_FreeEntity(ent); } #elif KISAK_SP if (pickupEvent) G_AddEvent(other, pickupEvent, weapIndex); if (pickedUp) { if (ent->s.eType == ET_ITEM) Scr_Notify(ent, scr_const.death, 0); G_FreeEntity(ent); } #endif } else { PrintMessage_CannotGrabItem(ent, other, touched, item, weapIndex); } } } } } int32_t __cdecl WeaponPickup(gentity_s *weaponEnt, gentity_s *player, int32_t *pickupEvent, int32_t touched) { int32_t weapIdx; // [esp+0h] [ebp-Ch] WeaponDef *weapDef; // [esp+4h] [ebp-8h] if (!weaponEnt) MyAssertHandler(".\\game\\g_items.cpp", 503, 0, "%s", "weaponEnt"); if (!player) MyAssertHandler(".\\game\\g_items.cpp", 504, 0, "%s", "player"); if (!player->client) MyAssertHandler(".\\game\\g_items.cpp", 505, 0, "%s", "player->client"); weapIdx = weaponEnt->s.index.brushmodel % 128; weapDef = BG_GetWeaponDef(weapIdx); if (!BG_PlayerCanPickUpWeaponType(weapDef, &player->client->ps)) return 0; if (touched) return WeaponPickup_Touch(weaponEnt, player, weapIdx, pickupEvent); return WeaponPickup_Grab(weaponEnt, player, weapIdx, pickupEvent); } int32_t __cdecl WeaponPickup_Grab(gentity_s *weaponEnt, gentity_s *player, int32_t weapIdx, int32_t *pickupEvent) { uint8_t weaponModel; // [esp+3h] [ebp-Dh] int32_t gotWeapon; // [esp+4h] [ebp-Ch] gentity_s *droppedEnt; // [esp+8h] [ebp-8h] BYREF WeaponDef *weapDef; // [esp+Ch] [ebp-4h] iassert(weaponEnt); iassert(player); iassert(player->client); droppedEnt = 0; weaponModel = weaponEnt->s.index.brushmodel / 128; weapDef = BG_GetWeaponDef(weapIdx); if (weaponEnt->s.eType == ET_MISSILE) { *pickupEvent = EV_AMMO_PICKUP; WeaponPickup_Notifies(weaponEnt, 0, player, weapDef); return 1; } else { iassert(weaponEnt->r.inuse); weaponEnt->flags |= FL_WEAPON_BEING_GRABBED; gotWeapon = WeaponPickup_AddWeapon(weaponEnt, player, weapIdx, weaponModel, &droppedEnt); iassert(weaponEnt->r.inuse); weaponEnt->flags &= ~(FL_WEAPON_BEING_GRABBED); if (gotWeapon) { *pickupEvent = EV_ITEM_PICKUP; WeaponPickup_AddAmmoForNewWeapon(weaponEnt, player); if (droppedEnt) WeaponPickup_LeechFromWeaponEnt(droppedEnt, player, 0, 0, 1); WeaponPickup_Notifies(weaponEnt, droppedEnt, player, weapDef); if (weapDef->weapType != WEAPTYPE_GRENADE || weapDef->offhandClass == OFFHAND_CLASS_NONE) G_SelectWeaponIndex(player - g_entities, weapIdx); return 1; } else { return 0; } } } int32_t __cdecl WeaponPickup_AddWeapon( gentity_s *ent, gentity_s *other, int32_t weapon, uint8_t weaponModel, gentity_s **pDroppedWeapon) { const char *v6; // eax int32_t passEntityNum; // [esp+Ch] [ebp-58h] uint32_t bitNum; // [esp+14h] [ebp-50h] gentity_s *droppedEnt; // [esp+18h] [ebp-4Ch] trace_t trace; // [esp+1Ch] [ebp-48h] BYREF int32_t mask; // [esp+48h] [ebp-1Ch] float up[3]; // [esp+4Ch] [ebp-18h] BYREF playerState_s *ps; // [esp+58h] [ebp-Ch] WeaponDef *weapDef; // [esp+5Ch] [ebp-8h] int32_t playerWeapIdx; // [esp+60h] [ebp-4h] if (!ent) MyAssertHandler(".\\game\\g_items.cpp", 192, 0, "%s", "ent"); if (!other) MyAssertHandler(".\\game\\g_items.cpp", 193, 0, "%s", "other"); ps = &other->client->ps; weapDef = BG_GetWeaponDef(weapon); if (weapDef->inventoryType) goto LABEL_6; if (!ps->weapon) goto LABEL_12; bitNum = ps->weapon; if (!ps) MyAssertHandler("c:\\trees\\cod3\\src\\bgame\\../bgame/bg_weapons.h", 229, 0, "%s", "ps"); if (!Com_BitCheckAssert(ps->weapons, bitNum, 16)) return 0; LABEL_12: if (!BG_PlayerWeaponsFull_Primaries(ps)) { LABEL_6: G_GivePlayerWeapon(ps, weapon, weaponModel); return 1; } playerWeapIdx = CurrentPrimaryWeapon(ps); if (playerWeapIdx) { if (!ps) MyAssertHandler("c:\\trees\\cod3\\src\\bgame\\../bgame/bg_weapons.h", 229, 0, "%s", "ps"); if (!Com_BitCheckAssert(ps->weapons, playerWeapIdx, 16)) MyAssertHandler(".\\game\\g_items.cpp", 227, 0, "%s", "BG_PlayerHasWeapon( ps, playerWeapIdx )"); droppedEnt = Drop_Weapon(other, playerWeapIdx, ps->weaponmodels[playerWeapIdx], 0); if (droppedEnt) { droppedEnt->spawnflags = ent->spawnflags & 0xFFFFFFFE; droppedEnt->s.groundEntityNum = ent->s.groundEntityNum; if ((droppedEnt->flags & 0x1000) != 0 && ent->tagInfo && ent->tagInfo->parent) { G_SetOrigin(droppedEnt, ent->r.currentOrigin); G_SetAngle(droppedEnt, ent->r.currentAngles); G_EntLinkTo(droppedEnt, ent->tagInfo->parent, ent->tagInfo->name); } else { up[0] = ent->r.currentOrigin[0]; up[1] = ent->r.currentOrigin[1]; up[2] = ent->r.currentOrigin[2] + 2.0; mask = G_ItemClipMask(ent); if (droppedEnt->r.ownerNum.isDefined()) { passEntityNum = droppedEnt->r.ownerNum.entnum(); G_TraceCapsule(&trace, ent->r.currentOrigin, droppedEnt->r.mins, droppedEnt->r.maxs, up, passEntityNum, mask); } else { G_TraceCapsule(&trace, ent->r.currentOrigin, droppedEnt->r.mins, droppedEnt->r.maxs, up, ENTITYNUM_NONE, mask); } if (trace.allsolid) { G_SetOrigin(droppedEnt, ent->r.currentOrigin); } else { Vec3Lerp(ent->r.currentOrigin, up, trace.fraction, up); if (droppedEnt->r.ownerNum.isDefined()) { G_TraceCapsule(&trace, up, droppedEnt->r.mins, droppedEnt->r.maxs, ent->r.currentOrigin, droppedEnt->r.ownerNum.entnum(), mask); } else { G_TraceCapsule(&trace, up, droppedEnt->r.mins, droppedEnt->r.maxs, ent->r.currentOrigin, ENTITYNUM_NONE, mask); } Vec3Lerp(up, ent->r.currentOrigin, trace.fraction, up); G_SetOrigin(droppedEnt, up); } G_SetAngle(droppedEnt, ent->r.currentAngles); } SV_LinkEntity(droppedEnt); } *pDroppedWeapon = droppedEnt; G_GivePlayerWeapon(ps, weapon, weaponModel); return 1; } else { #ifdef KISAK_MP v6 = va("%c \"GAME_CANT_GET_PRIMARY_WEAP_MESSAGE\"", 102); SV_GameSendServerCommand(other - g_entities, SV_CMD_CAN_IGNORE, v6); return 0; #elif KISAK_SP SV_GameSendServerCommand(other - g_entities, va("gm \"GAME_CANT_GET_PRIMARY_WEAP_MESSAGE\"")); return 0; #endif } } int32_t __cdecl CurrentPrimaryWeapon(playerState_s *ps) { int32_t weapIdx; // [esp+0h] [ebp-8h] WeaponDef *weapDef; // [esp+4h] [ebp-4h] if (!ps) MyAssertHandler(".\\game\\g_items.cpp", 148, 0, "%s", "ps"); if (!ps->weapon) return 0; weapIdx = ps->weapon; weapDef = BG_GetWeaponDef(weapIdx); if (weapDef->inventoryType == WEAPINVENTORY_ALTMODE) { weapIdx = weapDef->altWeaponIndex; weapDef = BG_GetWeaponDef(weapIdx); } if (!ps) MyAssertHandler("c:\\trees\\cod3\\src\\bgame\\../bgame/bg_weapons.h", 229, 0, "%s", "ps"); if (!Com_BitCheckAssert(ps->weapons, weapIdx, 16)) return 0; if (weapDef->inventoryType) return 0; return weapIdx; } int32_t __cdecl G_ItemClipMask(gentity_s *ent) { if (!ent) MyAssertHandler(".\\game\\g_items.cpp", 176, 0, "%s", "ent"); if (ent->clipmask) return ent->clipmask; else return 1169; } bool __cdecl WeaponPickup_LeechFromWeaponEnt( gentity_s *weaponEnt, gentity_s *player, int32_t haveExactWeapon, int32_t *pickupEvent, bool suppressNotifies) { int32_t v5; // eax uint8_t weaponModel; // [esp+3h] [ebp-1Dh] int32_t ammoTaken; // [esp+4h] [ebp-1Ch] uint32_t weapIdx; // [esp+8h] [ebp-18h] WeaponDef *weapDef; // [esp+Ch] [ebp-14h] int32_t ammoAvailable; // [esp+10h] [ebp-10h] item_ent_t *itemEnt; // [esp+14h] [ebp-Ch] int32_t i; // [esp+18h] [ebp-8h] bool removedAnyAmmo; // [esp+1Fh] [ebp-1h] if (!weaponEnt) MyAssertHandler(".\\game\\g_items.cpp", 295, 0, "%s", "weaponEnt"); if (!player) MyAssertHandler(".\\game\\g_items.cpp", 296, 0, "%s", "player"); removedAnyAmmo = 0; for (i = 0; i < 2; ++i) { v5 = weaponEnt->item[i].index % 128; weapIdx = v5; if (v5 > 0) { weaponModel = weaponEnt->item[i].index / 128; weapDef = BG_GetWeaponDef(v5); itemEnt = &weaponEnt->item[i]; ammoAvailable = itemEnt->ammoCount; if (haveExactWeapon) ammoAvailable += weaponEnt->item[i].clipAmmoCount; ammoTaken = Add_Ammo(player, weapIdx, weaponModel, ammoAvailable, 0); if (ammoTaken) { removedAnyAmmo = 1; if (!suppressNotifies && pickupPrints->current.enabled) PrintPlayerPickupMessage(player, weapIdx, weapDef); itemEnt->ammoCount -= ammoTaken; if (itemEnt->ammoCount < 0) { weaponEnt->item[i].clipAmmoCount += weaponEnt->item[i].ammoCount; itemEnt->ammoCount = 0; if (weaponEnt->item[i].clipAmmoCount < 0) weaponEnt->item[i].clipAmmoCount = 0; } } } } if (!suppressNotifies && removedAnyAmmo) { if (!pickupEvent) MyAssertHandler(".\\game\\g_items.cpp", 345, 0, "%s", "pickupEvent"); *pickupEvent = 9; } return haveExactWeapon && removedAnyAmmo; } void __cdecl PrintPlayerPickupMessage(gentity_s *player, uint32_t weapIdx, WeaponDef *weapDef) { const char *v3; // eax iassert(player); iassert(weapDef); #ifdef KISAK_MP if (BG_WeaponIsClipOnly(weapIdx)) v3 = va("*WARNING* One or more selections were skipped as they could not be interpreted as c data", 102, weapDef->szDisplayName); else v3 = va("*WARNING* One or more selections were skipped as they could not be interpreted as c data", 102, weapDef->szDisplayName); SV_GameSendServerCommand(player - g_entities, SV_CMD_CAN_IGNORE, v3); #elif KISAK_SP const char *v8; if (BG_WeaponIsClipOnly(weapIdx)) v8 = va("gm \"GAME_PICKUP_CLIPONLY_AMMO %s\"", weapDef->szDisplayName); else v8 = va("gm \"GAME_PICKUP_AMMO %s\"", weapDef->szDisplayName); SV_GameSendServerCommand(player - g_entities, v8); #endif } void __cdecl WeaponPickup_AddAmmoForNewWeapon(gentity_s *weaponEnt, gentity_s *player) { gclient_s *client; // esi int32_t i; // [esp+4h] [ebp-18h] uint8_t weaponModel; // [esp+Bh] [ebp-11h] int32_t weapon; // [esp+10h] [ebp-Ch] int32_t clipAmmo; // [esp+14h] [ebp-8h] WeaponDef *weapDef; // [esp+18h] [ebp-4h] for (i = 0; i < 2; ++i) { weapon = weaponEnt->item[i].index % 128; weaponModel = weaponEnt->item[i].index / 128; if (weapon > 0) { weapDef = BG_GetWeaponDef(weapon); clipAmmo = weaponEnt->item[i].clipAmmoCount; if (clipAmmo >= 0) { if (clipAmmo > weapDef->iClipSize) MyAssertHandler(".\\game\\g_items.cpp", 379, 0, "%s", "clipAmmo <= weapDef->iClipSize"); client = player->client; client->ps.ammoclip[BG_ClipForWeapon(weapon)] = clipAmmo; } Add_Ammo(player, weapon, weaponModel, weaponEnt->item[i].ammoCount, clipAmmo == -1); } } } void __cdecl WeaponPickup_Notifies( gentity_s *thisItem, gentity_s *newDroppedItem, gentity_s *player, WeaponDef *weapDef) { if (!thisItem) MyAssertHandler(".\\game\\g_items.cpp", 392, 0, "%s", "thisItem"); if (!player) MyAssertHandler(".\\game\\g_items.cpp", 393, 0, "%s", "player"); if (!weapDef) MyAssertHandler(".\\game\\g_items.cpp", 394, 0, "%s", "weapDef"); if (newDroppedItem) Scr_AddEntity(newDroppedItem); else Scr_AddUndefined(); Scr_AddEntity(player); Scr_Notify(thisItem, scr_const.trigger, 2u); } bool __cdecl WeaponPickup_Touch(gentity_s *weaponEnt, gentity_s *player, int32_t weapIdx, int32_t *pickupEvent) { gclient_s *client; // [esp+0h] [ebp-14h] bool haveExactWeapon; // [esp+8h] [ebp-Ch] bool removeWeaponFromWorld; // [esp+Fh] [ebp-5h] WeaponDef *weapDef; // [esp+10h] [ebp-4h] if (!weaponEnt) MyAssertHandler(".\\game\\g_items.cpp", 474, 0, "%s", "weaponEnt"); if (!player) MyAssertHandler(".\\game\\g_items.cpp", 475, 0, "%s", "player"); if (!player->client) MyAssertHandler(".\\game\\g_items.cpp", 476, 0, "%s", "player->client"); if (!pickupEvent) MyAssertHandler(".\\game\\g_items.cpp", 477, 0, "%s", "pickupEvent"); weapDef = BG_GetWeaponDef(weapIdx); client = player->client; if (!client) MyAssertHandler("c:\\trees\\cod3\\src\\bgame\\../bgame/bg_weapons.h", 229, 0, "%s", "ps"); haveExactWeapon = Com_BitCheckAssert(client->ps.weapons, weapIdx, 16); if (!haveExactWeapon && !BG_PlayerHasCompatibleWeapon(&player->client->ps, weapIdx)) return 0; removeWeaponFromWorld = WeaponPickup_LeechFromWeaponEnt(weaponEnt, player, haveExactWeapon, pickupEvent, 0); if (*pickupEvent) WeaponPickup_Notifies(weaponEnt, 0, player, weapDef); return removeWeaponFromWorld; } void __cdecl PrintMessage_CannotGrabItem(gentity_s *ent, gentity_s *player, int32_t touched, gitem_s *item, int32_t weapIndex) { WeaponDef *WeaponDef; // eax const char *v6; // eax gclient_s *ps; // [esp+0h] [ebp-4h] iassert(ent); iassert(player); iassert(player->client); iassert(item); if (!touched) { #ifdef KISAK_MP if (ent->s.clientNum != player->s.number) #endif { iassert(item->giType == IT_WEAPON); #ifdef KISAK_MP ps = player->client; iassert(ps); if (Com_BitCheckAssert(ps->ps.weapons, weapIndex, 16)) { WeaponDef = BG_GetWeaponDef(weapIndex); v6 = va("%c \"GAME_PICKUP_CANTCARRYMOREAMMO", 102, WeaponDef->szDisplayName); } else { v6 = va("%c \"GAME_CANT_GET_PRIMARY_WEAP_MESSAGE\"", 102); } SV_GameSendServerCommand(player - g_entities, SV_CMD_CAN_IGNORE, v6); #elif KISAK_SP const char *v10; if (BG_PlayerHasWeapon(&player->client->ps, weapIndex)) { WeaponDef = BG_GetWeaponDef(weapIndex); v10 = va("gm \"GAME_PICKUP_CANTCARRYMOREAMMO %s\"", WeaponDef->szDisplayName); } else { v10 = va("gm \"GAME_CANT_GET_PRIMARY_WEAP_MESSAGE\""); } SV_GameSendServerCommand(player - g_entities, v10); #endif } } } #ifdef KISAK_MP void __cdecl DroppedItemClearOwner(gentity_s *pSelf) { pSelf->s.clientNum = 64; } #endif void __cdecl G_GetItemClassname(const gitem_s *item, uint16_t *out) { char classname[256]; // [esp+4h] [ebp-108h] BYREF WeaponDef *weapDef; // [esp+108h] [ebp-4h] weapDef = BG_GetWeaponDef((((char *)item - (char *)bg_itemlist) >> 2) % 128); Com_sprintf(classname, 0x100u, "weapon_%s", weapDef->szInternalName); G_SetConstString(out, classname); } gentity_s *__cdecl Drop_Item(gentity_s *ent, const gitem_s *item, float angle, int32_t novelocity) { float velocity[3]; // [esp+10h] [ebp-24h] BYREF float angles[3]; // [esp+1Ch] [ebp-18h] BYREF float vPos[3]; // [esp+28h] [ebp-Ch] BYREF angles[0] = ent->r.currentAngles[0]; angles[1] = ent->r.currentAngles[1] + angle; angles[0] = 0.0; angles[2] = 0.0; if (novelocity) { velocity[0] = 0.0; velocity[1] = 0.0; velocity[2] = 0.0; } else { AngleVectors(angles, velocity, 0, 0); #ifdef KISAK_MP Vec3Scale(velocity, g_dropForwardSpeed->current.value, velocity); velocity[2] = crandom() * g_dropUpSpeedRand->current.value + g_dropUpSpeedBase->current.value + velocity[2]; velocity[0] = crandom() * g_dropHorzSpeedRand->current.value + velocity[0]; velocity[1] = crandom() * g_dropHorzSpeedRand->current.value + velocity[1]; #elif KISAK_SP Vec3Scale(velocity, 150.0f, velocity); velocity[2] = (float)((float)((float)(G_crandom() * (float)50.0) + velocity[2]) + (float)200.0); #endif } #ifdef KISAK_MP vPos[0] = ent->r.currentOrigin[0]; vPos[1] = ent->r.currentOrigin[1]; vPos[2] = ent->r.currentOrigin[2]; vPos[2] = (ent->r.maxs[2] - ent->r.mins[2]) * 0.5 + vPos[2]; #elif KISAK_SP float v8 = (float)(ent->r.maxs[2] - ent->r.mins[2]); vPos[0] = ent->r.currentOrigin[0]; vPos[2] = (float)((float)((float)v8 * (float)0.5) + ent->r.currentOrigin[2]); vPos[1] = ent->r.currentOrigin[1]; #endif return LaunchItem(item, vPos, angles, velocity, ent->s.number); } gentity_s *__cdecl LaunchItem(const gitem_s *item, float *origin, float *angles, float *velocity, int32_t ownerNum) { char *Name; // eax gentity_s *dropped; // [esp+30h] [ebp-18h] int32_t dropIdx; // [esp+34h] [ebp-14h] int32_t itemIndex; // [esp+38h] [ebp-10h] uint8_t weapModel; // [esp+43h] [ebp-5h] WeaponDef *weapDef; // [esp+44h] [ebp-4h] iassert(item); iassert(!IS_NAN((origin)[0]) && !IS_NAN((origin)[1]) && !IS_NAN((origin)[2])); iassert(!IS_NAN((velocity)[0]) && !IS_NAN((velocity)[1]) && !IS_NAN((velocity)[2])); itemIndex = ((char *)item - (char *)bg_itemlist) >> 2; dropped = G_Spawn(); dropIdx = GetFreeDropCueIdx(); level.droppedWeaponCue[dropIdx].setEnt(dropped); dropped->s.eType = ET_ITEM; dropped->s.index.brushmodel = itemIndex; G_GetItemClassname(item, &dropped->classname); dropped->item[0].index = itemIndex; iassert(item->giType == IT_WEAPON); dropped->r.mins[0] = -1.0; dropped->r.mins[1] = -1.0; dropped->r.mins[2] = -1.0; dropped->r.maxs[0] = 1.0; dropped->r.maxs[1] = 1.0; dropped->r.maxs[2] = 1.0; #ifdef KISAK_MP dropped->r.contents = 1079771400; dropped->r.contents |= 0x200000u; dropped->s.clientNum = ownerNum; #elif KISAK_SP dropped->r.contents = 1081868552; #endif weapModel = itemIndex / 128; weapDef = BG_GetWeaponDef(itemIndex % 128); iassert(weapDef); if (weapDef->worldModel[weapModel]) { Name = (char *)XModelGetName(weapDef->worldModel[weapModel]); G_SetModel(dropped, Name); } G_DObjUpdate(dropped); dropped->handler = ENT_HANDLER_DROPPED_ITEM; G_SetOrigin(dropped, origin); dropped->s.lerp.pos.trType = TR_GRAVITY; dropped->s.lerp.pos.trTime = level.time; dropped->s.lerp.pos.trDelta[0] = velocity[0]; dropped->s.lerp.pos.trDelta[1] = velocity[1]; dropped->s.lerp.pos.trDelta[2] = velocity[2]; G_SetAngle(dropped, angles); iassert(!IS_NAN((dropped->s.lerp.pos.trDelta)[0]) && !IS_NAN((dropped->s.lerp.pos.trDelta)[1]) && !IS_NAN((dropped->s.lerp.pos.trDelta)[2])); #ifdef KISAK_MP dropped->flags = FL_DROPPED_ITEM; dropped->nextthink = level.time + 1000; #elif KISAK_SP dropped->flags = (FL_DROPPED_ITEM | FL_SUPPORTS_LINKTO); #endif SV_LinkEntity(dropped); return dropped; } int32_t __cdecl GetFreeDropCueIdx() { float diff[3]; // [esp+0h] [ebp-38h] BYREF int32_t weapIndex; // [esp+Ch] [ebp-2Ch] WeaponDef *weapDef; // [esp+10h] [ebp-28h] int32_t iBest; // [esp+14h] [ebp-24h] int32_t j; // [esp+18h] [ebp-20h] int32_t maxDroppedWeapon; // [esp+1Ch] [ebp-1Ch] float fDistSqrd; // [esp+20h] [ebp-18h] float fBestDistSqrd; // [esp+24h] [ebp-14h] gclient_s *pClient; // [esp+28h] [ebp-10h] float fClientDistSqrd; // [esp+2Ch] [ebp-Ch] gentity_s *ent; // [esp+30h] [ebp-8h] #ifdef KISAK_MP maxDroppedWeapon = g_maxDroppedWeapons->current.integer; iassert(maxDroppedWeapon >= 1 && maxDroppedWeapon <= 32); #elif KISAK_SP maxDroppedWeapon = 32; // LWSS Hack. There is no dvar on SP, but the array is len 32 #endif iBest = -1; fBestDistSqrd = -1.0; for (int i = 0; i < maxDroppedWeapon; ++i) { if (!level.droppedWeaponCue[i].isDefined()) return i; ent = level.droppedWeaponCue[i].ent(); if ((ent->flags & 0x1000000) == 0) { if (bg_itemlist[ent->s.index.brushmodel].giType != IT_WEAPON) MyAssertHandler(".\\game\\g_items.cpp", 670, 0, "%s", "bg_itemlist[ ent->s.index.item ].giType == IT_WEAPON"); weapIndex = ent->item[0].index % 128; weapDef = BG_GetWeaponDef(weapIndex); if (!weapDef->avoidDropCleanup) { fDistSqrd = 9.9999803e11f; for (j = 0; j < level.maxclients; ++j) { pClient = &level.clients[j]; #ifdef KISAK_MP if (pClient->sess.connected == CON_CONNECTED && pClient->sess.sessionState == SESS_STATE_PLAYING) #endif { Vec3Sub(ent->r.currentOrigin, g_entities[j].r.currentOrigin, diff); fClientDistSqrd = Vec3LengthSq(diff); if (fDistSqrd > fClientDistSqrd) fDistSqrd = fClientDistSqrd; } } if (fBestDistSqrd < fDistSqrd) { fBestDistSqrd = fDistSqrd; iBest = i; } } } } if (iBest == -1) { Com_PrintWarning(16, "Could not find a suitable weapon entity to free out of %i possible. Using index zero.\n", maxDroppedWeapon); iBest = 0; } ent = level.droppedWeaponCue[iBest].ent(); iassert(ent); G_FreeEntity(ent); level.droppedWeaponCue[iBest].setEnt(NULL); return iBest; } bool __cdecl PlayerHasAnyAmmoToTransferToWeapon(gentity_s *player, uint32_t transferWeapon) { if (!player->client) MyAssertHandler(".\\game\\g_items.cpp", 890, 0, "%s", "player->client"); return player->client->ps.ammoclip[BG_ClipForWeapon(transferWeapon)] > 0 || GetNonClipAmmoToTransferToWeaponEntity(player, transferWeapon) > 0; } int32_t __cdecl GetNonClipAmmoToTransferToWeaponEntity(gentity_s *player, uint32_t transferWeapon) { int32_t ammoIndex; // [esp+0h] [ebp-10h] int32_t ammoDrop; // [esp+Ch] [ebp-4h] ammoIndex = BG_AmmoForWeapon(transferWeapon); BG_ClipForWeapon(transferWeapon); ammoDrop = player->client->ps.ammo[ammoIndex] - BG_GetAmmoPlayerMax(&player->client->ps, transferWeapon, transferWeapon); if (ammoDrop < 0) return 0; return ammoDrop; } gentity_s *__cdecl Drop_Weapon(gentity_s *ent, int32_t weapIdx, uint8_t weaponModel, uint32_t tag) { WeaponDef *WeaponDef; // eax gclient_s *v7; // esi int32_t v8; // eax float *currentOrigin; // [esp+Ch] [ebp-80h] float *trBase; // [esp+10h] [ebp-7Ch] gclient_s *client; // [esp+14h] [ebp-78h] trace_t trace; // [esp+18h] [ebp-74h] BYREF float vCenter[3]; // [esp+44h] [ebp-48h] BYREF mat4x3 tagMat; // [esp+50h] [ebp-3Ch] BYREF uint32_t altWeaponIndex; // [esp+80h] [ebp-Ch] gentity_s *dropEnt; // [esp+84h] [ebp-8h] const gitem_s *weapItem; // [esp+88h] [ebp-4h] if (BG_GetWeaponDef(weapIdx)->inventoryType == WEAPINVENTORY_ALTMODE) { altWeaponIndex = BG_GetWeaponDef(weapIdx)->altWeaponIndex; if (!altWeaponIndex) { WeaponDef = BG_GetWeaponDef(weapIdx); Com_PrintError( 15, "Drop_Weapon(): Trying to drop alt-type weapon, \"%s\", but it has no corresponding altWeapon set.\n", WeaponDef->szInternalName); return 0; } weapIdx = altWeaponIndex; } weapItem = &bg_itemlist[128 * weaponModel + weapIdx]; iassert(weapItem->giType == IT_WEAPON); if (ent->client) { client = ent->client; if (!client) MyAssertHandler("c:\\trees\\cod3\\src\\bgame\\../bgame/bg_weapons.h", 229, 0, "%s", "ps"); if (!Com_BitCheckAssert(client->ps.weapons, weapIdx, 16) || !PlayerHasAnyAmmoToTransferToWeapon(ent, weapIdx)) goto LABEL_15; } if (!BG_GetWeaponDef(weapIdx)->bClipOnly || (v7 = ent->client, v7->ps.ammoclip[BG_ClipForWeapon(weapIdx)])) { dropEnt = Drop_Item(ent, weapItem, 0.0, 0); if (ent->client) { TransferPlayerAmmoToWeaponEntity(ent, dropEnt, weapIdx); BG_TakePlayerWeapon(&ent->client->ps, weapIdx, 1); } else { TransferRandomAmmoToWeaponEntity(dropEnt, weapIdx); } if (tag) { if (G_DObjGetWorldTagMatrix(ent, tag, tagMat)) { Vec3Avg(ent->r.mins, ent->r.maxs, vCenter); Vec3Add(vCenter, ent->r.currentOrigin, vCenter); v8 = G_ItemClipMask(dropEnt); G_TraceCapsule(&trace, vCenter, dropEnt->r.mins, dropEnt->r.maxs, tagMat[3], ent->s.number, v8); Vec3Lerp(vCenter, tagMat[3], trace.fraction, dropEnt->s.lerp.pos.trBase); currentOrigin = dropEnt->r.currentOrigin; trBase = dropEnt->s.lerp.pos.trBase; dropEnt->r.currentOrigin[0] = dropEnt->s.lerp.pos.trBase[0]; currentOrigin[1] = trBase[1]; currentOrigin[2] = trBase[2]; dropEnt->s.lerp.pos.trTime = level.time; } G_SetAngle(dropEnt, ent->r.currentAngles); } return dropEnt; } else { LABEL_15: BG_TakePlayerWeapon(&ent->client->ps, weapIdx, 1); return 0; } } int32_t __cdecl TransferPlayerAmmoToWeaponEntity(gentity_s *player, gentity_s *weaponEnt, int32_t transferWeapon) { int32_t NonClipAmmoToTransferToWeaponEntity; // eax int32_t clipIndex; // [esp+4h] [ebp-14h] int32_t i; // [esp+Ch] [ebp-Ch] int32_t total; // [esp+10h] [ebp-8h] total = 0; for (i = 0; i < 2; ++i) { if (transferWeapon > 0) { clipIndex = BG_ClipForWeapon(transferWeapon); NonClipAmmoToTransferToWeaponEntity = GetNonClipAmmoToTransferToWeaponEntity(player, transferWeapon); weaponEnt->item[i].index = transferWeapon; weaponEnt->item[i].ammoCount = NonClipAmmoToTransferToWeaponEntity; weaponEnt->item[i].clipAmmoCount = player->client->ps.ammoclip[clipIndex]; total += weaponEnt->item[i].clipAmmoCount + weaponEnt->item[i].ammoCount; transferWeapon = BG_GetWeaponDef(transferWeapon)->altWeaponIndex; } } return total; } int32_t __cdecl TransferRandomAmmoToWeaponEntity(gentity_s *weaponEnt, int32_t transferWeapon) { int32_t i; // [esp+0h] [ebp-20h] int32_t iDropAmmo; // [esp+4h] [ebp-1Ch] int32_t iDropAmmoa; // [esp+4h] [ebp-1Ch] int32_t iMax; // [esp+8h] [ebp-18h] int32_t total; // [esp+Ch] [ebp-14h] int32_t iMin; // [esp+10h] [ebp-10h] int32_t iDropClip; // [esp+18h] [ebp-8h] WeaponDef *weapDef; // [esp+1Ch] [ebp-4h] total = 0; for (i = 0; i < 2; ++i) { if (transferWeapon > 0) { weapDef = BG_GetWeaponDef(transferWeapon); if (weapDef->iSharedAmmoCapIndex >= 0 && i) return total; iMax = weapDef->iDropAmmoMax; iMin = weapDef->iDropAmmoMin; if (iMax < iMin) { iMax = weapDef->iDropAmmoMin; iMin = weapDef->iDropAmmoMax; } if (iMax >= 0) { if (iMax < iMin) MyAssertHandler(".\\game\\g_items.cpp", 976, 0, "%s", "iMax >= iMin"); iDropAmmoa = iMin + G_rand() % (iMax - iMin + 1); if (iDropAmmoa > 0) { if (weapDef->iClipSize < 0) MyAssertHandler(".\\game\\g_items.cpp", 986, 0, "%s", "weapDef->iClipSize >= 0"); if (weapDef->iClipSize == 1) iDropClip = 1; else iDropClip = G_rand() % (weapDef->iClipSize + 1); if (iDropClip < iDropAmmoa) { iDropAmmo = iDropAmmoa - iDropClip; } else { iDropClip = iDropAmmoa; iDropAmmo = 0; } } else { iDropAmmo = 0; iDropClip = 0; } } else { iDropAmmo = 0; iDropClip = 0; } weaponEnt->item[i].index = transferWeapon; weaponEnt->item[i].ammoCount = iDropAmmo; weaponEnt->item[i].clipAmmoCount = iDropClip; transferWeapon = BG_GetWeaponDef(transferWeapon)->altWeaponIndex; total += weaponEnt->item[i].clipAmmoCount + weaponEnt->item[i].ammoCount; } } return total; } void __cdecl FinishSpawningItem(gentity_s *ent) { float v4; // [esp+10h] [ebp-BCh] float v5; // [esp+14h] [ebp-B8h] float v6; // [esp+20h] [ebp-ACh] float v7; // [esp+24h] [ebp-A8h] float vAngles[3]; // [esp+2Ch] [ebp-A0h] BYREF float vAxis[3][3]; // [esp+38h] [ebp-94h] BYREF gitem_s *item; // [esp+5Ch] [ebp-70h] float mins[3]; // [esp+60h] [ebp-6Ch] BYREF float start[3]; // [esp+6Ch] [ebp-60h] BYREF float maxs[3]; // [esp+78h] [ebp-54h] BYREF float endpos[3]; // [esp+84h] [ebp-48h] BYREF trace_t tr; // [esp+90h] [ebp-3Ch] BYREF float dest[3]; // [esp+BCh] [ebp-10h] BYREF int32_t clipMask; // [esp+C8h] [ebp-4h] ent->handler = ENT_HANDLER_ITEM; if ((ent->spawnflags & 1) != 0) { G_SetOrigin(ent, ent->r.currentOrigin); } else { item = &bg_itemlist[ent->s.index.brushmodel]; iassert(item->giType == IT_WEAPON); mins[0] = -1.0; mins[1] = -1.0; mins[2] = -1.0; maxs[0] = 1.0; maxs[1] = 1.0; maxs[2] = 1.0; clipMask = G_ItemClipMask(ent); start[0] = ent->r.currentOrigin[0]; start[1] = ent->r.currentOrigin[1]; start[2] = ent->r.currentOrigin[2]; v6 = ent->r.currentOrigin[1]; v7 = ent->r.currentOrigin[2] - 4096.0; dest[0] = ent->r.currentOrigin[0]; dest[1] = v6; dest[2] = v7; G_TraceCapsule(&tr, start, mins, maxs, dest, ent->s.number, clipMask); if (tr.startsolid) { start[0] = ent->r.currentOrigin[0]; start[1] = ent->r.currentOrigin[1]; start[2] = ent->r.currentOrigin[2]; start[2] = start[2] - 15.0; v4 = ent->r.currentOrigin[1]; v5 = ent->r.currentOrigin[2] - 4096.0; dest[0] = ent->r.currentOrigin[0]; dest[1] = v4; dest[2] = v5; G_TraceCapsule(&tr, start, mins, maxs, dest, ent->s.number, clipMask); } if (tr.startsolid) { Com_Printf(15, "FinishSpawningItem: %s startsolid at %s\n", SL_ConvertToString(ent->classname), vtos(ent->r.currentOrigin)); G_FreeEntity(ent); return; } ent->s.groundEntityNum = Trace_GetEntityHitId(&tr); g_entities[ent->s.groundEntityNum].flags |= FL_GROUND_ENT; Vec3Lerp(start, dest, tr.fraction, endpos); G_SetOrigin(ent, endpos); if (tr.fraction < 1.0) { vAxis[2][0] = tr.normal[0]; vAxis[2][1] = tr.normal[1]; vAxis[2][2] = tr.normal[2]; AngleVectors(ent->r.currentAngles, vAxis[0], 0, 0); Vec3Cross(vAxis[2], vAxis[0], vAxis[1]); Vec3Cross(vAxis[1], vAxis[2], vAxis[0]); AxisToAngles(vAxis, vAngles); if (bg_itemlist[ent->s.index.brushmodel].giType != IT_WEAPON) MyAssertHandler(".\\game\\g_items.cpp", 1176, 0, "%s", "bg_itemlist[ent->s.index.item].giType == IT_WEAPON"); vAngles[2] = vAngles[2] + 90.0; G_SetAngle(ent, vAngles); } } SV_LinkEntity(ent); } void __cdecl ClearRegisteredItems() { memset((uint8_t *)itemRegistered, 0, sizeof(itemRegistered)); itemRegistered[0] = 1; } #ifdef KISAK_MP void __cdecl SaveRegisteredWeapons() { char dest[8196]; // [esp+0h] [ebp-2010h] BYREF uint32_t weaponIndex; // [esp+2008h] [ebp-8h] WeaponDef *WeaponDef; // [esp+200Ch] [ebp-4h] level.registerWeapons = 0; dest[0] = 0; WeaponDef = 0; for (weaponIndex = 1; weaponIndex < BG_GetNumWeapons(); ++weaponIndex) { if (WeaponDef) I_strncat(dest, 0x2000, " "); WeaponDef = BG_GetWeaponDef(weaponIndex); I_strncat(dest, 0x2000, (char *)WeaponDef->szInternalName); } SV_SetConfigstring(2258, dest); } #endif void __cdecl SaveRegisteredItems() { char string[128]; // [esp+0h] [ebp-98h] BYREF int32_t modelIdx; // [esp+84h] [ebp-14h] int32_t bits; // [esp+88h] [ebp-10h] int32_t weapIdx; // [esp+8Ch] [ebp-Ch] int32_t n; // [esp+90h] [ebp-8h] int32_t digit; // [esp+94h] [ebp-4h] level.bRegisterItems = 0; n = 0; digit = 0; bits = 0; for (weapIdx = 0; weapIdx < 128; ++weapIdx) { for (modelIdx = 0; modelIdx < 16; ++modelIdx) { if (itemRegistered[128 * modelIdx + weapIdx]) { digit += 1 << bits; break; } } if (++bits == 4) { string[n++] = digit + (digit >= 10 ? 87 : 48); digit = 0; bits = 0; } } if (bits) string[n++] = digit + (digit >= 10 ? 87 : 48); string[n] = 0; SV_SetConfigstring(2314, string); } void __cdecl G_RegisterWeapon(uint32_t weapIndex) { char *Name; // eax char *v2; // eax uint32_t modelindex; // [esp+0h] [ebp-Ch] uint8_t weapModel; // [esp+7h] [ebp-5h] WeaponDef *weapDef; // [esp+8h] [ebp-4h] if (itemRegistered[weapIndex]) MyAssertHandler(".\\game\\g_items.cpp", 1301, 0, "%s", "!itemRegistered[weapIndex]"); itemRegistered[weapIndex] = 1; level.bRegisterItems = 1; #ifdef KISAK_MP level.registerWeapons = 1; #endif weapDef = BG_GetWeaponDef(weapIndex); if (*weapDef->szUseHintString && !G_GetHintStringIndex(&weapDef->iUseHintStringIndex, (char *)weapDef->szUseHintString)) { Com_Error(ERR_DROP, "Too many different hintstring values on weapons. Max allowed is %i different strings", 32); } if (*weapDef->dropHintString && !G_GetHintStringIndex(&weapDef->dropHintStringIndex, (char *)weapDef->dropHintString)) Com_Error(ERR_DROP, "Too many different hintstring values on weapons. Max allowed is %i different strings", 32); for (weapModel = 0; weapModel < 0x10u; ++weapModel) { if (weapDef->worldModel[weapModel]) { Name = (char *)XModelGetName(weapDef->worldModel[weapModel]); modelindex = G_ModelIndex(Name); if (XModelBad(weapDef->worldModel[weapModel])) G_OverrideModel(modelindex, (char*)"defaultweapon"); } } if (weapDef->projectileModel) { v2 = (char *)XModelGetName(weapDef->projectileModel); G_ModelIndex(v2); } //fireRumble = v4->fireRumble; //if (fireRumble && *fireRumble) // G_RumbleIndex(fireRumble); //meleeImpactRumble = v4->meleeImpactRumble; //if (meleeImpactRumble) //{ // if (*meleeImpactRumble) // G_RumbleIndex(meleeImpactRumble); //} } int32_t __cdecl IsItemRegistered(uint32_t iItemIndex) { if (iItemIndex >= 0x80) MyAssertHandler(".\\game\\g_items.cpp", 1349, 0, "%s", "(iItemIndex >= 0) && (iItemIndex < MAX_WEAPONS)"); return itemRegistered[iItemIndex]; } void __cdecl G_SpawnItem(gentity_s *ent, const gitem_s *item) { char *Name; // eax uint32_t weapIndex; // [esp+8h] [ebp-Ch] uint8_t weapModel; // [esp+Fh] [ebp-5h] WeaponDef *weapDef; // [esp+10h] [ebp-4h] ent->item[0].index = ((char *)item - (char *)bg_itemlist) >> 2; weapIndex = ent->item[0].index % 128; weapModel = ent->item[0].index / 128; weapDef = BG_GetWeaponDef(weapIndex); iassert(weapDef); if (weapDef->worldModel[weapModel]) { Name = (char *)XModelGetName(weapDef->worldModel[weapModel]); G_SetModel(ent, Name); } iassert(item->giType == IT_WEAPON); ent->r.mins[0] = -1.0; ent->r.mins[1] = -1.0; ent->r.mins[2] = -1.0; ent->r.maxs[0] = 1.0; ent->r.maxs[1] = 1.0; ent->r.maxs[2] = 1.0; ent->s.eType = ET_ITEM; #ifdef KISAK_MP ent->r.contents = 1079771400; ent->r.contents |= 0x200000u; ent->s.index.brushmodel = LOWORD(ent->missile.travelDist); #elif KISAK_SP ent->r.contents = 1081868552; ent->s.index.item = ent->item->index; #endif TransferRandomAmmoToWeaponEntity(ent, weapIndex); G_DObjUpdate(ent); #ifdef KISAK_MP ent->s.clientNum = MAX_CLIENTS; #endif ent->flags |= FL_SUPPORTS_LINKTO; if (level.spawnVar.spawnVarsValid) { G_SetAngle(ent, ent->r.currentAngles); ent->nextthink = level.time + 100; ent->handler = ENT_HANDLER_ITEM_INIT; } else { ent->handler = ENT_HANDLER_ITEM; if ((ent->spawnflags & 1) == 0) { ent->s.groundEntityNum = ENTITYNUM_NONE; iassert(item->giType == IT_WEAPON); ent->r.currentAngles[2] = ent->r.currentAngles[2] + 90.0; } G_SetAngle(ent, ent->r.currentAngles); G_SetOrigin(ent, ent->r.currentOrigin); SV_LinkEntity(ent); } } void __cdecl G_RunItem(gentity_s *ent) { int32_t passEntityNum; // [esp+10h] [ebp-ACh] float diff[6]; // [esp+24h] [ebp-98h] BYREF float v4; // [esp+3Ch] [ebp-80h] float v5; // [esp+40h] [ebp-7Ch] float v6; // [esp+44h] [ebp-78h] float v7; // [esp+48h] [ebp-74h] float v8; // [esp+4Ch] [ebp-70h] float v9; // [esp+50h] [ebp-6Ch] float *trDelta; // [esp+54h] [ebp-68h] float *trBase; // [esp+58h] [ebp-64h] float *currentOrigin; // [esp+5Ch] [ebp-60h] int32_t contents; // [esp+60h] [ebp-5Ch] float delta[3]; // [esp+64h] [ebp-58h] BYREF float origin[3]; // [esp+70h] [ebp-4Ch] BYREF float endpos[3]; // [esp+7Ch] [ebp-40h] BYREF trace_t tr; // [esp+88h] [ebp-34h] BYREF int32_t mask; // [esp+B4h] [ebp-8h] float dot; // [esp+B8h] [ebp-4h] //if (ent->s.eType == ET_PLAYER_CORPSE) // MyAssertHandler(".\\game\\g_items.cpp", 1465, 0, "%s", "ent->s.eType != ET_PLAYER_CORPSE"); if ((ent->s.groundEntityNum == ENTITYNUM_NONE || level.gentities[ent->s.groundEntityNum].s.lerp.pos.trType) && ent->s.lerp.pos.trType != TR_GRAVITY && ent->s.lerp.pos.trType != TR_RAGDOLL_GRAVITY && (ent->spawnflags & 1) == 0) { ent->s.lerp.pos.trType = TR_GRAVITY; ent->s.lerp.pos.trTime = level.time; trBase = ent->s.lerp.pos.trBase; currentOrigin = ent->r.currentOrigin; ent->s.lerp.pos.trBase[0] = ent->r.currentOrigin[0]; trBase[1] = currentOrigin[1]; trBase[2] = currentOrigin[2]; trDelta = ent->s.lerp.pos.trDelta; ent->s.lerp.pos.trDelta[0] = 0.0; trDelta[1] = 0.0; trDelta[2] = 0.0; } v9 = ent->s.lerp.pos.trBase[0]; if ((LODWORD(v9) & 0x7F800000) == 0x7F800000 || (v8 = ent->s.lerp.pos.trBase[1], (LODWORD(v8) & 0x7F800000) == 0x7F800000) || (v7 = ent->s.lerp.pos.trBase[2], (LODWORD(v7) & 0x7F800000) == 0x7F800000)) { MyAssertHandler( ".\\game\\g_items.cpp", 1492, 0, "%s", "!IS_NAN((ent->s.lerp.pos.trBase)[0]) && !IS_NAN((ent->s.lerp.pos.trBase)[1]) && !IS_NAN((ent->s.lerp.pos.trBase)[2])"); } v6 = ent->s.lerp.pos.trDelta[0]; if ((LODWORD(v6) & 0x7F800000) == 0x7F800000 || (v5 = ent->s.lerp.pos.trDelta[1], (LODWORD(v5) & 0x7F800000) == 0x7F800000) || (v4 = ent->s.lerp.pos.trDelta[2], (LODWORD(v4) & 0x7F800000) == 0x7F800000)) { MyAssertHandler( ".\\game\\g_items.cpp", 1493, 0, "%s", "!IS_NAN((ent->s.lerp.pos.trDelta)[0]) && !IS_NAN((ent->s.lerp.pos.trDelta)[1]) && !IS_NAN((ent->s.lerp.pos.trDelta)[2])"); } if (ent->s.lerp.pos.trType && !ent->tagInfo) { BG_EvaluateTrajectory(&ent->s.lerp.pos, level.time + 50, origin); diff[5] = origin[0]; if ((LODWORD(origin[0]) & 0x7F800000) == 0x7F800000 || (diff[4] = origin[1], (LODWORD(origin[1]) & 0x7F800000) == 0x7F800000) || (diff[3] = origin[2], (LODWORD(origin[2]) & 0x7F800000) == 0x7F800000)) { MyAssertHandler( ".\\game\\g_items.cpp", 1505, 0, "%s", "!IS_NAN((origin)[0]) && !IS_NAN((origin)[1]) && !IS_NAN((origin)[2])"); } mask = G_ItemClipMask(ent); if ((mask & ent->r.contents) != 0) MyAssertHandler(".\\game\\g_items.cpp", 1511, 0, "%s", "!( ent->r.contents & mask )"); Vec3Sub(origin, ent->r.currentOrigin, diff); if (Vec3LengthSq(diff) < 0.1000000014901161) origin[2] = origin[2] - 1.0; if (ent->r.ownerNum.isDefined()) { passEntityNum = ent->r.ownerNum.entnum(); G_TraceCapsule(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, passEntityNum, mask); } else { G_TraceCapsule(&tr, ent->r.currentOrigin, ent->r.mins, ent->r.maxs, origin, ENTITYNUM_NONE, mask); } if (tr.fraction >= 1.0) { ent->r.currentOrigin[0] = origin[0]; ent->r.currentOrigin[1] = origin[1]; ent->r.currentOrigin[2] = origin[2]; } else { Vec3Lerp(ent->r.currentOrigin, origin, tr.fraction, endpos); if (!tr.startsolid && tr.fraction < 0.009999999776482582 && tr.normal[2] < 0.5) { Vec3Sub(origin, ent->r.currentOrigin, delta); dot = 1.0 - Vec3Dot(delta, tr.normal); Vec3Mad(origin, dot, tr.normal, origin); if (ent->r.ownerNum.isDefined()) { G_TraceCapsule(&tr, endpos, ent->r.mins, ent->r.maxs, origin, ent->r.ownerNum.entnum(), mask); } else { G_TraceCapsule(&tr, endpos, ent->r.mins, ent->r.maxs, origin, ENTITYNUM_NONE, mask); } Vec3Lerp(endpos, origin, tr.fraction, endpos); } ent->s.lerp.pos.trType = TR_LINEAR_STOP; ent->s.lerp.pos.trTime = level.time; ent->s.lerp.pos.trDuration = 50; ent->s.lerp.pos.trBase[0] = ent->r.currentOrigin[0]; ent->s.lerp.pos.trBase[1] = ent->r.currentOrigin[1]; ent->s.lerp.pos.trBase[2] = ent->r.currentOrigin[2]; Vec3Sub(endpos, ent->r.currentOrigin, ent->s.lerp.pos.trDelta); Vec3Scale(ent->s.lerp.pos.trDelta, 20.0, ent->s.lerp.pos.trDelta); ent->r.currentOrigin[0] = endpos[0]; ent->r.currentOrigin[1] = endpos[1]; ent->r.currentOrigin[2] = endpos[2]; } SV_LinkEntity(ent); G_RunThink(ent); if (ent->r.inuse && tr.fraction < 0.009999999776482582) { if (tr.normal[2] <= 0.0 || (contents = SV_PointContents(ent->r.currentOrigin, -1, 0x80000000)) != 0) { G_FreeEntity(ent); } else { G_OrientItemToGround(ent, &tr); G_SetOrigin(ent, endpos); ent->s.groundEntityNum = Trace_GetEntityHitId(&tr); g_entities[ent->s.groundEntityNum].flags |= FL_GROUND_ENT; SV_LinkEntity(ent); } } } else { G_RunThink(ent); } } void __cdecl G_OrientItemToGround(gentity_s *ent, trace_t *trace) { float vAngles[3]; // [esp+8h] [ebp-30h] BYREF float vAxis[3][3]; // [esp+14h] [ebp-24h] BYREF vAxis[2][0] = trace->normal[0]; vAxis[2][1] = trace->normal[1]; vAxis[2][2] = trace->normal[2]; AngleVectors(ent->r.currentAngles, vAxis[0], 0, 0); Vec3Cross(vAxis[2], vAxis[0], vAxis[1]); Vec3Cross(vAxis[1], vAxis[2], vAxis[0]); AxisToAngles(vAxis, vAngles); if (ent->s.index.brushmodel) { if (bg_itemlist[ent->s.index.brushmodel].giType != IT_WEAPON) MyAssertHandler(".\\game\\g_items.cpp", 1443, 0, "%s", "bg_itemlist[ent->s.index.item].giType == IT_WEAPON"); vAngles[2] = vAngles[2] + 90.0; } G_SetAngle(ent, vAngles); }
0
0.920409
1
0.920409
game-dev
MEDIA
0.979153
game-dev
0.780375
1
0.780375
Roblox/avatar
1,341
InGameAvatarEditor/src/ServerScriptService/AvatarEditorInGameSetup/AvatarEditorInGame/Modules/AvatarExperience/AvatarEditor/Models/OutfitInfo.lua
--[[ Model for an Outfit (e.g. Hat). { outfitId = number assets = {} bodyColors = {} } ]] local Modules = game:GetService("Players").LocalPlayer.PlayerGui.AvatarEditorInGame.Modules local MockId = require(Modules.NotLApp.MockId) local Constants = require(Modules.AvatarExperience.AvatarEditor.Constants) local AEOutfitInfo = {} function AEOutfitInfo.new() local self = {} return self end function AEOutfitInfo.mock() local self = AEOutfitInfo.new() local MEDIUM_STONE_GREY = 194 self.outfitId = MockId() self.name = "" self.assets = {} self.bodyColors = { HeadColor = MEDIUM_STONE_GREY, LeftArmColor = MEDIUM_STONE_GREY, LeftLegColor = MEDIUM_STONE_GREY, RightArmColor = MEDIUM_STONE_GREY, RightLegColor = MEDIUM_STONE_GREY, TorsoColor = MEDIUM_STONE_GREY, } self.scales = { height = 0, width = 0, head = 0, depth = 0, proportion = 0, bodyType = 0, } self.avatarType = Constants.AvatarType.R15 self.isEditable = true return self end function AEOutfitInfo.fromWebApi(outfitId, name, assets, bodyColors, scales, avatarType, isEditable) local self = AEOutfitInfo.new() self.outfitId = outfitId self.name = name self.assets = assets self.bodyColors = bodyColors self.scales = scales self.avatarType = avatarType self.isEditable = isEditable return self end return AEOutfitInfo
0
0.645024
1
0.645024
game-dev
MEDIA
0.857121
game-dev
0.857529
1
0.857529
lyte2d/lyte2d
24,627
deps/ode-0.16.4/tests/joints/hinge.cpp
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ //234567890123456789012345678901234567890123456789012345678901234567890123456789 // 1 2 3 4 5 6 7 //////////////////////////////////////////////////////////////////////////////// // This file create unit test for some of the functions found in: // ode/src/joinst/hinge.cpp // // //////////////////////////////////////////////////////////////////////////////// #include <UnitTest++.h> #include <ode/ode.h> #include "../../ode/src/config.h" #include "../../ode/src/joints/hinge.h" SUITE (TestdxJointHinge) { // The 2 bodies are positionned at (0, 0, 0), with no rotation // The joint is an Hinge Joint // Axis is along the X axis // Anchor at (0, 0, 0) // ^Y // | // | // | // | // | // Z <---- . (X going out of the page) struct dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X { dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X() { wId = dWorldCreate(); bId1 = dBodyCreate (wId); dBodySetPosition (bId1, 0, 0, 0); bId2 = dBodyCreate (wId); dBodySetPosition (bId2, 0, 0, 0); jId = dJointCreateHinge (wId, 0); joint = (dxJointHinge*) jId; dJointAttach (jId, bId1, bId2); dJointSetHingeAnchor (jId, 0, 0, 0); axis[0] = 1; axis[1] = 0; axis[2] = 0; } ~dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X() { dWorldDestroy (wId); } dWorldID wId; dBodyID bId1; dBodyID bId2; dJointID jId; dxJointHinge* joint; dVector3 axis; }; // Rotate 2nd body 90deg around X then back to original position // // ^ ^ ^ // | | => | <--- // | | | // B1 B2 B1 B2 // // Start with a Delta of 90deg // ^ ^ ^ // | <--- => | | // | | | // B1 B2 B1 B2 TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X, test_dJointSetHingeAxisOffset_B2_90deg) { dMatrix3 R; CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0); dBodySetRotation (bId2, R); CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -M_PI/2.0); CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId2, R); CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4); } // Rotate 2nd body -90deg around X then back to original position // // ^ ^ ^ // | | => | ---> // | | | // B1 B2 B1 B2 // // Start with a Delta of 90deg // ^ ^ ^ // | ---> => | | // | | | // B1 B2 B1 B2 TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X, test_dJointSetHingeAxisOffset_B2_Minus90deg) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, -M_PI/2.0); dBodySetRotation (bId2, R); CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], M_PI/2.0); CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId2, R); CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4); } // Rotate 1st body 0.23rad around X then back to original position // // ^ ^ ^ ^ // | | => \ | // | | \ | // B1 B2 B1 B2 // // Start with a Delta of 0.23rad // ^ ^ ^ ^ // \ | => | | // \ | | | // B1 B2 B1 B2 TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X, test_dJointSetHingeAxisOffset_B1_0_23rad) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, REAL(0.23) ); dBodySetRotation (bId1, R); CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], REAL(0.23)); CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId1, R); CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4); } // Rotate 1st body -0.23rad around Z then back to original position // // ^ ^ ^ ^ // | | => / | // | | / | // B1 B2 B1 B2 // // Start with a Delta of 0.23rad // ^ ^ ^ ^ // / | => | | // / | | | // B1 B2 B1 B2 TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X, test_dJointSetHingeAxisOffset_B1_Minus0_23rad) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23)); dBodySetRotation (bId1, R); CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -REAL(0.23)); CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId1, R); CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4); } // The 2 bodies are positionned at (0, 0, 0), with no rotation // The joint is an Hinge Joint. // Axis in the inverse direction of the X axis // Anchor at (0, 0, 0) // ^Y // | // | // | // | // | // Z <---- x (X going out of the page) struct dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X { dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X() { wId = dWorldCreate(); bId1 = dBodyCreate (wId); dBodySetPosition (bId1, 0, -1, 0); bId2 = dBodyCreate (wId); dBodySetPosition (bId2, 0, 1, 0); jId = dJointCreateHinge (wId, 0); joint = (dxJointHinge*) jId; dJointAttach (jId, bId1, bId2); dJointSetHingeAnchor (jId, 0, 0, 0); axis[0] = -1; axis[1] = 0; axis[2] = 0; } ~dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X() { dWorldDestroy (wId); } dWorldID wId; dBodyID bId1; dBodyID bId2; dJointID jId; dxJointHinge* joint; dVector3 axis; }; // Rotate 2nd body 90deg around X then back to original position // // ^ ^ ^ // | | => | <--- // | | | // B1 B2 B1 B2 // // Start with a Delta of 90deg // ^ ^ ^ // | <--- => | | // | | | // B1 B2 B1 B2 TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X, test_dJointSetHingeAxisOffset_B2_90Deg) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0); dBodySetRotation (bId2, R); CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], M_PI/2.0); CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId2, R); CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4); } // Rotate 2nd body -90deg around X then back to original position // // ^ ^ ^ // | | => | ---> // | | | // B1 B2 B1 B2 // // Start with a Delta of 90deg // ^ ^ ^ // | ---> => | | // | | | // B1 B2 B1 B2 TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X, test_dJointSetHingeAxisOffset_B2_Minus90Deg) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, -M_PI/2.0); dBodySetRotation (bId2, R); CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -M_PI/2.0); CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId2, R); CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4); } // Rotate 1st body 0.23rad around X then back to original position // // ^ ^ ^ ^ // | | => \ | // | | \ | // B1 B2 B1 B2 // // Start with a Delta of 0.23rad // ^ ^ ^ ^ // \ | => | | // \ | | | // B1 B2 B1 B2 TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X, test_dJointSetHingeAxisOffset_B1_0_23rad) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, REAL(0.23)); dBodySetRotation (bId1, R); CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -REAL(0.23)); CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId1, R); CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4); } // Rotate 2nd body -0.23rad around Z then back to original position // // ^ ^ ^ ^ // | | => / | // | | / | // B1 B2 B1 B2 // // Start with a Delta of 0.23rad // ^ ^ ^ ^ // / | => | | // / | | | // B1 B2 B1 B2 TEST_FIXTURE (dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Inverse_of_X, test_dJointSetHingeAxisOffset_B1_Minus0_23rad) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23)); dBodySetRotation (bId1, R); CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], REAL(0.23)); CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId1, R); CHECK_CLOSE (0.0, dJointGetHingeAngle (jId), 1e-4); } // Only one body body1 at (0,0,0) // The joint is an Hinge Joint. // Axis is along the X axis // Anchor at (0, 0, 0) // // ^Y // | // | // | // | // | // Z <-- X struct dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X { dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X() { wId = dWorldCreate(); bId1 = dBodyCreate (wId); dBodySetPosition (bId1, 0, 0, 0); jId = dJointCreateHinge (wId, 0); joint = (dxJointHinge*) jId; dJointAttach (jId, bId1, NULL); dJointSetHingeAnchor (jId, 0, 0, 0); axis[0] = 1; axis[1] = 0; axis[2] = 0; } ~dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X() { dWorldDestroy (wId); } dWorldID wId; dBodyID bId1; dJointID jId; dxJointHinge* joint; dVector3 axis; }; // Rotate B1 by 90deg around X then back to original position // // ^ // | => <--- // | // B1 B1 // // Start with a Delta of 90deg // ^ // <--- => | // | // B1 B1 TEST_FIXTURE (dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X, test_dJointSetHingeAxisOffset_1Body_B1_90Deg) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0); dBodySetRotation (bId1, R); CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], M_PI/2.0); CHECK_CLOSE (M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId1, R); CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4); } // Rotate B1 by -0.23rad around X then back to original position // // ^ ^ // | => / // | / // B1 B1 // // Start with a Delta of -0.23rad // ^ ^ // / => | // / | // B1 B1 TEST_FIXTURE (dxJointHinge_Fixture_B1_At_Zero_Axis_Along_X, test_dJointSetHingeAxisOffset_1Body_B1_Minus0_23rad) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23)); dBodySetRotation (bId1, R); CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -REAL(0.23)); CHECK_CLOSE (-REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId1, R); CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4); } // Only one body body1 at (0,0,0) // The joint is an Hinge Joint. // Axis the inverse of the X axis // Anchor at (0, 0, 0) // // ^Y // | // | // | // | // | // Z <-- X struct dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X { dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X() { wId = dWorldCreate(); bId1 = dBodyCreate (wId); dBodySetPosition (bId1, 0, 0, 0); jId = dJointCreateHinge (wId, 0); joint = (dxJointHinge*) jId; dJointAttach (jId, bId1, NULL); dJointSetHingeAnchor (jId, 0, 0, 0); axis[0] = -1; axis[1] = 0; axis[2] = 0; } ~dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X() { dWorldDestroy (wId); } dWorldID wId; dBodyID bId1; dJointID jId; dxJointHinge* joint; dVector3 axis; }; // Rotate B1 by 90deg around X then back to original position // // ^ // | => <--- // | // B1 B1 // // Start with a Delta of 90deg // ^ // <--- => | // | // B1 B1 TEST_FIXTURE (dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X, test_dJointSetHingeAxisOffset_1Body_B1_90Deg) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0); dBodySetRotation (bId1, R); CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -M_PI/2.0); CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId1, R); CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4); } // Rotate B1 by -0.23rad around X then back to original position // // ^ ^ // | => / // | / // B1 B1 // // Start with a Delta of -0.23rad // ^ ^ // / => | // / | // B1 B1 TEST_FIXTURE (dxJointHinge_Fixture_B1_At_Zero_Axis_Inverse_of_X, test_dJointSetHingeAxisOffset_1Body_B1_Minus0_23rad) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23)); dBodySetRotation (bId1, R); CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], REAL(0.23)); CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId1, R); CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4); } // Only one body body2 at (0,0,0) // The joint is an Hinge Joint. // Axis is along the X axis // Anchor at (0, 0, 0) // // ^Y // | // | // | // | // | // Z <-- X struct dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X { dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X() { wId = dWorldCreate(); bId2 = dBodyCreate (wId); dBodySetPosition (bId2, 0, 0, 0); jId = dJointCreateHinge (wId, 0); joint = (dxJointHinge*) jId; dJointAttach (jId, NULL, bId2); dJointSetHingeAnchor (jId, 0, 0, 0); axis[0] = 1; axis[1] = 0; axis[2] = 0; } ~dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X() { dWorldDestroy (wId); } dWorldID wId; dBodyID bId2; dJointID jId; dxJointHinge* joint; dVector3 axis; }; // Rotate B2 by 90deg around X then back to original position // // ^ // | => <--- // | // B2 B2 // // Start with a Delta of 90deg // ^ // <--- => | // | // B2 B2 TEST_FIXTURE (dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X, test_dJointSetHingeAxisOffset_1Body_B2_90Deg) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, M_PI/2.0); dBodySetRotation (bId2, R); CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], -M_PI/2.0); CHECK_CLOSE (-M_PI/2.0, dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId2, R); CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4); } // Rotate B2 by -0.23rad around X then back to original position // // ^ ^ // | => / // | / // B2 B2 // // Start with a Delta of -0.23rad // ^ ^ // / => | // / | // B2 B2 TEST_FIXTURE (dxJointHinge_Fixture_B2_At_Zero_Axis_Along_X, test_dJointSetHingeAxisOffset_1Body_B2_Minus0_23rad) { dMatrix3 R; dJointSetHingeAxis (jId, axis[0], axis[1], axis[2]); CHECK_CLOSE (dJointGetHingeAngle (jId), 0.0, 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, -REAL(0.23)); dBodySetRotation (bId2, R); CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dJointSetHingeAxisOffset (jId, axis[0], axis[1], axis[2], REAL(0.23)); CHECK_CLOSE (REAL(0.23), dJointGetHingeAngle (jId), 1e-4); dRFromAxisAndAngle (R, 1, 0, 0, 0); dBodySetRotation (bId2, R); CHECK_CLOSE (0, dJointGetHingeAngle (jId), 1e-4); } // Create 2 bodies attached by a Hinge joint // Axis is along the X axis (Default value // Anchor at (0, 0, 0) (Default value) // // ^Y // | // * Body2 // | // | // Body1 | // * Z--------> struct dxJointHinge_Test_Initialization { dxJointHinge_Test_Initialization() { wId = dWorldCreate(); // Remove gravity to have the only force be the force of the joint dWorldSetGravity(wId, 0,0,0); for (int j=0; j<2; ++j) { bId[j][0] = dBodyCreate (wId); dBodySetPosition (bId[j][0], -1, -2, -3); bId[j][1] = dBodyCreate (wId); dBodySetPosition (bId[j][1], 11, 22, 33); dMatrix3 R; dVector3 axis; // Random axis axis[0] = REAL(0.53); axis[1] = -REAL(0.71); axis[2] = REAL(0.43); dNormalize3(axis); dRFromAxisAndAngle (R, axis[0], axis[1], axis[2], REAL(0.47123)); // 27deg dBodySetRotation (bId[j][0], R); axis[0] = REAL(1.2); axis[1] = REAL(0.87); axis[2] = -REAL(0.33); dNormalize3(axis); dRFromAxisAndAngle (R, axis[0], axis[1], axis[2], REAL(0.47123)); // 27deg dBodySetRotation (bId[j][1], R); jId[j] = dJointCreateHinge (wId, 0); dJointAttach (jId[j], bId[j][0], bId[j][1]); // dJointSetHingeParam(jId[j], dParamLoStop, 1); // dJointSetHingeParam(jId[j], dParamHiStop, 2); // dJointSetHingeParam(jId[j], dParamFMax, 200); } } ~dxJointHinge_Test_Initialization() { dWorldDestroy (wId); } dWorldID wId; dBodyID bId[2][2]; dJointID jId[2]; }; // Test if setting a Hinge with its default values // will behave the same as a default Hinge joint TEST_FIXTURE (dxJointHinge_Test_Initialization, test_Hinge_Initialization) { using namespace std; dVector3 axis; dJointGetHingeAxis(jId[1], axis); dJointSetHingeAxis(jId[1], axis[0], axis[1], axis[2]); dVector3 anchor; dJointGetHingeAnchor(jId[1], anchor); dJointSetHingeAnchor(jId[1], anchor[0], anchor[1], anchor[2]); for (int b=0; b<2; ++b) { // Compare body b of the first joint with its equivalent on the // second joint const dReal *qA = dBodyGetQuaternion(bId[0][b]); const dReal *qB = dBodyGetQuaternion(bId[1][b]); CHECK_CLOSE (qA[0], qB[0], 1e-6); CHECK_CLOSE (qA[1], qB[1], 1e-6); CHECK_CLOSE (qA[2], qB[2], 1e-6); CHECK_CLOSE (qA[3], qB[3], 1e-6); } dWorldStep (wId,0.5); dWorldStep (wId,0.5); dWorldStep (wId,0.5); dWorldStep (wId,0.5); for (int b=0; b<2; ++b) { // Compare body b of the first joint with its equivalent on the // second joint const dReal *qA = dBodyGetQuaternion(bId[0][b]); const dReal *qB = dBodyGetQuaternion(bId[1][b]); CHECK_CLOSE (qA[0], qB[0], 1e-6); CHECK_CLOSE (qA[1], qB[1], 1e-6); CHECK_CLOSE (qA[2], qB[2], 1e-6); CHECK_CLOSE (qA[3], qB[3], 1e-6); const dReal *posA = dBodyGetPosition(bId[0][b]); const dReal *posB = dBodyGetPosition(bId[1][b]); CHECK_CLOSE (posA[0], posB[0], 1e-6); CHECK_CLOSE (posA[1], posB[1], 1e-6); CHECK_CLOSE (posA[2], posB[2], 1e-6); CHECK_CLOSE (posA[3], posB[3], 1e-6); } } TEST_FIXTURE(dxJointHinge_Fixture_B1_and_B2_At_Zero_Axis_Along_X, test_Hinge_dParamVel) { const dReal targetvel = 100; const dReal tolerance = targetvel * #ifdef dSINGLE 1e-2 #else 1e-6 #endif ; dJointSetHingeParam(jId, dParamFMax, dInfinity); dJointSetHingeParam(jId, dParamVel, targetvel); dWorldStep(wId, 0.001); const dReal *v1 = dBodyGetAngularVel(bId1); const dReal *v2 = dBodyGetAngularVel(bId2); dVector3 rvel = { v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2] }; CHECK_CLOSE(rvel[0], targetvel, tolerance); CHECK_CLOSE(rvel[1], 0, tolerance); CHECK_CLOSE(rvel[2], 0, tolerance); } } // End of SUITE TestdxJointHinge
0
0.673815
1
0.673815
game-dev
MEDIA
0.467048
game-dev
0.988874
1
0.988874
a327ex/BYTEPATH
3,033
objects/enemies/Waver.lua
Waver = GameObject:extend() function Waver:new(area, x, y, opts) Waver.super.new(self, area, x, y, opts) local direction = table.random({-1, 1}) self.x = gw/2 + direction*(gw/2 + 48) self.y = random(16, gh - 16) self.w, self.h = 12, 6 self.shape = HC.polygon(self.w, 0, 0, self.h, -self.w, 0, 0, -self.h) self.shape.id = self.id self.shape:moveTo(self.x, self.y) self.shape.object = self self.shape.tag = 'Enemy' self.v = random(90, 110) self.r = direction == 1 and math.pi or 0 self.vx, self.vy = self.v*math.cos(self.r), self.v*math.sin(self.r) self.hp = 70*current_room.director.enemy_hp_multiplier -- Attack self.timer:every(random(2.2, 2.6), function() self.timer:every(0.25, function() self.area:addGameObject('WaverPreAttackEffect', self.x, self.y, {waver = self}) end, 3) self.timer:after(1, function() for i = 1, 4 do self.timer:after((i-1)*0.075, function() self.area:addGameObject('EnemyProjectile', self.x + 1.4*self.w*math.cos(self.r), self.y + 1.4*self.w*math.sin(self.r), {r = self.r, v = random(140, 160)}) self.area:addGameObject('EnemyProjectile', self.x + 1.4*self.w*math.cos(self.r - math.pi), self.y + 1.4*self.w*math.sin(self.r - math.pi), {r = self.r - math.pi, v = random(140, 160)}) end) end end) end) -- Waving local d = table.random({-1, 1}) local m = random(1, 4) self.timer:tween(0.25, self, {r = self.r + m*d*math.pi/8}, 'linear', function() self.timer:tween(0.5, self, {r = self.r - m*d*math.pi/4}, 'linear') end) self.timer:every(0.75, function() self.timer:tween(0.25, self, {r = self.r + m*d*math.pi/4}, 'linear', function() self.timer:tween(0.5, self, {r = self.r - m*d*math.pi/4}, 'linear') end) end) end function Waver:update(dt) Waver.super.update(self, dt) self:enemyProjectileCollisions() self.vx, self.vy = self.v*math.cos(self.r), self.v*math.sin(self.r) self.shape:move(self.vx*dt, self.vy*dt) self.shape:setRotation(self.r) self.x, self.y = self.shape:center() end function Waver:draw() love.graphics.setColor(hp_color) if self.hit_flash then love.graphics.setColor(default_color) end self.shape:draw('line') love.graphics.setColor(default_color) end function Waver:destroy() Waver.super.destroy(self) end function Waver:hit(damage) if self.dead then return end self.hp = self.hp - (damage or 100) if self.hp <= 0 then playGameEnemyDie() current_room.score = current_room.score + 300 self.dead = true if not current_room.player.no_ammo_drop then self.area:addGameObject('Ammo', self.x, self.y) end self.area:addGameObject('EnemyDeathEffect', self.x, self.y, {color = hp_color, w = 2.5*self.w}) else self.hit_flash = true self.timer:after('hit_flash', 0.2, function() self.hit_flash = false end) end end
0
0.761737
1
0.761737
game-dev
MEDIA
0.774707
game-dev
0.984959
1
0.984959
Sgt-Imalas/Sgt_Imalas-Oni-Mods
3,136
Rockets-TinyYetBig/TODO/__LegacyContentToSortOut/LandingLegs/PlatformDeployerModuleConfig.cs
using System.Collections.Generic; using TUNING; using UnityEngine; namespace Rockets_TinyYetBig.LandingLegs { public class PlatformDeployerModuleConfig : IBuildingConfig { public const string ID = "RTB_LandingPlatformDeployerModule"; public override string[] GetRequiredDlcIds() => DlcManager.EXPANSION1; public override BuildingDef CreateBuildingDef() { float[] constructionMass = new float[] { 300f }; string[] constructioMaterials = MATERIALS.REFINED_METALS; EffectorValues noiseval = NOISE_POLLUTION.NOISY.TIER2; EffectorValues decorval = BUILDINGS.DECOR.NONE; BuildingDef buildingDef = BuildingTemplates.CreateBuildingDef( id: ID, width: 5, height: 5, anim: "rocket_storage_live_kanim", hitpoints: 1000, construction_time: 60f, construction_mass: constructionMass, construction_materials: constructioMaterials, melting_point: 9999f, BuildLocationRule.Anywhere, decor: decorval, noise: noiseval); BuildingTemplates.CreateRocketBuildingDef(buildingDef); buildingDef.SceneLayer = Grid.SceneLayer.Building; buildingDef.OverheatTemperature = 2273.15f; buildingDef.Floodable = false; buildingDef.AttachmentSlotTag = GameTags.Rocket; buildingDef.ObjectLayer = ObjectLayer.Building; buildingDef.attachablePosition = new CellOffset(0, 0); buildingDef.RequiresPowerInput = false; buildingDef.RequiresPowerOutput = false; buildingDef.CanMove = true; buildingDef.Cancellable = false; buildingDef.ShowInBuildMenu = false; return buildingDef; } public override void ConfigureBuildingTemplate(GameObject go, Tag prefab_tag) { BuildingConfigManager.Instance.IgnoreDefaultKComponent(typeof(RequiresFoundation), prefab_tag); go.AddOrGet<LoopingSounds>(); go.GetComponent<KPrefabID>().AddTag(RoomConstraints.ConstraintTags.IndustrialMachinery); Storage storage = go.AddComponent<Storage>(); storage.showInUI = true; storage.useWideOffsets = true; storage.SetDefaultStoredItemModifiers(Storage.StandardInsulatedStorage); BuildingInternalConstructor.Def def1 = go.AddOrGetDef<BuildingInternalConstructor.Def>(); def1.constructionMass = 750f; def1.outputIDs = new List<string>() { PlatformLanderConfig.ID }; def1.spawnIntoStorage = true; def1.storage = (DefComponent<Storage>)storage; def1.constructionSymbol = "under_construction"; go.AddOrGet<BuildingInternalConstructorWorkable>().SetWorkTime(120f); JettisonableCargoModule.Def def2 = go.AddOrGetDef<JettisonableCargoModule.Def>(); def2.landerPrefabID = PlatformLanderConfig.ID.ToTag(); def2.landerContainer = (DefComponent<Storage>)storage; def2.clusterMapFXPrefabID = "DeployingPioneerLanderFX"; go.AddOrGet<BuildingAttachPoint>().points = new BuildingAttachPoint.HardPoint[1] { new BuildingAttachPoint.HardPoint(new CellOffset(0, 5), GameTags.Rocket, null) }; } public override void DoPostConfigureComplete(GameObject go) { BuildingTemplates.ExtendBuildingToRocketModuleCluster(go, null, ROCKETRY.BURDEN.MODERATE_PLUS); go.GetComponent<KPrefabID>().prefabInitFn += inst => { }; } } }
0
0.849936
1
0.849936
game-dev
MEDIA
0.958828
game-dev
0.870571
1
0.870571
mezz/JustEnoughItems
5,279
Library/src/main/java/mezz/jei/library/gui/helpers/GuiHelper.java
package mezz.jei.library.gui.helpers; import mezz.jei.api.gui.ITickTimer; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.gui.drawable.IDrawableAnimated; import mezz.jei.api.gui.drawable.IDrawableBuilder; import mezz.jei.api.gui.drawable.IDrawableStatic; import mezz.jei.api.gui.ingredient.ICraftingGridHelper; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.ingredients.IIngredientRenderer; import mezz.jei.api.ingredients.IIngredientType; import mezz.jei.api.ingredients.ITypedIngredient; import mezz.jei.api.runtime.IIngredientManager; import mezz.jei.common.Internal; import mezz.jei.common.gui.elements.DrawableAnimated; import mezz.jei.common.gui.elements.DrawableBlank; import mezz.jei.common.gui.elements.DrawableCombined; import mezz.jei.common.gui.elements.DrawableIngredient; import mezz.jei.common.gui.textures.Textures; import mezz.jei.common.util.ErrorUtil; import mezz.jei.common.util.TickTimer; import mezz.jei.library.gui.elements.DrawableBuilder; import net.minecraft.resources.ResourceLocation; public class GuiHelper implements IGuiHelper { private final IIngredientManager ingredientManager; public GuiHelper(IIngredientManager ingredientManager) { this.ingredientManager = ingredientManager; } @Override public IDrawableBuilder drawableBuilder(ResourceLocation resourceLocation, int u, int v, int width, int height) { return new DrawableBuilder(resourceLocation, u, v, width, height); } @Override public IDrawableAnimated createAnimatedDrawable(IDrawableStatic drawable, int ticksPerCycle, IDrawableAnimated.StartDirection startDirection, boolean inverted) { ErrorUtil.checkNotNull(drawable, "drawable"); ErrorUtil.checkNotNull(startDirection, "startDirection"); return new DrawableAnimated(drawable, ticksPerCycle, startDirection, inverted); } @Override public IDrawableAnimated createAnimatedDrawable(IDrawableStatic drawable, ITickTimer tickTimer, IDrawableAnimated.StartDirection startDirection) { ErrorUtil.checkNotNull(drawable, "drawable"); ErrorUtil.checkNotNull(tickTimer, "tickTimer"); ErrorUtil.checkNotNull(startDirection, "startDirection"); return new DrawableAnimated(drawable, tickTimer, startDirection); } @Override public IDrawableStatic getSlotDrawable() { Textures textures = Internal.getTextures(); return textures.getSlot(); } @Override public IDrawableStatic getOutputSlot() { Textures textures = Internal.getTextures(); return textures.getOutputSlot(); } @Override public IDrawableStatic getRecipeArrow() { Textures textures = Internal.getTextures(); return textures.getRecipeArrow(); } @Override public IDrawableStatic getRecipeArrowFilled() { Textures textures = Internal.getTextures(); return textures.getRecipeArrowFilled(); } @Override public IDrawableAnimated createAnimatedRecipeArrow(int ticksPerCycle) { IDrawableAnimated animatedFill = createAnimatedDrawable(getRecipeArrowFilled(), ticksPerCycle, IDrawableAnimated.StartDirection.LEFT, false); return new DrawableCombined(getRecipeArrow(), animatedFill); } @Override public IDrawableStatic getRecipePlusSign() { Textures textures = Internal.getTextures(); return textures.getRecipePlusSign(); } @Override public IDrawableStatic getRecipeFlameEmpty() { Textures textures = Internal.getTextures(); return textures.getFlameEmptyIcon(); } @Override public IDrawableStatic getRecipeFlameFilled() { Textures textures = Internal.getTextures(); return textures.getFlameIcon(); } @Override public IDrawableAnimated createAnimatedRecipeFlame(int ticksPerCycle) { IDrawableAnimated animatedFill = createAnimatedDrawable(getRecipeFlameFilled(), ticksPerCycle, IDrawableAnimated.StartDirection.TOP, true); return new DrawableCombined(getRecipeFlameEmpty(), animatedFill); } @Override public IDrawableStatic createBlankDrawable(int width, int height) { return new DrawableBlank(width, height); } @Override public <V> IDrawable createDrawableIngredient(IIngredientType<V> type, V ingredient) { ErrorUtil.checkNotNull(type, "type"); ErrorUtil.checkNotNull(ingredient, "ingredient"); IIngredientRenderer<V> ingredientRenderer = ingredientManager.getIngredientRenderer(type); ITypedIngredient<V> typedIngredient = ingredientManager.createTypedIngredient(type, ingredient, false) .orElseThrow(() -> { String info = ErrorUtil.getIngredientInfo(ingredient, type, ingredientManager); return new IllegalArgumentException(String.format("Ingredient is invalid and cannot be used as a drawable ingredient: %s", info)); }); return new DrawableIngredient<>(typedIngredient, ingredientRenderer); } @Override public <V> IDrawable createDrawableIngredient(ITypedIngredient<V> ingredient) { ErrorUtil.checkNotNull(ingredient, "ingredient"); IIngredientType<V> type = ingredient.getType(); IIngredientRenderer<V> ingredientRenderer = ingredientManager.getIngredientRenderer(type); return new DrawableIngredient<>(ingredient, ingredientRenderer); } @Override public ICraftingGridHelper createCraftingGridHelper() { return CraftingGridHelper.INSTANCE; } @Override public ITickTimer createTickTimer(int ticksPerCycle, int maxValue, boolean countDown) { return new TickTimer(ticksPerCycle, maxValue, countDown); } }
0
0.866249
1
0.866249
game-dev
MEDIA
0.727519
game-dev
0.982986
1
0.982986
SpongePowered/Sponge
12,127
src/main/java/org/spongepowered/common/entity/SpongeEntitySnapshot.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.entity; import net.minecraft.nbt.CompoundTag; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.data.persistence.InvalidDataException; import org.spongepowered.api.data.persistence.Queries; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.EntityArchetype; import org.spongepowered.api.entity.EntitySnapshot; import org.spongepowered.api.entity.EntityType; import org.spongepowered.api.event.CauseStackManager.StackFrame; import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.event.cause.entity.SpawnTypes; import org.spongepowered.api.util.Transform; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.bridge.data.DataContainerHolder; import org.spongepowered.common.bridge.data.SpongeDataHolderBridge; import org.spongepowered.common.data.holder.SpongeImmutableDataHolder; import org.spongepowered.common.data.persistence.NBTTranslator; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.util.Constants; import org.spongepowered.math.vector.Vector3d; import org.spongepowered.math.vector.Vector3i; import java.lang.ref.WeakReference; import java.util.Objects; import java.util.Optional; import java.util.StringJoiner; import java.util.UUID; public class SpongeEntitySnapshot implements EntitySnapshot, SpongeImmutableDataHolder<EntitySnapshot>, DataContainerHolder.Immutable<EntitySnapshot> { private final @Nullable UUID uniqueId; private final ResourceKey worldKey; private final EntityType<?> entityType; private final Vector3d position; private final Vector3d rotation; private final Vector3d scale; private final @Nullable CompoundTag compound; private final @Nullable WeakReference<Entity> entityReference; SpongeEntitySnapshot(final SpongeEntitySnapshotBuilder builder) { this.entityType = builder.entityType; this.uniqueId = builder.uniqueId; this.compound = builder.compound == null ? null : builder.compound.copy(); if (builder.manipulator != null) { ((SpongeDataHolderBridge) this).bridge$getManipulator().copyFrom(builder.manipulator); } this.worldKey = builder.worldKey; this.position = builder.position; this.rotation = builder.rotation; this.scale = builder.scale; this.entityReference = builder.entityReference; if (this.compound != null) { this.compound.put(Constants.Entity.ENTITY_POSITION, Constants.NBT.newDoubleNBTList(this.position.x(), this.position.y(), this.position.z())); // TODO should ensure other elements are within the compound as well } } // internal use only public WeakReference<Entity> getEntityReference() { return this.entityReference; } @Override public Optional<UUID> uniqueId() { return Optional.ofNullable(this.uniqueId); } @Override public Optional<Transform> transform() { final Transform transform = Transform.of(this.position, this.rotation); return Optional.of(transform); } @Override public EntityType<?> type() { return this.entityType; } @Override public Optional<ServerLocation> location() { final Optional<ServerWorld> optional = SpongeCommon.game().server().worldManager().world(this.worldKey); if (optional.isPresent()) { final ServerLocation location = ServerLocation.of(optional.get(), this.position); return Optional.of(location); } return Optional.empty(); } @Override public int contentVersion() { return 1; } @Override public DataContainer toContainer() { final DataContainer unsafeNbt = NBTTranslator.INSTANCE.translateFrom(this.compound == null ? new CompoundTag() : this.compound); final DataContainer container = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED) .set(Queries.CONTENT_VERSION, this.contentVersion()) .set(Queries.WORLD_KEY, this.worldKey.formatted()) .createView(Constants.Sponge.SNAPSHOT_WORLD_POSITION) .set(Queries.POSITION_X, this.position.x()) .set(Queries.POSITION_Y, this.position.y()) .set(Queries.POSITION_Z, this.position.z()) .container() .createView(Constants.Entity.ROTATION) .set(Queries.POSITION_X, this.rotation.x()) .set(Queries.POSITION_Y, this.rotation.y()) .set(Queries.POSITION_Z, this.rotation.z()) .container() .createView(Constants.Entity.SCALE) .set(Queries.POSITION_X, this.scale.x()) .set(Queries.POSITION_Y, this.scale.y()) .set(Queries.POSITION_Z, this.scale.z()) .container() .set(Constants.Entity.TYPE, net.minecraft.world.entity.EntityType.getKey((net.minecraft.world.entity.EntityType<?>) this.entityType)) .set(Constants.Sponge.UNSAFE_NBT, unsafeNbt); if (this.uniqueId != null) { container.set(Constants.Entity.UUID, this.uniqueId.toString()); } return container; } @Override public boolean validateRawData(final DataView container) { return new SpongeEntitySnapshotBuilder().buildContent(container).isPresent(); } @Override public EntitySnapshot withRawData(final DataView container) throws InvalidDataException { final Optional<EntitySnapshot> snap = new SpongeEntitySnapshotBuilder().buildContent(container); return snap.orElseThrow(InvalidDataException::new); } @Override public EntitySnapshot copy() { return this; } @Override public ResourceKey world() { return this.worldKey; } @Override public Vector3i position() { return this.position.toInt(); } @Override public EntitySnapshot withLocation(final ServerLocation location) { Objects.requireNonNull(location, "location"); final SpongeEntitySnapshotBuilder builder = this.createBuilder(); builder.position = location.position(); builder.worldKey = location.world().key(); builder.compound = new CompoundTag(); return builder.build(); } private SpongeEntitySnapshotBuilder createBuilder() { return new SpongeEntitySnapshotBuilder() .type(this.type()) .rotation(this.rotation) .scale(this.scale); } public Optional<CompoundTag> getCompound() { if (this.compound == null) { return Optional.empty(); } return Optional.of(this.compound.copy()); } @Override public Optional<Entity> restore() { if (this.entityReference != null) { final Entity entity = this.entityReference.get(); if (entity != null) { return Optional.of(entity); } } final Optional<ServerWorld> world = Sponge.server().worldManager().world(this.worldKey); if (!world.isPresent()) { return Optional.empty(); } if (this.uniqueId != null) { final Optional<Entity> entity = world.get().entity(this.uniqueId); if (entity.isPresent()) { return entity; } } try (final StackFrame frame = PhaseTracker.getInstance().pushCauseFrame()) { frame.addContext(EventContextKeys.SPAWN_TYPE, SpawnTypes.PLUGIN); final Entity newEntity = world.get().createEntity(this.type(), this.position); if (newEntity != null) { final net.minecraft.world.entity.Entity nmsEntity = (net.minecraft.world.entity.Entity) newEntity; if (this.compound != null) { nmsEntity.load(this.compound); } final boolean spawnResult = world.get().spawnEntity((Entity) nmsEntity); if (spawnResult) { return Optional.of((Entity) nmsEntity); } } } return Optional.empty(); } @Override public EntityArchetype createArchetype() { final EntityArchetype.Builder builder = SpongeEntityArchetypeBuilder.pooled(); builder.type(this.entityType); if (this.compound != null) { builder.entityData(NBTTranslator.INSTANCE.translate(this.compound)); } return builder.build(); } @Override public DataContainer data$getDataContainer() { if (this.compound == null) { return DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED); } return NBTTranslator.INSTANCE.translate(this.compound); } @Override public EntitySnapshot data$withDataContainer(final DataContainer container) { final SpongeEntitySnapshotBuilder builder = this.createBuilder(); builder.worldKey = this.worldKey; builder.position = this.position; builder.compound = NBTTranslator.INSTANCE.translate(container);; return builder.build(); } @Override public int hashCode() { return Objects.hash(this.uniqueId, this.worldKey, this.entityType, this.position, this.rotation, this.scale); } @SuppressWarnings("rawtypes") @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } final SpongeEntitySnapshot other = (SpongeEntitySnapshot) obj; return Objects.equals(this.uniqueId, other.uniqueId) && Objects.equals(this.worldKey, other.worldKey) && Objects.equals(this.entityType, other.entityType) && Objects.equals(this.position, other.position) && Objects.equals(this.rotation, other.rotation) && Objects.equals(this.scale, other.scale); } @Override public String toString() { return new StringJoiner(", ", SpongeEntitySnapshot.class.getSimpleName() + "[", "]") .add("uniqueId=" + this.uniqueId) .add("entityType=" + this.entityType) .add("position=" + this.position) .add("rotation=" + this.rotation) .add("scale=" + this.scale) .toString(); } }
0
0.869289
1
0.869289
game-dev
MEDIA
0.814648
game-dev
0.905982
1
0.905982
TypeCobolTeam/TypeCobol
2,754
Codegen/test/resources/input/TypeCobol/TypedefQualifIndexedBy9.rdz.tcbl
 IDENTIFICATION DIVISION. PROGRAM-ID. DVZF0OS3. data DIVISION. working-storage section. 01 Event TYPEDEF STRICT PRIVATE. 05 IDT pic X(05). 05 Periodicity pic 9(03). 01 EventList TYPEDEF STRICT PRIVATE. 05 Counter pic 9(04) comp-5. 05 EventArray. 10 Event TYPE Event occurs 10 depending on Counter indexed by Idx. 01 MyGroupVar usage is comp-2. 05 LigCln-Taxes OCCURS 10 INDEXED BY Idx-nonQualified. 01 MyEventList type EventList. procedure division. PERFORM VARYING Idx-nonQualified FROM 1 BY 1 UNTIL Idx-nonQualified > MyEventList::Idx display "test" END-PERFORM. DECLARE PROCEDURE DisplayEventList PRIVATE IN-OUT EventList type EventList. data division. working-storage section. 01 EventList2 type EventList. PROCEDURE DIVISION. PERFORM VARYING EventList::Idx FROM 1 BY 1 UNTIL EventList::Idx > EventList2::Idx display "test" END-PERFORM GOBACK. end-declare . IDENTIFICATION DIVISION. PROGRAM-ID. Imbrique. data DIVISION. working-storage section. 01 EventList type EventList. 01 EventList2 type EventList. procedure division. PERFORM VARYING EventList::Idx FROM 1 BY 1 UNTIL EventList::Idx > EventList2::Idx display "test" END-PERFORM GOBACK. . END PROGRAM Imbrique. END PROGRAM DVZF0OS3. IDENTIFICATION DIVISION. PROGRAM-ID. DVZF0OS3bis. data DIVISION. working-storage section. 01 Event TYPEDEF STRICT PRIVATE. 05 IDT pic X(05). 05 Periodicity pic 9(03). 01 EventList TYPEDEF STRICT PRIVATE. 05 Counter pic 9(04) comp-5. 05 EventArray. 10 Event TYPE Event occurs 10 depending on Counter indexed by Idx. 01 MyEventList type EventList. procedure division. DECLARE PROCEDURE DisplayEventList PRIVATE IN-OUT EventList type EventList. data division. working-storage section. 01 EventList2 type EventList. PROCEDURE DIVISION. PERFORM VARYING EventList::Idx FROM 1 BY 1 UNTIL EventList::Idx > EventList2::Idx display "test" END-PERFORM GOBACK. end-declare . END PROGRAM DVZF0OS3bis.
0
0.937187
1
0.937187
game-dev
MEDIA
0.147929
game-dev
0.901136
1
0.901136
EWSoftware/SHFB
11,606
SHFB/Source/SandcastleCore/PresentationStyle/Transformation/Elements/Html/AutoOutlineElement.cs
//=============================================================================================================== // System : Sandcastle Tools - Sandcastle Tools Core Class Library // File : AutoOutlineElement.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 02/06/2024 // Note : Copyright 2022-2024, Eric Woodruff, All rights reserved // // This file contains the class used to handle autoOutline elements // // This code is published under the Microsoft Public License (Ms-PL). A copy of the license should be // distributed with the code and can be found at the project website: https://GitHub.com/EWSoftware/SHFB. This // notice, the author's name, and all copyright notices must remain intact in all applications, documentation, // and source files. // // Date Who Comments // ============================================================================================================== // 01/26/2022 EFW Created the code //=============================================================================================================== using System; using System.Linq; using System.Xml.Linq; namespace Sandcastle.Core.PresentationStyle.Transformation.Elements.Html { /// <summary> /// This is used to handle <c>autoOutline</c> elements in a topic /// </summary> /// <remarks><para>This element inserts a bullet list of links to the topic's sections or a section's /// sub-sections with optional support for limiting the expansion down to a specific level. Authors can use /// the tag directly or specify a token (defined in a token file) in a topic's introduction to get a bullet /// list of the sections; or in a <c>ddue:section</c>/<c>ddue:content</c> to get a bullet list of the /// section's sub-sections. If the token is used, the shared content component replaces /// <c>&lt;token&gt;autoOutline&lt;/token&gt;</c> with an <c>&lt;autoOutline/&gt;</c> node that you specify /// in the token's content. This was the old way of doing it but this version allows it to be specified /// directly like any other MAML tag.</para> /// /// <para>The <c>excludeRelatedTopics</c> attribute can be set to true to exclude the link to the related /// topics section if present or set to false to omit it. If not specified, the default is true to include /// it.</para> /// /// <para>The <c>lead</c> attribute can be included to specify the lead in text. It can be set to "none" /// to omit the lead in text. If omitted, default lead in text will be used.</para> /// /// <para>Examples:</para></remarks> /// <example> /// <code language="xml"> /// &lt;!-- Show only top-level topic titles, default lead-in text, includes related /// topics link --&gt; /// &lt;autoOutline/&gt; /// /// &lt;!-- Show only top-level topic titles without the related topics link, default /// lead-in text --&gt; /// &lt;autoOutline excludeRelatedTopics="true"/&gt; /// /// &lt;!-- Add custom lead-in text --&gt; /// &lt;autoOutline excludeRelatedTopics="true" lead="Changes in this release" /&gt; /// /// &lt;!-- Show top-level titles and titles for one level down, default lead-in text, /// includes related topics link --&gt; /// &lt;autoOutline&gt;1&lt;/autoOutline&gt; /// /// &lt;-- Show top-level titles and titles for one level down, omit the lead-in text /// &lt;autoOutline lead="none"&gt;1&lt;/autoOutline&gt; --&gt; /// /// &lt;-- Show titles from the top down to three levels, default lead-in text, includes /// related topics link --&gt; /// &lt;autoOutline&gt;3&lt;/autoOutline&gt; /// </code> /// </example> public class AutoOutlineElement : Element { #region Properties //===================================================================== /// <summary> /// This is used to set a style class name on top-level auto-outlines /// </summary> /// <remarks>This is useful for hiding top-level auto-outlines on all but certain devices if another /// element on the page displays section headers such as In This Article quick links. Custom lead text, /// if specified, will still be rendered as it may not refer to the auto-outline.</remarks> public string TopLevelStyleName { get; set; } #endregion #region Constructor //===================================================================== /// <inheritdoc /> public AutoOutlineElement() : base("autoOutline") { } #endregion #region Methods //===================================================================== /// <inheritdoc /> public override void Render(TopicTransformationCore transformation, XElement element) { if(transformation == null) throw new ArgumentNullException(nameof(transformation)); if(element == null) throw new ArgumentNullException(nameof(element)); string leadIn = element.Attribute("lead")?.Value.NormalizeWhiteSpace(); AutoOutlineType outlineType = element.Attribute("excludeRelatedTopics").ToBoolean() ? AutoOutlineType.TopNoRelated : AutoOutlineType.TopLevel; if(!Int32.TryParse(element.Value, out int maxDepth)) maxDepth = 0; var intro = element.Ancestors(Ddue + "introduction").FirstOrDefault(); if(intro != null) { // If in an introduction, it outlines the top level sections this.InsertAutoOutline(transformation, transformation.CurrentElement, intro.Parent, leadIn, outlineType, 0, maxDepth); } else { // If in a section/content element, it outlines the subsections of the parent section element // if it has any. var content = element.Ancestors(Ddue + "content").Where( c => c.Parent.Name == Ddue + "section").FirstOrDefault(); if(content != null) { var sections = content.Parent.Element(Ddue + "sections"); if(sections != null) { this.InsertAutoOutline(transformation, transformation.CurrentElement, sections, leadIn, AutoOutlineType.Subsection, 0, maxDepth); } } } } /// <summary> /// Insert an auto-outline /// </summary> /// <param name="transformation">The topic transformation in use</param> /// <param name="renderTo">The parent element to which the outline will be rendered</param> /// <param name="content">The content from which to get the auto-outline sections</param> /// <param name="leadIn">The lead in text</param> /// <param name="outlineType">The outline type</param> /// <param name="currentDepth">The current outline depth</param> /// <param name="maxDepth">The maximum outline depth</param> private void InsertAutoOutline(TopicTransformationCore transformation, XElement renderTo, XElement content, string leadIn, AutoOutlineType outlineType, int currentDepth, int maxDepth) { // Ignore any without a title section if(!content.Elements(Ddue + "section").Any( s => (s.Element(Ddue + "title")?.Value ?? String.Empty).NormalizeWhiteSpace().Length != 0)) { return; } if(leadIn == null || !leadIn.Equals("none", StringComparison.Ordinal)) { if(!String.IsNullOrWhiteSpace(leadIn)) { // No class on this one as the text may not refer to the auto-outline so it should always // be visible. renderTo.Add(new XElement("p", leadIn)); } else { if(outlineType < AutoOutlineType.Subsection) { var para = new XElement("p", new XElement("include", new XAttribute("item", "boilerplate_autoOutlineTopLevelIntro"))); // Apply the top level style so that the lead-in text is hidden when the outline is hidden if(!String.IsNullOrWhiteSpace(this.TopLevelStyleName)) para.Add(new XAttribute("class", this.TopLevelStyleName)); renderTo.Add(para); } else { if(outlineType == AutoOutlineType.Subsection) { renderTo.Add(new XElement("p", new XElement("include", new XAttribute("item", "boilerplate_autoOutlineSubsectionIntro")))); } } } } var ul = new XElement("ul"); if(outlineType <= AutoOutlineType.TopNoRelated && !String.IsNullOrWhiteSpace(this.TopLevelStyleName)) ul.Add(new XAttribute("class", this.TopLevelStyleName)); renderTo.Add(ul); foreach(var s in content.Elements(Ddue + "section")) { string title = s.Element(Ddue + "title")?.Value.NormalizeWhiteSpace(); // Ignore sections without a title if(String.IsNullOrWhiteSpace(title)) continue; var li = new XElement("li"); string address = s.Attribute("address")?.Value; var summary = s.Element(Ddue + "summary"); if(!String.IsNullOrWhiteSpace(address)) li.Add(new XElement("a", new XAttribute("href", "#" + address), title)); else li.Add(title); if(summary != null && summary.Value.NormalizeWhiteSpace().Length != 0) { var div = new XElement("div"); li.Add(div); transformation.RenderChildElements(div, summary.Nodes()); } ul.Add(li); // Expand subsections if wanted var subsections = s.Element(Ddue + "sections"); if(subsections != null && currentDepth < maxDepth) { this.InsertAutoOutline(transformation, li, subsections, null, AutoOutlineType.SubSubsection, currentDepth + 1, maxDepth); } } // Add See Also section link for top level outlines but only if it has related topics if(outlineType == AutoOutlineType.TopLevel) { var relatedTopics = transformation.DocumentNode.Descendants(Ddue + "relatedTopics").FirstOrDefault(); if(relatedTopics != null && relatedTopics.HasElements) { ul.Add(new XElement("li", new XElement("a", new XAttribute("href", "#seeAlsoSection"), new XElement("include", new XAttribute("item", "title_relatedTopics"))))); } } } #endregion } }
0
0.844942
1
0.844942
game-dev
MEDIA
0.237698
game-dev
0.768002
1
0.768002
Archy-X/AuraSkills
4,908
common/src/main/java/dev/aurelium/auraskills/common/reward/RewardTable.java
package dev.aurelium.auraskills.common.reward; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import dev.aurelium.auraskills.api.stat.Stat; import dev.aurelium.auraskills.common.AuraSkillsPlugin; import dev.aurelium.auraskills.common.hooks.PermissionsHook; import dev.aurelium.auraskills.common.reward.type.PermissionReward; import dev.aurelium.auraskills.common.reward.type.StatReward; import dev.aurelium.auraskills.common.user.User; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class RewardTable { private final AuraSkillsPlugin plugin; private final List<Stat> statsLeveled; private final Map<Integer, List<SkillReward>> rewards; public RewardTable(AuraSkillsPlugin plugin) { this.plugin = plugin; this.rewards = new ConcurrentHashMap<>(); this.statsLeveled = new ArrayList<>(); } public ImmutableList<SkillReward> getRewards(int level) { return ImmutableList.copyOf(rewards.getOrDefault(level, new ArrayList<>())); } public Map<Integer, List<SkillReward>> getRewardsMap() { return rewards; } public void addReward(@NotNull SkillReward reward, int level) { List<SkillReward> rewards = this.rewards.computeIfAbsent(level, k -> new ArrayList<>()); rewards.add(reward); if (reward instanceof StatReward statReward) { if (!statsLeveled.contains(statReward.getStat())) { statsLeveled.add(statReward.getStat()); } } } public ImmutableList<Stat> getStatsLeveled() { return ImmutableList.copyOf(statsLeveled); } /** * Searches rewards for all rewards of a certain type * * @param type The class of the type of reward to search * @param <T> The reward type * @return A map of each level to a list of rewards of that type */ public <T extends SkillReward> Map<Integer, ImmutableList<T>> searchRewards(Class<T> type) { ImmutableMap.Builder<Integer, ImmutableList<T>> builder = ImmutableMap.builder(); for (Map.Entry<Integer, List<SkillReward>> entry : rewards.entrySet()) { List<T> rewardList = new ArrayList<>(); for (SkillReward reward : entry.getValue()) { if (type.isInstance(reward)) { rewardList.add(type.cast(reward)); } } if (!rewardList.isEmpty()) { builder.put(entry.getKey(), ImmutableList.copyOf(rewardList)); } } return builder.build(); } // Searches all rewards of a certain type at a single level public <T extends SkillReward> ImmutableList<T> searchRewards(Class<T> type, int level) { ImmutableList<SkillReward> levelRewards = getRewards(level); List<T> rewardList = new ArrayList<>(); for (SkillReward reward : levelRewards) { if (type.isInstance(reward)) { rewardList.add(type.cast(reward)); } } return ImmutableList.copyOf(rewardList); } public Map<Stat, Double> getStatLevels(int level) { Map<Stat, Double> statsMap = new ConcurrentHashMap<>(); Map<Integer, ImmutableList<StatReward>> statRewardMap = searchRewards(StatReward.class); for (int i = plugin.config().getStartLevel() + 1; i <= level; i++) { ImmutableList<StatReward> statRewardList = statRewardMap.get(i); if (statRewardList != null) { for (StatReward statReward : statRewardList) { double existing = statsMap.getOrDefault(statReward.getStat(), 0.0); statsMap.put(statReward.getStat(), existing + statReward.getValue()); } } } return statsMap; } public void applyPermissions(User player, int level) { Map<Integer, ImmutableList<PermissionReward>> permissionRewardMap = searchRewards(PermissionReward.class); for (Map.Entry<Integer, ImmutableList<PermissionReward>> entry : permissionRewardMap.entrySet()) { int entryLevel = entry.getKey(); for (PermissionReward reward : entry.getValue()) { if (plugin.getHookManager().isRegistered(PermissionsHook.class)) { PermissionsHook hook = plugin.getHookManager().getHook(PermissionsHook.class); if (level >= entryLevel) { // Add permission if unlocked hook.setPermission(player, reward.getPermission(), reward.getValue()); } else { // Remove permission if not unlocked hook.unsetPermission(player, reward.getPermission(), reward.getValue()); } } } } } }
0
0.961121
1
0.961121
game-dev
MEDIA
0.833193
game-dev
0.97298
1
0.97298
desertkun/brainout
2,842
server/src/com/desertkun/brainout/data/components/RandomJumpComponentData.java
package com.desertkun.brainout.data.components; import com.badlogic.gdx.math.MathUtils; import com.desertkun.brainout.BrainOut; import com.desertkun.brainout.BrainOutServer; import com.desertkun.brainout.client.Client; import com.desertkun.brainout.common.enums.EntityReceived; import com.desertkun.brainout.common.msg.server.ActiveReceivedConsumableMsg; import com.desertkun.brainout.components.PlayerOwnerComponent; import com.desertkun.brainout.content.components.RandomJumpComponent; import com.desertkun.brainout.data.active.ActiveData; import com.desertkun.brainout.data.components.base.Component; import com.desertkun.brainout.data.consumable.ConsumableRecord; import com.desertkun.brainout.events.ActivateInstrumentEvent; import com.desertkun.brainout.events.AddImpulseEvent; import com.desertkun.brainout.events.Event; import com.desertkun.brainout.reflection.Reflect; import com.desertkun.brainout.reflection.ReflectAlias; import java.util.TimerTask; @Reflect("RandomJumpComponent") @ReflectAlias("data.components.RandomJumpComponentData") public class RandomJumpComponentData extends Component<RandomJumpComponent> { private final ActiveData activeData; public RandomJumpComponentData(ActiveData activeData, RandomJumpComponent component) { super(activeData, component); this.activeData = activeData; } @Override public void init() { super.init(); scheduleJump(); } @Override public boolean onEvent(Event event) { return false; } private void scheduleJump() { BrainOutServer.Timer.schedule(new TimerTask() { @Override public void run() { BrainOutServer.PostRunnable(() -> { jump(false); scheduleJump(); }); } }, MathUtils.random(2000, 5000)); } public void jump(boolean ignoreDead) { if (!ignoreDead && !activeData.isAlive()) return; SimplePhysicsComponentData phy = activeData.getComponentWithSubclass(SimplePhysicsComponentData.class); if (phy == null) return; float p = getContentComponent().getPower(); phy.getSpeed().add( MathUtils.random(5.0f, 10.0f) * MathUtils.randomSign() * p, 18.0f * p ); ServerSimplePhysicsSyncComponentData sync = activeData.getComponent(ServerSimplePhysicsSyncComponentData.class); if (sync != null) { BrainOutServer.PostRunnable(() -> sync.trigger(false)); } } @Override public boolean hasRender() { return false; } @Override public boolean hasUpdate() { return false; } }
0
0.968282
1
0.968282
game-dev
MEDIA
0.921234
game-dev
0.98182
1
0.98182
linuxdeepin/dde-file-manager
2,329
src/plugins/common/dfmplugin-menu/menu.h
// SPDX-FileCopyrightText: 2022 - 2023 UnionTech Software Technology Co., Ltd. // // SPDX-License-Identifier: GPL-3.0-or-later #ifndef MENU_H #define MENU_H #include "dfmplugin_menu_global.h" #include <dfm-base/interfaces/abstractscenecreator.h> #include <dfm-framework/dpf.h> namespace dfmplugin_menu { class MenuHandle : public QObject { Q_OBJECT public: explicit MenuHandle(QObject *parent = nullptr); ~MenuHandle(); bool init(); public slots: // scene bool contains(const QString &name); bool registerScene(const QString &name, DFMBASE_NAMESPACE::AbstractSceneCreator *creator); DFMBASE_NAMESPACE::AbstractSceneCreator *unregisterScene(const QString &name); bool bind(const QString &name, const QString &parent); void unbind(const QString &name, const QString &parent = QString()); DFMBASE_NAMESPACE::AbstractMenuScene *createScene(const QString &name); // utils QVariantHash perfectMenuParams(const QVariantHash &params); bool isMenuDisable(const QVariantHash &params); private slots: void publishSceneAdded(const QString &scene); void publishSceneRemoved(const QString &scene); protected: void createSubscene(DFMBASE_NAMESPACE::AbstractSceneCreator *creator, DFMBASE_NAMESPACE::AbstractMenuScene *parent); private: QHash<QString, DFMBASE_NAMESPACE::AbstractSceneCreator *> creators; QReadWriteLock locker; }; class Menu : public dpf::Plugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.deepin.plugin.common" FILE "menu.json") public: virtual void initialize() override; virtual bool start() override; virtual void stop() override; private: MenuHandle *handle = nullptr; private: DPF_EVENT_NAMESPACE(DPMENU_NAMESPACE) // MenuScene DPF_EVENT_REG_SIGNAL(signal_MenuScene_SceneAdded) DPF_EVENT_REG_SIGNAL(signal_MenuScene_SceneRemoved) DPF_EVENT_REG_SLOT(slot_MenuScene_Contains) DPF_EVENT_REG_SLOT(slot_MenuScene_RegisterScene) DPF_EVENT_REG_SLOT(slot_MenuScene_UnregisterScene) DPF_EVENT_REG_SLOT(slot_MenuScene_Bind) DPF_EVENT_REG_SLOT(slot_MenuScene_Unbind) DPF_EVENT_REG_SLOT(slot_MenuScene_CreateScene) // menu utils DPF_EVENT_REG_SLOT(slot_Menu_PerfectParams) DPF_EVENT_REG_SLOT(slot_Menu_IsDisable) }; } // end namespace dfmplugin_menu #endif // MENU_H
0
0.940221
1
0.940221
game-dev
MEDIA
0.532039
game-dev,desktop-app
0.594687
1
0.594687
GregTechCEu/GregTech
8,501
src/main/java/gregtech/integration/bq/BQuDataFixer.java
package gregtech.integration.bq; import gregtech.api.GregTechAPI; import gregtech.api.util.Mods; import gregtech.datafix.migration.lib.MTERegistriesMigrator; import net.minecraft.command.ICommandSender; import net.minecraft.util.ResourceLocation; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public final class BQuDataFixer { private static final Logger LOG = LogManager.getLogger(BQuDataFixer.class); /** * {@code saves/<world>/betterquesting/QuestDatabase.json} */ private static final String QUEST_DB_JSON_FILE = "QuestDatabase.json"; /** * {@code config/betterquesting/resources/} */ private static final String BQ_RESOURCES_DIR = "resources"; private static final String MC_CONFIG_DIR = "config"; private static final String ID_8 = "id:8"; private static final String DAMAGE_2 = "Damage:2"; private static final String TAG_10 = "tag:10"; private static final String ORIG_ID_8 = "orig_id:8"; private static final String ORIG_META_3 = "orig_meta:3"; private static final String PLACEHOLDER = "betterquesting:placeholder"; private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); private BQuDataFixer() {} public static void onServerStarting(@NotNull ICommandSender server) { LOG.info("Attempting to apply BQu DataFixers"); Path worldDir = server.getEntityWorld().getSaveHandler().getWorldDirectory().toPath(); if (processWorldDir(worldDir)) { LOG.info("Successfully applied BQu data fixers"); } else { LOG.error("Failed to apply BQu data fixers"); } } /** * Processes the current world directory and applies data fixers * * @param worldDir the current world's directory * @return if processing was successful */ public static boolean processWorldDir(@NotNull Path worldDir) { LOG.info("Processing world directory"); Path bqDir = worldDir.resolve(Mods.Names.BETTER_QUESTING); Path questDbPath = bqDir.resolve(QUEST_DB_JSON_FILE); if (!Files.isRegularFile(questDbPath)) { LOG.info("Unable to find BQ Quest Database, assuming this is a new world"); return true; } JsonObject json; try { json = readJson(questDbPath); } catch (FileNotFoundException e) { LOG.info("Unable to find BQ Quest Database, assuming this is a new world"); return true; } catch (IOException e) { LOG.error("Failed to read BQ Quest Database in World Folder", e); return false; } for (var entry : json.entrySet()) { recurseJsonApplyFix(entry.getValue()); } try { writeJson(questDbPath, json); } catch (IOException e) { LOG.error("Failed to write BQ Quest DataBase in World Folder", e); } return true; } /** * Processes the BQu config directory and applies data fixers * * @param worldDir the current world's directory * @return if processing was successful */ public static boolean processConfigDir(@NotNull Path worldDir) { LOG.info("Processing config directory"); Path mcDir = worldDir.getParent().getParent(); Path configDir = mcDir.resolve(MC_CONFIG_DIR); Path bqConfigDir = configDir.resolve(Mods.Names.BETTER_QUESTING); List<Path> paths; try (var stream = Files.walk(bqConfigDir, 4)) { paths = stream.filter(p -> !p.endsWith(BQ_RESOURCES_DIR)) // do not walk down the resources dir .filter(Files::isRegularFile) .filter(path -> path.toFile().getName().endsWith(".json")) .collect(Collectors.toList()); } catch (IOException e) { LOG.error("Failed to read BQ Quest Database in Config Folder", e); return false; } Map<Path, JsonObject> map = new Object2ObjectOpenHashMap<>(paths.size()); for (Path path : paths) { try { map.put(path, readJson(path)); } catch (IOException e) { LOG.error("Failed to read BQ Quest File from Config Folder", e); } } map.values().stream() .flatMap(jsonObject -> jsonObject.entrySet().stream()) .map(Map.Entry::getValue) .forEach(BQuDataFixer::recurseJsonApplyFix); for (var entry : map.entrySet()) { try { writeJson(entry.getKey(), entry.getValue()); } catch (IOException e) { LOG.error("Failed to write BQ Quest File in Config Folder", e); } } return true; } /** * @param path the path to read * @return the json object stored at the path * @throws IOException if failure */ private static @NotNull JsonObject readJson(@NotNull Path path) throws IOException { LOG.info("Reading file at path {}", path); try (Reader reader = Files.newBufferedReader(path)) { return GSON.fromJson(reader, JsonObject.class); } } /** * Recursively walks a JSON file and applies datafixers to matching sub-objects * * @param element the json element to recurse */ private static void recurseJsonApplyFix(@NotNull JsonElement element) { if (element.isJsonObject()) { JsonObject object = element.getAsJsonObject(); if (object.has(ID_8)) { applyDataFix(object); } else { for (var entry : object.entrySet()) { recurseJsonApplyFix(entry.getValue()); } } } else if (element.isJsonArray()) { for (JsonElement value : element.getAsJsonArray()) { recurseJsonApplyFix(value); } } } /** * @param path the path to write the file * @param jsonObject the object to write * @throws IOException if failure */ private static void writeJson(@NotNull Path path, @NotNull JsonObject jsonObject) throws IOException { LOG.info("Writing file to path {}", path); try (Writer writer = Files.newBufferedWriter(path)) { GSON.toJson(jsonObject, writer); } } /** * Applies {@link MTERegistriesMigrator} fixes to a BQu json file * * @param jsonObject the json to fix */ private static void applyDataFix(@NotNull JsonObject jsonObject) { MTERegistriesMigrator migrator = GregTechAPI.MIGRATIONS.registriesMigrator(); ResourceLocation itemBlockId; short meta; String id = jsonObject.get(ID_8).getAsString(); boolean isPlaceHolder = PLACEHOLDER.equals(id); if (isPlaceHolder) { // fix cases where BQu marks items as missing with placeholders JsonObject orig = jsonObject.getAsJsonObject(TAG_10); if (orig == null) { return; } if (!orig.has(ORIG_ID_8) || !orig.has(ORIG_META_3)) { return; } itemBlockId = new ResourceLocation(orig.get(ORIG_ID_8).getAsString()); meta = orig.get(ORIG_META_3).getAsShort(); } else { itemBlockId = new ResourceLocation(id); meta = jsonObject.get(DAMAGE_2).getAsShort(); } ResourceLocation fixedName = migrator.fixItemName(itemBlockId, meta); if (fixedName != null) { jsonObject.add(ID_8, new JsonPrimitive(fixedName.toString())); } short fixedMeta = migrator.fixItemMeta(itemBlockId, meta); if (fixedMeta != meta) { jsonObject.add(DAMAGE_2, new JsonPrimitive(fixedMeta)); } if (isPlaceHolder) { jsonObject.remove(TAG_10); } } }
0
0.979709
1
0.979709
game-dev
MEDIA
0.847558
game-dev
0.979159
1
0.979159
SMGCommunity/Petari
4,100
src/Game/MapObj/AirBubble.cpp
#include "Game/LiveActor/HitSensor.hpp" #include "Game/MapObj/AirBubble.hpp" AirBubble::AirBubble(const char *pName) : LiveActor(pName) { _A4.x = 0.0f; _A4.y = 0.0f; _A4.z = 1.0f; _B0 = 0.0f; _C4 = 360; } void AirBubble::init(const JMapInfoIter &rIter) { MR::initDefaultPos(this, rIter); MR::useStageSwitchWriteDead(this, rIter); initModelManagerWithAnm("AirBubble", nullptr, false); MR::connectToSceneItem(this); initHitSensor(1); MR::addHitSensorMapObj(this, "body", 8, 130.0f * mScale.x, TVec3f(0.0f, 0.0f, 0.0f)); initEffectKeeper(0, nullptr, false); initSound(2, false); initNerve(&NrvAirBubble::AirBubbleNrvWait::sInstance); _C8 = 0; makeActorAppeared(); MR::setClippingFar100m(this); MR::startBck(this, "Move", nullptr); _C9 = 0; } void AirBubble::initAfterPlacement() { if (_C8) { MR::moveCoordAndTransToNearestRailPos(this); } _8C = mPosition; } void AirBubble::appear() { LiveActor::appear(); } void AirBubble::kill() { if (MR::isValidSwitchDead(this)) { MR::onSwitchDead(this); } LiveActor::kill(); } void AirBubble::control() { } void AirBubble::appearMove(const TVec3f &a1, s32 a2) { _8C.set<f32>(a1); mPosition.set<f32>(a1); appear(); MR::showModel(this); setNerve(&NrvAirBubble::AirBubbleNrvMove::sInstance); MR::invalidateClipping(this); _C4 = a2 > 0 ? a2 : 360; } void AirBubble::exeBreak() { if (MR::isFirstStep(this)) { MR::startSound(this, "SE_OJ_AIR_BUBBLE_BREAK", -1, -1); MR::emitEffect(this, "RecoveryBubbleBreak"); MR::incPlayerOxygen(8); MR::tryRumblePadMiddle(this, 0); kill(); } } bool AirBubble::receiveMsgPush(HitSensor *pSender, HitSensor *pReceiver) { if (MR::isSensorPlayer(pReceiver)) { if (isNerve(&NrvAirBubble::AirBubbleNrvKillWait::sInstance)) { MR::incPlayerOxygen(8); kill(); return true; } else { setNerve(&NrvAirBubble::AirBubbleNrvBreak::sInstance); } return true; } return false; } bool AirBubble::receiveOtherMsg(u32 msg, HitSensor *pSender, HitSensor *pReceiver) { bool res; if (MR::isMsgItemShow(msg)) { return MR::receiveItemShowMsg(msg, pSender, pReceiver); } if (MR::isMsgItemHide(msg)) { return MR::receiveItemHideMsg(msg, pSender, pReceiver); } if (MR::isMsgItemStartMove(msg)) { _C9 = 1; return true; } else if (MR::isMsgItemEndMove(msg)) { _C9 = 0; _8C = mPosition; return true; } else if (MR::isMsgSpinStormRange(msg) && canSpinGet()) { TVec3f stack_8(pSender->mPosition); stack_8 -= mPosition; if (PSVECMag(&stack_8) < 250.0f) { setNerve(&NrvAirBubble::AirBubbleNrvBreak::sInstance); return true; } } return false; } bool AirBubble::canSpinGet() const { if (isNerve(&NrvAirBubble::AirBubbleNrvWait::sInstance) || isNerve(&NrvAirBubble::AirBubbleNrvMove::sInstance)) { return true; } return false; } AirBubble::~AirBubble() { } namespace NrvAirBubble { INIT_NERVE(AirBubbleNrvWait); INIT_NERVE(AirBubbleNrvMove); INIT_NERVE(AirBubbleNrvBreak); INIT_NERVE(AirBubbleNrvKillWait); void AirBubbleNrvKillWait::execute(Spine *pSpine) const { AirBubble* bubble = reinterpret_cast<AirBubble*>(pSpine->mExecutor); if (MR::isGreaterStep(bubble, 90)) { bubble->kill(); } } void AirBubbleNrvBreak::execute(Spine *pSpine) const { AirBubble* bubble = reinterpret_cast<AirBubble*>(pSpine->mExecutor); bubble->exeBreak(); } void AirBubbleNrvMove::execute(Spine *pSpine) const { AirBubble* bubble = reinterpret_cast<AirBubble*>(pSpine->mExecutor); bubble->exeMove(); } void AirBubbleNrvWait::execute(Spine *pSpine) const { AirBubble* bubble = reinterpret_cast<AirBubble*>(pSpine->mExecutor); bubble->exeWait(); } };
0
0.923848
1
0.923848
game-dev
MEDIA
0.908142
game-dev
0.976092
1
0.976092
Benimatic/twilightforest
3,534
src/main/java/twilightforest/item/ItemTFEmptyMazeMap.java
package twilightforest.item; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemMapBase; import net.minecraft.item.ItemStack; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import twilightforest.TFAchievementPage; import twilightforest.TFFeature; import twilightforest.TFMazeMapData; import twilightforest.TwilightForestMod; import twilightforest.world.WorldProviderTwilightForest; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemTFEmptyMazeMap extends ItemMapBase { boolean mapOres; protected ItemTFEmptyMazeMap(boolean mapOres) { super(); this.setCreativeTab(TFItems.creativeTab); this.mapOres = mapOres; } /** * Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer */ @Override public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) { ItemStack mapItem = new ItemStack(mapOres ? TFItems.oreMap : TFItems.mazeMap, 1, par2World.getUniqueDataId(ItemTFMazeMap.STR_ID)); String var5 = "mazemap_" + mapItem.getItemDamage(); TFMazeMapData mapData = new TFMazeMapData(var5); par2World.setItemData(var5, mapData); mapData.scale = 0; int step = 128 * (1 << mapData.scale); // need to fix center for feature offset if (par2World.provider instanceof WorldProviderTwilightForest && TFFeature.getFeatureForRegion(MathHelper.floor_double(par3EntityPlayer.posX) >> 4, MathHelper.floor_double(par3EntityPlayer.posZ) >> 4, par2World) == TFFeature.labyrinth) { ChunkCoordinates mc = TFFeature.getNearestCenterXYZ(MathHelper.floor_double(par3EntityPlayer.posX) >> 4, MathHelper.floor_double(par3EntityPlayer.posZ) >> 4, par2World); mapData.xCenter = mc.posX; mapData.zCenter = mc.posZ; mapData.yCenter = MathHelper.floor_double(par3EntityPlayer.posY); } else { mapData.xCenter = (int)(Math.round(par3EntityPlayer.posX / step) * step) + 10; // mazes are offset slightly mapData.zCenter = (int)(Math.round(par3EntityPlayer.posZ / step) * step) + 10; // mazes are offset slightly mapData.yCenter = MathHelper.floor_double(par3EntityPlayer.posY); } mapData.dimension = par2World.provider.dimensionId; mapData.markDirty(); --par1ItemStack.stackSize; //cheevos if (mapItem.getItem() == TFItems.mazeMap) { par3EntityPlayer.triggerAchievement(TFAchievementPage.twilightMazeMap); } if (mapItem.getItem() == TFItems.oreMap) { par3EntityPlayer.triggerAchievement(TFAchievementPage.twilightOreMap); } if (par1ItemStack.stackSize <= 0) { return mapItem; } else { if (!par3EntityPlayer.inventory.addItemStackToInventory(mapItem.copy())) { par3EntityPlayer.dropPlayerItemWithRandomChoice(mapItem, false); } return par1ItemStack; } } /** * Properly register icon source */ @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister par1IconRegister) { this.itemIcon = par1IconRegister.registerIcon(TwilightForestMod.ID + ":" + this.getUnlocalizedName().substring(5)); } }
0
0.841354
1
0.841354
game-dev
MEDIA
0.892373
game-dev
0.871778
1
0.871778
PCGen/pcgen
11,631
data/pathfinder/paizo/campaign_setting/inner_sea_world_guide/iswg_classes.lst
# Fri Nov 16 19:52:40 2018 -- reformated by PCGen PrettyLST v6.08.00 # CVS $Revision: $ $Author: $ -- Fri Jan 1 12:57:05 2016 -- reformated by PCGen PrettyLST v6.06.00 # Class Name Product Identity? Hit Dice Type Max Level Source Page Define Combat bonus Save bonus Modify VAR FACT CLASS:Harrower NAMEISPI:YES HD:6 TYPE:PC.Prestige MAXLEVEL:10 SOURCEPAGE:p.276 DEFINE:HarrowerLVL|0 BONUS:COMBAT|BASEAB|classlevel("APPLIEDAS=NONEPIC")/2|TYPE=Base.REPLACE|PREVAREQ:UseAlternateBABProgression,0 BONUS:SAVE|BASE.Will|(classlevel("APPLIEDAS=NONEPIC")+1)/2|PREVAREQ:UseAlternateSaveProgression,0 BONUS:SAVE|BASE.Fortitude,BASE.Reflex|(classlevel("APPLIEDAS=NONEPIC")+1)/3|PREVAREQ:UseAlternateSaveProgression,0 BONUS:VAR|ClassBABPoor|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalBAB,1 BONUS:VAR|HarrowerLVL|CL BONUS:VAR|ClassSavePoor_Fortitude|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 BONUS:VAR|ClassSavePoor_Reflex|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 BONUS:VAR|ClassSaveGood_Will|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 FACT:ClassType|PC FACT:Abb|Har # Class Name Required Ability Restricted AL Required Skill Required Text CLASS:Harrower PREABILITY:1,CATEGORY=FEAT,Harrowed !PREALIGN:TN PRESKILL:1,Knowledge (Arcana)=5,Knowledge (Religion)=5 PRESKILL:1,TYPE.Perform=5 PRETEXT:PRESPELLSCHOOL:3,Divination=0; PRESPELLTYPE:1,Arcane=3,Divine=3 PRETEXT:Must own a Harrow deck # Class Name Skill Pts/Lvl Class Skill CLASS:Harrower STARTSKILLPTS:2 CSKILL:Bluff|TYPE=Craft|Diplomacy|Knowledge (Arcana)|Knowledge (Local)|Knowledge (Planes)|Knowledge (Religion)|TYPE=Perform|TYPE=Profession|Spellcraft|Use Magic Device ###Block: Ability Progression 1 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Blessing of the Harrow 2 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Harrow Casting|Tower of Intelligence 3 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Tower of Strength 4 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Tower of Charisma 5 BONUS:VAR|SpiritDeckTimes|max(1,1+CHA) ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Spirit Deck 6 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Divination ~ Harrower 7 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Tower of Constitution 8 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Tower of Dexterity 9 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Tower of Wisdom 10 ADD:SPELLCASTER|ANY ABILITY:Special Ability|AUTOMATIC|Reading the Signs # Class Name Product Identity? Hit Dice Type Max Level Source Page Define Combat bonus Save bonus Modify VAR FACT CLASS:Hellknight NAMEISPI:YES HD:10 TYPE:PC.Prestige MAXLEVEL:10 SOURCEPAGE:p.278 DEFINE:HellknightLVL|0 BONUS:COMBAT|BASEAB|classlevel("APPLIEDAS=NONEPIC")|TYPE=Base.REPLACE|PREVAREQ:UseAlternateBABProgression,0 BONUS:SAVE|BASE.Fortitude|(classlevel("APPLIEDAS=NONEPIC")+1)/2|PREVAREQ:UseAlternateSaveProgression,0 BONUS:SAVE|BASE.Reflex,BASE.Will|(classlevel("APPLIEDAS=NONEPIC")+1)/3|PREVAREQ:UseAlternateSaveProgression,0 BONUS:VAR|ClassBABFull|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalBAB,1 BONUS:VAR|HellknightLVL|CL BONUS:VAR|ClassSaveGood_Fortitude|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 BONUS:VAR|ClassSavePoor_Reflex|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 BONUS:VAR|ClassSavePoor_Will|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 FACT:ClassType|PC FACT:Abb|HKn # Class Name Required Ability Required AL Required Skill Required Text PRETOTALAB CLASS:Hellknight PREABILITY:1,CATEGORY=FEAT,Armor Proficiency (Heavy) PREALIGN:LG,LN,LE PRESKILL:2,Intimidate=5,Knowledge (Planes)=2 PRETEXT:Must slay a devil with HD greater than your own. This must be witnessed by a Hellknight PRETOTALAB:5 # Class Name Skill Pts/Lvl Class Skill CLASS:Hellknight STARTSKILLPTS:2 CSKILL:Intimidate|Knowledge (Local)|Perception|Ride|Sense Motive ###Block: Level Progression 1 BONUS:VAR|AuraLawLVL|TL-AlignmentAuraLVL ABILITY:Special Ability|AUTOMATIC|Aura of Law 1 BONUS:ABILITYPOOL|Hellknight Order|1|TYPE=Base BONUS:VAR|HKSmiteTimes|(CL+2)/3 ABILITY:Special Ability|AUTOMATIC|Detect Chaos ~ HK|Smite Chaos ~ HK 2 ABILITY:Special Ability|AUTOMATIC|Discern Lies ~ HK|PREVARGT:3+CHA,0 2 BONUS:VAR|HellknightArmorLVL|CL ABILITY:Special Ability|AUTOMATIC|Hellknight Armor ~ HK 3 BONUS:ABILITYPOOL|Hellknight Force of Will 1|1 BONUS:VAR|HKDiscipline|CL/3 BONUS:VAR|HKForceOfWill|CL/3 ABILITY:Special Ability|AUTOMATIC|Discipline ~ HK|Force of Will ~ HK 6 BONUS:ABILITYPOOL|Hellknight Force of Will 2|1 7 ABILITY:Special Ability|AUTOMATIC|Lawbringer ~ HK 9 BONUS:ABILITYPOOL|Hellknight Force of Will 3|1 ABILITY:Special Ability|AUTOMATIC|Infernal Armor ~ HK 10 ABILITY:Special Ability|AUTOMATIC|Hell's Knight ~ HK # Class Name Hit Dice Type Max Level Source Page Define Combat bonus Save bonus Modify VAR FACT CLASS:Low Templar HD:10 TYPE:PC.Prestige MAXLEVEL:10 SOURCEPAGE:p.280 DEFINE:LowTemplarLVL|0 BONUS:COMBAT|BASEAB|classlevel("APPLIEDAS=NONEPIC")|TYPE=Base.REPLACE|PREVAREQ:UseAlternateBABProgression,0 BONUS:SAVE|BASE.Fortitude|(classlevel("APPLIEDAS=NONEPIC")+1)/2|PREVAREQ:UseAlternateSaveProgression,0 BONUS:SAVE|BASE.Reflex,BASE.Will|(classlevel("APPLIEDAS=NONEPIC")+1)/3|PREVAREQ:UseAlternateSaveProgression,0 BONUS:VAR|ClassBABFull|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalBAB,1 BONUS:VAR|LowTemplarLVL|CL BONUS:VAR|ClassSaveGood_Fortitude|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 BONUS:VAR|ClassSavePoor_Reflex|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 BONUS:VAR|ClassSavePoor_Will|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 FACT:ClassType|PC FACT:Abb|Low # Class Name Required Ability Required Skill CLASS:Low Templar PREABILITY:2,CATEGORY=FEAT,Mounted Combat,Weapon Focus (TYPE=Martial) PRESKILL:2,Bluff=5,Ride=5 PRESKILL:1,Knowledge (Nobility)=2,Knowledge (Planes)=2 # Class Name Skill Pts/Lvl Class Skill CLASS:Low Templar STARTSKILLPTS:2 CSKILL:Appraise|Bluff|TYPE=Craft|Diplomacy|Disguise|Escape Artist|Handle Animal|Intimidate|Knowledge (Local)|Knowledge (Nobility)|Knowledge (Planes)|Linguistics|Ride|Sense Motive|Stealth|Survival ###Block: Weapon & Armor Proficiencies 1 ABILITY:Internal|AUTOMATIC|TYPE=ArmorProfHeavy|TYPE=ShieldProfTower|TYPE=WeaponProfMartial ###Block: Level Progression 1 BONUS:VAR|LowCrusader|(CL+2)/3 ABILITY:Special Ability|AUTOMATIC|Crusader ~ Low|Flag of Convenience ~ Low 2 ABILITY:Special Ability|AUTOMATIC|Dirty Fighting ~ Low 3 BONUS:VAR|SneakAttackDice|(CL+2)/5 ABILITY:Special Ability|AUTOMATIC|Sneak Attack 5 BONUS:ABILITYPOOL|Low Templar Path|1 ABILITY:Special Ability|AUTOMATIC|Live to Fight Another Day ~ Low 6 ABILITY:Special Ability|AUTOMATIC|Ruthless ~ Low 9 ABILITY:Special Ability|AUTOMATIC|Parting Shot ~ Low 10 BONUS:ABILITYPOOL|Low Templar Final Choice|1 ABILITY:Special Ability|AUTOMATIC|Planar Cohort ~ Low # Class Name Product Identity? Hit Dice Type Max Level Source Page Define Combat bonus Save bonus Modify VAR FACT CLASS:Red Mantis Assassin NAMEISPI:YES HD:8 TYPE:PC.Prestige MAXLEVEL:10 SOURCEPAGE:p.282 DEFINE:RedMantisAssassinLVL|0 DEFINE:Caster_Level_RedMantisAssassin|0 DEFINE:CasterLevelBLRedMantisAssassin|0 DEFINE:Caster_Level_BL_Stripped_RedMantisAssassin|0 BONUS:COMBAT|BASEAB|classlevel("APPLIEDAS=NONEPIC")*3/4|TYPE=Base.REPLACE|PREVAREQ:UseAlternateBABProgression,0 BONUS:SAVE|BASE.Reflex,BASE.Will|(classlevel("APPLIEDAS=NONEPIC")+1)/2|PREVAREQ:UseAlternateSaveProgression,0 BONUS:SAVE|BASE.Fortitude|(classlevel("APPLIEDAS=NONEPIC")+1)/3|PREVAREQ:UseAlternateSaveProgression,0 BONUS:VAR|ClassBABModerate|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalBAB,1 BONUS:VAR|RedMantisLVL|CL BONUS:VAR|ClassSavePoor_Fortitude|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 BONUS:VAR|ClassSaveGood_Reflex|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 BONUS:VAR|ClassSaveGood_Will|classlevel("APPLIEDAS=NONEPIC")|PREVAREQ:UseFractionalSave,1 BONUS:VAR|Caster_Level_BL_Stripped_RedMantisAssassin|Caster_Level_RedMantisAssassin-CasterLevelBLRedMantisAssassin BONUS:VAR|Caster_Level_RedMantisAssassin|RedMantisAssassinLVL+Caster_Level_Bonus+CasterLevelBLRedMantisAssassin BONUS:VAR|Caster_Level_Highest__Arcane|Caster_Level_RedMantisAssassin|TYPE=Base BONUS:VAR|Caster_Level_Total__Arcane|Caster_Level_RedMantisAssassin FACT:ClassType|PC FACT:Abb|RMA FACT:SpellType|Arcane # Class Name Required Ability Required AL Required Skill CLASS:Red Mantis Assassin PREABILITY:4,CATEGORY=FEAT,Alertness,Exotic Weapon Proficiency (Sawtooth Sabre),Two-Weapon Fighting,Weapon Focus (Sawtooth Sabre) PREALIGN:LE PRESKILL:3,Intimidate=5,Perception=5,Stealth=5 # Class Name Skill Pts/Lvl Class Skill CLASS:Red Mantis Assassin STARTSKILLPTS:6 CSKILL:Acrobatics|Appraise|Bluff|Climb|Disguise|Escape Artist|Heal|Intimidate|Knowledge (Local)|Knowledge (Nature)|Knowledge (Nobility)|Knowledge (Religion)|Perception|Sense Motive|Stealth # Class Name Spell Stat Memorize Spell Scoll Prohibited Caster level Use Spell List CLASS:Red Mantis Assassin SPELLSTAT:CHA MEMORIZE:NO PROHIBITED:Abjuration,Conjuration,Divination,Enchantment,Evocation,Necromancy BONUS:CASTERLEVEL|Red Mantis Assassin|Caster_Level_RedMantisAssassin SPELLLIST:2|Sorcerer|Wizard ###Block: Weapon & Armor Proficiencies 1 ABILITY:Class Feature|AUTOMATIC|RMA Weapon Proficiencies 1 ABILITY:Internal|AUTOMATIC|TYPE=ArmorProfLight|TYPE=WeaponProfMartial ###Block: Level Progression 1 BONUS:VAR|SneakAttackDice|1 BONUS:VAR|SabreFightingLvl|CL ABILITY:Special Ability|AUTOMATIC|Armored Casting ~ RMA|Sabre Fighting|Sneak Attack 2 ABILITY:Special Ability|AUTOMATIC|Prayer Attack|RMA Bonus Spells 3 ABILITY:Special Ability|AUTOMATIC|Red Shroud 4 BONUS:VAR|SneakAttackDice|1 ABILITY:Special Ability|AUTOMATIC|Summon Mantis 5 BONUS:VAR|SabreFighting|1 ABILITY:Special Ability|AUTOMATIC|Resurrection Sense 6 ABILITY:Special Ability|AUTOMATIC|Mantis Form|PREVARLT:RedMantisAssassinLvl,8 7 BONUS:VAR|SneakAttackDice|1 8 ABILITY:Special Ability|AUTOMATIC|Fading ABILITY:Special Ability|AUTOMATIC|Blood Mantis Form|PREVARLT:RedMantisAssassinLvl,10 9 ABILITY:Special Ability|AUTOMATIC|Mantis Doom 10 BONUS:VAR|SneakAttackDice|1 ABILITY:Special Ability|AUTOMATIC|Death Mantis Form ###Block: Spells 1 CAST:0,1 KNOWN:0,2 2 CAST:0,2 KNOWN:0,3 3 CAST:0,3 KNOWN:0,4 4 CAST:0,3,1 KNOWN:0,4,2 5 CAST:0,4,2 KNOWN:0,4,3 6 CAST:0,4,3 KNOWN:0,4,4 7 CAST:0,4,3,1 KNOWN:0,5,4,2 8 CAST:0,4,4,2 KNOWN:0,5,4,3 9 CAST:0,5,4,3 KNOWN:0,5,4,4 10 CAST:0,5,4,3,1 KNOWN:0,5,5,4,2 # Class Name CLASS:Druid.MOD 1 PROHIBITSPELL:DESCRIPTOR.Fire|PREABILITY:1,CATEGORY=FEAT,Shade of the Uskwood
0
0.77714
1
0.77714
game-dev
MEDIA
0.973444
game-dev
0.793802
1
0.793802
Doddler/RagnarokRebuildTcp
1,195
RebuildClient/Assets/Scripts/SkillHandlers/Handlers/Acolyte/SignumCrusisHandler.cs
using Assets.Scripts.Effects.EffectHandlers; using Assets.Scripts.Network; using Assets.Scripts.Objects; using RebuildSharedData.Enum; using RebuildSharedData.Enum.EntityStats; namespace Assets.Scripts.SkillHandlers.Handlers { [SkillHandler(CharacterSkill.SignumCrusis)] public class SignumCrusisHandler : SkillHandlerBase { public override void StartSkillCasting(ServerControllable src, ServerControllable target, int lvl, float castTime) { HoldStandbyMotionForCast(src, castTime); src.AttachEffect(CastEffect.Create(castTime, src.gameObject, AttackElement.Holy)); } public override void ExecuteSkillTargeted(ServerControllable src, ref AttackResultData attack) { if (src == null) return; src.PerformSkillMotion(); AudioManager.Instance.OneShotSoundEffect(src.Id, "ef_signum.ogg", src.transform.position, 1f, 0.5f); AudioManager.Instance.OneShotSoundEffect(src.Id, "ef_bash.ogg", src.transform.position, 1f, 0.5f); CameraFollower.Instance.AttachEffectToEntity("SignumCrusis", src.gameObject, src.Id); } } }
0
0.879424
1
0.879424
game-dev
MEDIA
0.990661
game-dev
0.829004
1
0.829004
OpenXRay/xray-15
1,166
cs/engine/xrGame/ai/monsters/states/monster_state_attack_melee_inline.h
#pragma once #define TEMPLATE_SPECIALIZATION template <\ typename _Object\ > #define CStateMonsterAttackMeleeAbstract CStateMonsterAttackMelee<_Object> TEMPLATE_SPECIALIZATION CStateMonsterAttackMeleeAbstract::CStateMonsterAttackMelee(_Object *obj) : inherited(obj) { } TEMPLATE_SPECIALIZATION CStateMonsterAttackMeleeAbstract::~CStateMonsterAttackMelee() { } TEMPLATE_SPECIALIZATION void CStateMonsterAttackMeleeAbstract::execute() { object->set_action (ACT_ATTACK); if (object->control().direction().is_face_target(object->EnemyMan.get_enemy(), PI_DIV_3)) object->dir().face_target (object->EnemyMan.get_enemy(), 800); else object->dir().face_target (object->EnemyMan.get_enemy(), 0, deg(15)); object->set_state_sound (MonsterSound::eMonsterSoundAggressive); } TEMPLATE_SPECIALIZATION bool CStateMonsterAttackMeleeAbstract::check_start_conditions() { return ( object->MeleeChecker.can_start_melee(object->EnemyMan.get_enemy()) && object->EnemyMan.see_enemy_now() ); } TEMPLATE_SPECIALIZATION bool CStateMonsterAttackMeleeAbstract::check_completion() { return (object->MeleeChecker.should_stop_melee(object->EnemyMan.get_enemy())); }
0
0.914193
1
0.914193
game-dev
MEDIA
0.868621
game-dev
0.941115
1
0.941115
Avatarchik/Pixel-PUBG
3,806
Assets/Game/GUI/Elements/Inventory/GUIItemEquipped.cs
using UnityEngine; using UnityEngine.EventSystems; //װGUI public class GUIItemEquipped : MonoBehaviour, IDropHandler { public ItemCollector CurrentItemCollector; public ItemSticker CurrentSticker; public string Tag; public EquipType Type; [HideInInspector] public GUIItemCollector guiItem; void Start() { } void Awake() { guiItem = this.GetComponent<GUIItemCollector>(); } // public void Clear() { if (CurrentItemCollector != null) CurrentItemCollector.Clear(); CurrentSticker = null; } //л public void Toggle(){ if (UnitZ.playerManager != null && UnitZ.playerManager.PlayingCharacter != null && UnitZ.playerManager.PlayingCharacter.inventory != null) UnitZ.playerManager.PlayingCharacter.inventory.ToggleUseEquipped(CurrentItemCollector); } public void SetupCollector() { //if (UnitZ.playerManager.PlayingCharacter == null) //return; if (CurrentSticker != null) { CurrentItemCollector = UnitZ.playerManager.PlayingCharacter.inventory.GetItemCollectorByEquipIndex(CurrentSticker.Index); if (guiItem != null) guiItem.Item = CurrentItemCollector; } } //ӳ public void OnDrop(PointerEventData data) { if (UnitZ.playerManager.PlayingCharacter == null) return; GUIItemEquipped itemEquip = GetItemEquipDrop(data); if (itemEquip != null) { //װƷл UnitZ.playerManager.PlayingCharacter.inventory.SwapEquppedSticker(CurrentSticker, itemEquip.CurrentSticker); return; } GUIItemCollector itemDrop = GetItemCollectorDrop(data); if (itemDrop != null && itemDrop.Item != null) { //װƷ if (itemDrop.Type == "Inventory") { if (itemDrop.Item != null) { if (UnitZ.playerManager.PlayingCharacter.inventory.EquipItemToStickerByCollector(itemDrop.Item, CurrentSticker)) UnitZ.playerManager.PlayingCharacter.inventory.ToggleUseEquipped(itemDrop.Item); } } //ӵװƷ if (itemDrop.Type == "Ground") { if (itemDrop.Item != null) { UnitZ.playerManager.PlayingCharacter.Interactive(itemDrop.Item.Item.gameObject); UnitZ.playerManager.PlayingCharacter.inventory.stickerTarget = CurrentSticker; } } } } //ӻ public void DropBackToInventory() { if (CurrentItemCollector != null) UnitZ.playerManager.PlayingCharacter.inventory.UnEquipItem(CurrentItemCollector); } //ӻص public void DropToGround() { if (CurrentItemCollector != null) UnitZ.playerManager.PlayingCharacter.inventory.DropItemByCollector(CurrentItemCollector, CurrentItemCollector.Num); } //GUi private GUIItemCollector GetItemCollectorDrop(PointerEventData data) { var originalObj = data.pointerDrag; if (originalObj == null) { return null; } if (originalObj.GetComponent<GUIItemCollector>()) { return originalObj.GetComponent<GUIItemCollector>(); } return null; } //GUIƷװ private GUIItemEquipped GetItemEquipDrop(PointerEventData data) { var originalObj = data.pointerDrag; if (originalObj == null) { return null; } if (originalObj.GetComponent<GUIItemEquipped>()) { return originalObj.GetComponent<GUIItemEquipped>(); } return null; } }
0
0.861424
1
0.861424
game-dev
MEDIA
0.98534
game-dev
0.938952
1
0.938952
project-topaz/topaz
2,060
scripts/zones/Northern_San_dOria/npcs/Charlaimagnat.lua
----------------------------------- -- Area: Northern San d'Oria -- NPC: Charlaimagnat -- Standard Info NPC ----------------------------------- local ID = require("scripts/zones/Northern_San_dOria/IDs") require("scripts/globals/keyitems") require("scripts/globals/quests") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) local realday = tonumber(tostring(os.date("%Y")) .. os.date("%m") .. os.date("%d")) local TheMissingPiece = player:getQuestStatus(OUTLANDS, tpz.quest.id.outlands.THE_MISSING_PIECE) if (TheMissingPiece == QUEST_ACCEPTED and player:hasKeyItem(tpz.ki.TABLET_OF_ANCIENT_MAGIC) and player:hasKeyItem(tpz.ki.LETTER_FROM_ALFESAR)) then player:startEvent(703) -- Continuing the Quest elseif (TheMissingPiece == QUEST_ACCEPTED and realday < player:getCharVar("TheMissingPiece_date")) then player:startEvent(704) -- didn't wait a day yet elseif (TheMissingPiece == QUEST_ACCEPTED and realday >= player:getCharVar("TheMissingPiece_date")) then player:startEvent(705) -- Quest Completed else player:startEvent(702) -- standard dialogue end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 703) then player:setCharVar("TheMissingPiece_date", tostring(os.date("%Y")) .. os.date("%m") .. os.date("%d") + 1) player:addTitle(tpz.title.ACQUIRER_OF_ANCIENT_ARCANUM) player:delKeyItem(tpz.ki.TABLET_OF_ANCIENT_MAGIC) player:delKeyItem(tpz.ki.LETTER_FROM_ALFESAR) elseif (csid == 705) then if (player:getFreeSlotsCount() == 0) then -- does the player have space player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, 4729) else -- give player teleport-altep player:addItem(4729) player:messageSpecial(ID.text.ITEM_OBTAINED, 4729) player:addFame(RABAO, 30) player:completeQuest(OUTLANDS, tpz.quest.id.outlands.THE_MISSING_PIECE) end end end
0
0.895435
1
0.895435
game-dev
MEDIA
0.948594
game-dev
0.967647
1
0.967647
CraneInForest/LockStepSimpleFramework-Shared
8,739
core/BattleLogic.cs
// // @brief: 战斗主逻辑 // @version: 1.0.0 // @author helin // @date: 8/20/2018 // // // using System.Collections; public class BattleLogic { //是否暂停(进入结算界面时, 战斗逻辑就会暂停) public bool m_bIsBattlePause = true; //帧同步核心逻辑对象 LockStepLogic m_lockStepLogic = null; //战斗日志 string battleRecord = ""; //游戏逻辑帧 static public int s_uGameLogicFrame = 0; //是否已开战 private bool m_bFireWar = false; //- 主循环 // Some description, can be over several lines. // @return value description. // @author public void updateLogic() { //如果战斗逻辑暂停则不再运行 if (m_bIsBattlePause) { return; } //调用帧同步逻辑 m_lockStepLogic.updateLogic(); } //- 战斗逻辑 // // @return none public void frameLockLogic() { //如果是回放模式 if (GameData.g_bRplayMode) { //检测回放事件 checkPlayBackEvent(GameData.g_uGameLogicFrame); } recordLastPos(); //动作管理器update GameData.g_actionMainManager.updateLogic(); //塔 for (int i = 0; i < GameData.g_listTower.Count; i++) { GameData.g_listTower[i].updateLogic(); } //子弹 for (int i = 0; i < GameData.g_listBullet.Count; i++) { GameData.g_listBullet[i].updateLogic(); } //士兵 for (int i = 0; i < GameData.g_listSoldier.Count; i++) { GameData.g_listSoldier[i].updateLogic(); } if (m_bFireWar && GameData.g_listSoldier.Count == 0) { stopBattle(); } } //- 记录最后的位置 // // @return none. void recordLastPos() { //子弹 for (int i = 0; i < GameData.g_listBullet.Count; i++) { GameData.g_listBullet[i].recordLastPos(); } //士兵 for (int i = 0; i < GameData.g_listSoldier.Count; i++) { GameData.g_listSoldier[i].recordLastPos(); } } //- 更新各种对象绘制的位置 // 包括怪,子弹等等,因为塔的位置是固定的,所以不需要实时刷新塔的位置,提升效率 // @return none public void updateRenderPosition(float interpolation) { //子弹 for (int i = 0; i<GameData.g_listBullet.Count; i++) { GameData.g_listBullet[i].updateRenderPosition(interpolation); } //士兵 for (int i = 0; i<GameData.g_listSoldier.Count; i++) { GameData.g_listSoldier[i].updateRenderPosition(interpolation); } } //- 初始化 // // @param mt 上下文句柄 // @return 元表 public void init() { UnityTools.Log ("BattleLogic init!"); //初始化帧同步逻辑对象 m_lockStepLogic = new LockStepLogic(); m_lockStepLogic.setCallUnit(this); //游戏运行速度 UnityTools.setTimeScale(1); //战斗不暂停 m_bIsBattlePause = true; } /// <summary> /// 开始战斗 /// </summary> /// <returns></returns> public void startBattle() { GameData.g_srand = new SRandom(1000); m_bIsBattlePause = false; m_lockStepLogic.init(); //读取玩家操作数据,为回放做准备 if (GameData.g_bRplayMode) { loadUserCtrlInfo(); } GameData.g_uGameLogicFrame = 0; TowerStandState.s_fixTestCount = (Fix64)0; TowerStandState.s_scTestContent = ""; //创建塔 createTowers(); } /// <summary> /// 停止战斗 /// </summary> /// <returns></returns> public void stopBattle() { UnityTools.Log("end logic frame: " + GameData.g_uGameLogicFrame); UnityTools.Log("s_fixTestCount: " + TowerStandState.s_fixTestCount); UnityTools.Log("s_scTestContent: " + TowerStandState.s_scTestContent); m_bFireWar = false; s_uGameLogicFrame = GameData.g_uGameLogicFrame; //记录关键事件 if (!GameData.g_bRplayMode) { GameData.battleInfo info = new GameData.battleInfo(); info.uGameFrame = GameData.g_uGameLogicFrame; info.sckeyEvent = "stopBattle"; GameData.g_listUserControlEvent.Add(info); } gameEnd(); } /// <summary> /// 回放战斗录像 /// </summary> /// <returns></returns> public void replayVideo() { GameData.g_bRplayMode = true; GameData.g_uGameLogicFrame = 0; startBattle(); } /// <summary> /// 创建塔 /// </summary> /// <returns></returns> private void createTowers() { for (int i = 0; i < 5; i++) { var tower = GameData.g_towerFactory.createTower(); tower.m_fixv3LogicPosition = new FixVector3((Fix64)5, (Fix64)1.3f, (Fix64)(-3.0f) + (Fix64)2.5f * i); tower.updateRenderPosition(0); } } /// <summary> /// 创建士兵 /// </summary> /// <returns></returns> public void createSoldier() { m_bFireWar = true; var soldier = GameData.g_soldierFactory.createSoldier(); soldier.m_fixv3LogicPosition = new FixVector3((Fix64)0, (Fix64)1, (Fix64)(-4.0f)); soldier.updateRenderPosition(0); float moveSpeed = 3 + GameData.g_srand.Range(0, 3); soldier.moveTo(soldier.m_fixv3LogicPosition, new FixVector3(soldier.m_fixv3LogicPosition.x, soldier.m_fixv3LogicPosition.y, (Fix64)8), (Fix64)moveSpeed); //记录关键事件 if (!GameData.g_bRplayMode) { GameData.battleInfo info = new GameData.battleInfo(); info.uGameFrame = GameData.g_uGameLogicFrame; info.sckeyEvent = "createSoldier"; GameData.g_listUserControlEvent.Add(info); } } //- 读取玩家的操作信息 // // @return none void loadUserCtrlInfo() { GameData.g_listPlaybackEvent.Clear(); string content = battleRecord; string[] contents = content.Split('$'); for (int i = 0; i < contents.Length - 1; i++) { string[] battleInfo = contents[i].Split(','); GameData.battleInfo info = new GameData.battleInfo(); info.uGameFrame = int.Parse(battleInfo[0]); info.sckeyEvent = battleInfo[1]; GameData.g_listPlaybackEvent.Add(info); } } //- 检测回放事件 // 如果有回放事件则进行回放 // @param gameFrame 当前的游戏帧 // @return none void checkPlayBackEvent(int gameFrame) { if (GameData.g_listPlaybackEvent.Count > 0) { for (int i = 0; i < GameData.g_listPlaybackEvent.Count; i++) { GameData.battleInfo v = GameData.g_listPlaybackEvent[i]; if (gameFrame == v.uGameFrame) { if (v.sckeyEvent == "createSoldier") { createSoldier(); } } } } } //- 暂停战斗逻辑 // // @return none. void pauseBattleLogic() { m_bIsBattlePause = true; } public void gameEnd() { if (!m_bIsBattlePause) { //UnityTools.setTimeScale(1); //销毁战场上的所有对象 //塔 for (int i = GameData.g_listTower.Count - 1; i >= 0; i--) { GameData.g_listTower[i].killSelf(); } //子弹 for (int i = GameData.g_listBullet.Count - 1; i >= 0; i--) { GameData.g_listBullet[i].killSelf(); } //士兵 for (int i = GameData.g_listSoldier.Count - 1; i >= 0; i--) { GameData.g_listSoldier[i].killSelf(); } if (!GameData.g_bRplayMode) { recordBattleInfo(); #if _CLIENTLOGIC_ SimpleSocket socket = new SimpleSocket(); socket.Init(); socket.sendBattleRecordToServer(UnityTools.playerPrefsGetString("battleRecord")); #endif } pauseBattleLogic(); GameData.g_bRplayMode = false; GameData.release(); } } //- 记录战斗信息(回放时使用) // // @return none void recordBattleInfo() { if (false == GameData.g_bRplayMode) { //记录战斗数据 string content = ""; for (int i = 0; i < GameData.g_listUserControlEvent.Count; i++) { GameData.battleInfo v = GameData.g_listUserControlEvent[i]; //出兵 if (v.sckeyEvent == "createSoldier") { content += v.uGameFrame + "," + v.sckeyEvent + "$"; } } UnityTools.playerPrefsSetString("battleRecord", content); GameData.g_listUserControlEvent.Clear(); } } public void setBattleRecord(string record) { battleRecord = record; } //- 释放资源 // // @return none void release() { } }
0
0.646632
1
0.646632
game-dev
MEDIA
0.816358
game-dev
0.816539
1
0.816539
Brackeys/MultiplayerFPS-Tutorial
2,315
MultiplayerFPS/Assets/Standard Assets/ParticleSystems/Scripts/ExplosionFireAndDebris.cs
using System; using System.Collections; using UnityEngine; using Random = UnityEngine.Random; namespace UnityStandardAssets.Effects { public class ExplosionFireAndDebris : MonoBehaviour { public Transform[] debrisPrefabs; public Transform firePrefab; public int numDebrisPieces = 0; public int numFires = 0; private IEnumerator Start() { float multiplier = GetComponent<ParticleSystemMultiplier>().multiplier; for (int n = 0; n < numDebrisPieces*multiplier; ++n) { var prefab = debrisPrefabs[Random.Range(0, debrisPrefabs.Length)]; Vector3 pos = transform.position + Random.insideUnitSphere*3*multiplier; Quaternion rot = Random.rotation; Instantiate(prefab, pos, rot); } // wait one frame so these new objects can be picked up in the overlapsphere function yield return null; float r = 10*multiplier; var cols = Physics.OverlapSphere(transform.position, r); foreach (var col in cols) { if (numFires > 0) { RaycastHit fireHit; Ray fireRay = new Ray(transform.position, col.transform.position - transform.position); if (col.Raycast(fireRay, out fireHit, r)) { AddFire(col.transform, fireHit.point, fireHit.normal); numFires--; } } } float testR = 0; while (numFires > 0 && testR < r) { RaycastHit fireHit; Ray fireRay = new Ray(transform.position + Vector3.up, Random.onUnitSphere); if (Physics.Raycast(fireRay, out fireHit, testR)) { AddFire(null, fireHit.point, fireHit.normal); numFires--; } testR += r*.1f; } } private void AddFire(Transform t, Vector3 pos, Vector3 normal) { pos += normal*0.5f; Transform fire = (Transform) Instantiate(firePrefab, pos, Quaternion.identity); fire.parent = t; } } }
0
0.739128
1
0.739128
game-dev
MEDIA
0.95553
game-dev
0.819036
1
0.819036
Sheldonfrith/bevy_gpu_compute
3,754
bevy_gpu_compute_macro/src/pipeline/phases/wgsl_helper_transformer/run.rs
use proc_macro2::TokenStream; use syn::{ Expr, ItemFn, ItemMod, parse_quote, visit::Visit, visit_mut::{self, VisitMut}, }; use crate::pipeline::phases::custom_type_collector::custom_type::CustomType; use super::{ erroneous_usage_finder::ErroneousUsageFinder, helper_method::WgslHelperMethod, parse::parse_possible_wgsl_helper, to_expanded_format::ToExpandedFormat, to_expanded_format_for_cpu::ToExpandedFormatForCpu, }; /// Rust's normal type checking will ensure that these helper functions are using correctly defined types pub fn transform_wgsl_helper_methods( custom_types: &[CustomType], rust_module: &mut ItemMod, for_cpu: bool, ) { let mut converter = WgslHelperExpressionConverter::new(custom_types, for_cpu); converter.visit_item_mod_mut(rust_module); if !for_cpu { let mut error_finder = ErroneousUsageFinder::new(custom_types); error_finder.visit_item_mod(rust_module); } } struct WgslHelperExpressionConverter { custom_types: Vec<CustomType>, in_main_func: bool, nesting_level: u32, for_cpu: bool, } impl VisitMut for WgslHelperExpressionConverter { fn visit_item_fn_mut(&mut self, node: &mut ItemFn) { if node.sig.ident == "main" && self.nesting_level == 0 { self.in_main_func = true; self.nesting_level += 1; visit_mut::visit_item_fn_mut(self, node); self.nesting_level -= 1; self.in_main_func = false; } else { // For any other function, just increment nesting level and continue self.nesting_level += 1; visit_mut::visit_item_fn_mut(self, node); self.nesting_level -= 1; } } fn visit_expr_mut(&mut self, expr: &mut Expr) { if self.nesting_level > 0 { let in_main = self.in_main_func && self.nesting_level == 1; if let Expr::Call(call) = expr { let helper_method = parse_possible_wgsl_helper(call, &self.custom_types); if let Some(method) = helper_method { if self.for_cpu { let replacement = process_wgsl_helper_for_cpu(method); *expr = parse_quote!(#replacement); } else { let replacement = process_wgsl_helper(method, in_main); *expr = parse_quote!(#replacement); } } } } // Continue visiting child nodes visit_mut::visit_expr_mut(self, expr); } } impl WgslHelperExpressionConverter { pub fn new(custom_types: &[CustomType], for_cpu: bool) -> Self { Self { custom_types: custom_types.to_vec(), in_main_func: false, nesting_level: 0, for_cpu, } } } fn process_wgsl_helper(helper_method: WgslHelperMethod, in_main_func: bool) -> TokenStream { if !helper_method .method_expander_kind .as_ref() .unwrap() .valid_outside_main() && !in_main_func { panic!( "WGSL helpers that read from inputs or write to outputs (`bevy_gpu_compute_core::wgsl_helpers`) can only be used inside the main function. It is technically possible to pass in entire input arrays, configs, or output arrays to helper functions, but considering the performance implications, it is not recommended. Instead interact with your inputs and outputs in the main function and pass in only the necessary data to the helper functions." ); } ToExpandedFormat::run(&helper_method) } fn process_wgsl_helper_for_cpu(helper_method: WgslHelperMethod) -> TokenStream { ToExpandedFormatForCpu::run(&helper_method) }
0
0.757343
1
0.757343
game-dev
MEDIA
0.308312
game-dev
0.923402
1
0.923402
opanel-mc/opanel
3,429
forge-1.20.2/src/main/java/net/opanel/forge_1_20_2/Main.java
package net.opanel.forge_1_20_2; import com.mojang.logging.LogUtils; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.server.ServerStartedEvent; import net.minecraftforge.event.server.ServerStartingEvent; import net.minecraftforge.event.server.ServerStoppingEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.opanel.OPanel; import net.opanel.forge_1_20_2.command.OPanelCommand; import net.opanel.forge_1_20_2.config.Config; import net.opanel.forge_1_20_2.config.ConfigManagerImpl; import net.opanel.forge_1_20_2.terminal.LogListenerManagerImpl; import org.apache.logging.log4j.LogManager; import org.slf4j.Logger; @Mod(Main.MODID) @OnlyIn(Dist.DEDICATED_SERVER) public class Main { public static final String MODID = "opanel"; public static final Logger LOGGER = LogUtils.getLogger(); public OPanel instance; private LogListenerManagerImpl logListenerAppender; public Main() { ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.SPEC); MinecraftForge.EVENT_BUS.register(this); initLogListenerAppender(); } @SubscribeEvent public void onServerStarting(ServerStartingEvent event) { instance = new OPanel(new ConfigManagerImpl(), new LoggerImpl(LOGGER)); instance.setLogListenerManager(logListenerAppender); OPanelCommand.instance = instance; } private void initLogListenerAppender() { final org.apache.logging.log4j.core.Logger logger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger(); logListenerAppender = LogListenerManagerImpl.createAppender("LogListenerAppender", true); logListenerAppender.start(); logger.addAppender(logListenerAppender); } private void disposeLogListenerAppender() { final org.apache.logging.log4j.core.Logger logger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger(); logger.removeAppender(logListenerAppender); logListenerAppender.clearListeners(); } @SubscribeEvent public void onServerStart(ServerStartedEvent event) { if(instance == null) throw new NullPointerException("OPanel is not initialized."); instance.setServer(new ForgeServer(event.getServer())); try { instance.getWebServer().start(); // default port 3000 } catch (Exception e) { e.printStackTrace(); } } @SubscribeEvent public void onServerStop(ServerStoppingEvent event) { try { if(logListenerAppender != null) disposeLogListenerAppender(); } catch(Exception e) { LOGGER.error("Failed to dispose log listener appender: " + e.getMessage()); } try { if(instance != null) instance.stop(); } catch(Exception e) { LOGGER.error("Failed to stop OPanel instance: " + e.getMessage()); } } @SubscribeEvent public void onServerTick(TickEvent.ServerTickEvent event) { if(instance == null) throw new NullPointerException("OPanel is not initialized."); instance.onTick(); } }
0
0.892555
1
0.892555
game-dev
MEDIA
0.859142
game-dev
0.965188
1
0.965188
retronx-team/love-nx
3,549
repo/love/src/modules/physics/box2d/RevoluteJoint.h
/** * Copyright (c) 2006-2022 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #ifndef LOVE_PHYSICS_BOX2D_REVOLUTE_JOINT_H #define LOVE_PHYSICS_BOX2D_REVOLUTE_JOINT_H // Module #include "Joint.h" namespace love { namespace physics { namespace box2d { /** * A RevoluteJoint allows two bodies relative rotation * around a single point. **/ class RevoluteJoint : public Joint { public: static love::Type type; /** * Creates a new RevoluteJoint connecting body1 and body2. **/ RevoluteJoint(Body *body1, Body *body2, float xA, float yA, float xB, float yB, bool collideConnected); RevoluteJoint(Body *body1, Body *body2, float xA, float yA, float xB, float yB, bool collideConnected, float referenceAngle); virtual ~RevoluteJoint(); /** * Get the current joint angle in degrees. **/ float getJointAngle() const; /** * Get the current joint angle speed in degrees per second. **/ float getJointSpeed() const; /** * Enable/disable the joint motor. **/ void setMotorEnabled(bool enable); /** * Checks whether the motor is enabled. **/ bool isMotorEnabled() const; /** * Set the maximum motor torque, usually in N-m. **/ void setMaxMotorTorque(float torque); /** * Sets the motor speed in radians per second. **/ void setMotorSpeed(float speed); /** * Gets the motor speed in radians per second. **/ float getMotorSpeed() const; /** * Get the current motor torque, usually in N-m. * @param inv_dt The inverse timestep. **/ float getMotorTorque(float inv_dt) const; /** * Get the maximum motor torque, usually in N-m. **/ float getMaxMotorTorque() const; /** * Enable/disable the joint limit. **/ void setLimitsEnabled(bool enable); /** * Checks whether limits are enabled. **/ bool areLimitsEnabled() const; /** * Sets the upper limit in degrees. **/ void setUpperLimit(float limit); /** * Sets the lower limit in degrees. **/ void setLowerLimit(float limit); /** * Sets the limits in degrees. **/ void setLimits(float lower, float upper); /** * Gets the lower limit in degrees. **/ float getLowerLimit() const; /** * Gets the upper limit in degrees. **/ float getUpperLimit() const; /** * Gets the limits in degrees. * @returns The lower limit. * @returns The upper limit. **/ int getLimits(lua_State *L); /** * Gets the reference angle. **/ float getReferenceAngle() const; private: // The Box2D revolute joint object. b2RevoluteJoint *joint; void init(b2RevoluteJointDef &def, Body *body1, Body *body2, float xA, float yA, float xB, float yB, bool collideConnected); }; } // box2d } // physics } // love #endif // LOVE_PHYSICS_BOX2D_REVOLUTE_JOINT_H
0
0.803896
1
0.803896
game-dev
MEDIA
0.923981
game-dev
0.738479
1
0.738479
tenox7/micropolis
1,543
src/sim/s_init.c
#include "sim.h" /* Initialize Stuff */ /* comefrom: loadFile bootUp main doMessage */ InitWillStuff() { register short x, y, z; RandomlySeedRand(); InitGraphMax(); RoadEffect = 32; PoliceEffect = 1000; /*added*/ FireEffect = 1000; CityScore = 500; CityPop = -1; LastCityTime = -1; LastCityYear = -1; LastCityMonth = -1; LastFunds = -1; LastR = LastC = LastI = -999999; OverRide = 0; PendingTool = -1; MesNum = 0; MessagePort = 0; RoadFund = 0; PoliceFund = 0; FireFund = 0; UpdateDelayed = 0; ValveFlag = 1; DestroyAllSprites(); DisasterEvent = 0; TaxFlag = 0; for (x = 0; x < HWLDX; x++) { for (y = 0; y < HWLDY; y++) { PopDensity[x][y] = 0; TrfDensity[x][y] = 0; PollutionMem[x][y] = 0; LandValueMem[x][y] = 0; CrimeMem[x][y] = 0; } } for (x = 0; x < QWX; x++) { for (y = 0; y < QWY; y++) { TerrainMem[x][y] = 0; } } for (x = 0; x < SmX; x++) { for (y = 0; y < SmY; y++) { RateOGMem[x][y] = 0; FireRate[x][y] = 0; ComRate[x][y] = 0; PoliceMap[x][y] = 0; PoliceMapEffect[x][y] = 0; FireRate[x][y] = 0; } } ResetLastKeys(); DoNewGame(); DoUpdateHeads(); } ResetMapState() { SimView *view; for (view = sim->map; view != NULL; view = view->next) { view->map_state = ALMAP; } } ResetEditorState() { SimView *view; for (view = sim->editor; view != NULL; view = view->next) { view->tool_state = dozeState; view->tool_state_save = -1; } }
0
0.701297
1
0.701297
game-dev
MEDIA
0.742898
game-dev
0.884566
1
0.884566
ProjectIgnis/CardScripts
1,323
rush/c160436005.lua
--万能地雷グレイモヤ --Widespread Ruin (Rush) --scripted by YoshiDuels local s,id=GetID() function s.initial_effect(c) --Destroy a monster with the highest ATK local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_ATTACK_ANNOUNCE) e1:SetCondition(s.condition) e1:SetTarget(s.target) e1:SetOperation(s.activate) c:RegisterEffect(e1) end function s.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttacker():IsControler(1-tp) end function s.filter(c) return c:IsFaceup() and c:IsAttackPos() end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.filter,tp,0,LOCATION_MZONE,1,nil) end local g=Duel.GetMatchingGroup(s.filter,tp,0,LOCATION_MZONE,nil) local tg=g:GetMaxGroup(Card.GetAttack) Duel.SetOperationInfo(0,CATEGORY_DESTROY,tg,1,0,0) end function s.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(s.filter,tp,0,LOCATION_MZONE,nil) if #g==0 then return end local tg=g:GetMaxGroup(Card.GetAttack) if #tg>1 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local sg=tg:Select(tp,1,1,nil) sg=sg:AddMaximumCheck() Duel.HintSelection(sg,true) Duel.Destroy(sg,REASON_EFFECT) else tg=tg:AddMaximumCheck() Duel.Destroy(tg,REASON_EFFECT) end end
0
0.846466
1
0.846466
game-dev
MEDIA
0.992555
game-dev
0.962937
1
0.962937
crosslife/OpenBird
3,323
cocos2d/external/Box2D/Collision/Shapes/b2EdgeShape.cpp
/* * Copyright (c) 2006-2010 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Collision/Shapes/b2EdgeShape.h> #include <new> void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2) { m_vertex1 = v1; m_vertex2 = v2; m_hasVertex0 = false; m_hasVertex3 = false; } b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const { void* mem = allocator->Allocate(sizeof(b2EdgeShape)); b2EdgeShape* clone = new (mem) b2EdgeShape; *clone = *this; return clone; } int32 b2EdgeShape::GetChildCount() const { return 1; } bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const { B2_NOT_USED(xf); B2_NOT_USED(p); return false; } // p = p1 + t * d // v = v1 + s * e // p1 + t * d = v1 + s * e // s * e - t * d = p1 - v1 bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& xf, int32 childIndex) const { B2_NOT_USED(childIndex); // Put the ray into the edge's frame of reference. b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); b2Vec2 d = p2 - p1; b2Vec2 v1 = m_vertex1; b2Vec2 v2 = m_vertex2; b2Vec2 e = v2 - v1; b2Vec2 normal(e.y, -e.x); normal.Normalize(); // q = p1 + t * d // dot(normal, q - v1) = 0 // dot(normal, p1 - v1) + t * dot(normal, d) = 0 float32 numerator = b2Dot(normal, v1 - p1); float32 denominator = b2Dot(normal, d); if (denominator == 0.0f) { return false; } float32 t = numerator / denominator; if (t < 0.0f || input.maxFraction < t) { return false; } b2Vec2 q = p1 + t * d; // q = v1 + s * r // s = dot(q - v1, r) / dot(r, r) b2Vec2 r = v2 - v1; float32 rr = b2Dot(r, r); if (rr == 0.0f) { return false; } float32 s = b2Dot(q - v1, r) / rr; if (s < 0.0f || 1.0f < s) { return false; } output->fraction = t; if (numerator > 0.0f) { output->normal = -b2Mul(xf.q, normal); } else { output->normal = b2Mul(xf.q, normal); } return true; } void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const { B2_NOT_USED(childIndex); b2Vec2 v1 = b2Mul(xf, m_vertex1); b2Vec2 v2 = b2Mul(xf, m_vertex2); b2Vec2 lower = b2Min(v1, v2); b2Vec2 upper = b2Max(v1, v2); b2Vec2 r(m_radius, m_radius); aabb->lowerBound = lower - r; aabb->upperBound = upper + r; } void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const { B2_NOT_USED(density); massData->mass = 0.0f; massData->center = 0.5f * (m_vertex1 + m_vertex2); massData->I = 0.0f; }
0
0.950152
1
0.950152
game-dev
MEDIA
0.94818
game-dev
0.970748
1
0.970748
Valks-Games/sankari
3,458
Scripts/Linker.cs
namespace Sankari; public partial class Linker : Node { [Export] public bool DeveloperMode { get; set; } [Export] public bool LoadFirstLevel { get; set; } [Export] public bool PressPlayOnLaunch { get; set; } [Export] public bool AutoHostJoin { get; set; } [Export] public bool LoadTestLevel { get; set; } [Export] public bool InstantlyLoadLevel { get; set; } [Export] public NodePath NodePathTransition; public CanvasLayer CanvasLayer { get; private set; } public UIConsoleManager ConsoleManager { get; private set; } public UIPlayerList UIPlayerList { get; private set; } public UIMapMenu UIMapMenu { get; private set; } public Node SFXPlayers { get; private set; } private GameManager gameManager; public override async void _Ready() { SFXPlayers = GetNode<Node>("SFX Players"); CanvasLayer = GetNode<CanvasLayer>("CanvasLayer"); ConsoleManager = CanvasLayer.GetNode<UIConsoleManager>("PanelContainer/Console"); UIMapMenu = CanvasLayer.GetNode<UIMapMenu>("UIMapMenu"); UIPlayerList = CanvasLayer.GetNode<UIPlayerList>("Player List"); gameManager = new GameManager(this); UIPlayerList.SetupListeners(); if (DeveloperMode) { if (PressPlayOnLaunch) { if (!LoadTestLevel) { GameManager.Menu.PressPlay(); } else { Logger.LogWarning("Will not press play on launch because 'LoadTestLevel' was enabled"); } } if (LoadFirstLevel) { GameManager.Menu.Hide(); LevelManager.CurrentLevel = "Level A1"; await LevelManager.LoadLevel(InstantlyLoadLevel); } if (LoadTestLevel) { GameManager.Menu.Hide(); LevelManager.CurrentLevel = "Test Level"; await LevelManager.LoadLevel(InstantlyLoadLevel); } } } public override void _Process(double delta) { Logger.Update(); } public override void _Input(InputEvent @event) { if (Input.IsActionJustPressed("console")) ConsoleManager.ToggleVisibility(); } /*public override void _Input(InputEvent @event) { if (@event is InputEventKey inputEventKey) Notifications.Notify(this, Event.OnKeyboardInput, inputEventKey); if (@event is InputEventMouseButton inputEventMouseButton) Notifications.Notify(this, Event.OnMouseButtonInput, inputEventMouseButton); if (@event is InputEventMouseMotion inputEventMouseMotion) Notifications.Notify(this, Event.OnMouseMotionInput, inputEventMouseMotion); if (@event is InputEventJoypadButton inputEventJoypadButton) Notifications.Notify(this, Event.OnJoypadButtonInput, inputEventJoypadButton); }*/ public override async void _Notification(int what) { if (what == NotificationWMCloseRequest) { GetTree().AutoAcceptQuit = false; await Cleanup(); } } public async Task Cleanup() { if (Logger.StillWorking()) await Task.Delay(1); //ModLoader.SaveEnabled(); //Options.SaveOptions(); Tokens.Cleanup(); GetTree().Quit(); } }
0
0.886613
1
0.886613
game-dev
MEDIA
0.772444
game-dev
0.875767
1
0.875767
magefree/mage
2,018
Mage.Sets/src/mage/cards/t/TattermungeDuo.java
package mage.cards.t; import java.util.UUID; import mage.MageInt; import mage.ObjectColor; import mage.abilities.common.SpellCastControllerTriggeredAbility; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.effects.common.continuous.GainAbilitySourceEffect; import mage.abilities.keyword.ForestwalkAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.filter.FilterSpell; import mage.filter.predicate.mageobject.ColorPredicate; /** * * @author North */ public final class TattermungeDuo extends CardImpl { private static final FilterSpell redFilter = new FilterSpell("a red spell"); private static final FilterSpell greenFilter = new FilterSpell("a green spell"); static { redFilter.add(new ColorPredicate(ObjectColor.RED)); greenFilter.add(new ColorPredicate(ObjectColor.GREEN)); } public TattermungeDuo(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{R/G}"); this.subtype.add(SubType.GOBLIN); this.subtype.add(SubType.WARRIOR); this.subtype.add(SubType.SHAMAN); this.power = new MageInt(2); this.toughness = new MageInt(3); // Whenever you cast a red spell, Tattermunge Duo gets +1/+1 until end of turn. this.addAbility(new SpellCastControllerTriggeredAbility(new BoostSourceEffect(1, 1, Duration.EndOfTurn), redFilter, false)); // Whenever you cast a green spell, Tattermunge Duo gains forestwalk until end of turn. this.addAbility(new SpellCastControllerTriggeredAbility(new GainAbilitySourceEffect(new ForestwalkAbility(false), Duration.EndOfTurn), greenFilter, false)); } private TattermungeDuo(final TattermungeDuo card) { super(card); } @Override public TattermungeDuo copy() { return new TattermungeDuo(this); } }
0
0.887117
1
0.887117
game-dev
MEDIA
0.92508
game-dev
0.992707
1
0.992707
ShadowBlip/OpenGamepadUI
20,710
core/systems/input/input_icon_manager.gd
@icon("res://assets/editor-icons/tabler-icons.svg") extends Resource class_name InputIconManager ## [InputIconManager] is responsible for managing what input glyphs to show in the UI ## ## The InputIconManager will keep track of the last used input device and signal ## when the input device has changed to allow the UI to display the appropriate ## glyphs. In order for [InputIconManager] to work correctly, a [InputIconProcessor] ## must be added to the scene. signal input_type_changed(input_type: InputType) const MAPPINGS_DIR := "res://assets/gamepad/icon_mappings" const DEFAULT_MAPPING := "res://assets/gamepad/icon_mappings/xbox360.tres" enum InputType { KEYBOARD_MOUSE, GAMEPAD, } var in_game_state := load("res://assets/state/states/in_game.tres") as State var input_plumber := load("res://core/systems/input/input_plumber.tres") as InputPlumberInstance var logger := Log.get_logger("InputIconManager", Log.LEVEL.INFO) ## Disable/Enable signaling on input type changes var disabled := false ## The last detected input type var last_input_type := InputType.GAMEPAD ## The device name of the last detected input var last_input_device: String ## Mapping of device names to match to path to input icon mapping. There can be ## multiple device names that match a single icon mapping resource. ## E.g. {"Xbox 360 Controller": "res://assets/gamepad/icon_mappings/xb360.tres"} var _device_mappings := discover_device_mappings(MAPPINGS_DIR) ## Mapping of icon mapping names to the path to the mapping ## E.g. {"XBox 360": "res://assets/gamepad/icon_mappings/xb360.tres"} var _mappings := {} ## Mapping of device names to a mapping name. There can be multiple device names ## that match a single icon mapping name. ## E.g. {"Xbox 360 Wireless Controller": "XBox 360"} var _device_name_to_mapping_name := {} var _custom_input_actions := {} ## Special actions is a mapping of actions that can have fallback mappings ## if a particular icon map doesn't have certain inputs. ## TODO: Can we do this better? var _special_actions := { "ui_accept": { InputType.GAMEPAD: { "paths": ["joypad/a"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/enter"], }, }, "ogui_qb": { InputType.GAMEPAD: { "paths": ["joypad/quickaccess"], "fallback": ["joypad/guide", "joypad/a"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/ctrl", "key/f2"], }, }, "ogui_guide": { InputType.GAMEPAD: { "paths": ["joypad/guide"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/ctrl", "key/f1"], }, }, "ogui_menu": { InputType.GAMEPAD: { "paths": ["joypad/guide"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/ctrl", "key/f1"], }, }, "ogui_osk": { InputType.GAMEPAD: { "paths": ["joypad/keyboard"], "fallback": ["joypad/guide", "joypad/b"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/alt", "key/4"], }, }, "ogui_back": { InputType.GAMEPAD: { "paths": ["joypad/b"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/esc"], }, }, "ogui_east": { InputType.GAMEPAD: { "paths": ["joypad/b"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/esc"], }, }, "ogui_tab_left": { InputType.GAMEPAD: { "paths": ["joypad/lb"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/ctrl", "key/page_up"], }, }, "ogui_tab_right": { InputType.GAMEPAD: { "paths": ["joypad/rb"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/ctrl", "key/page_down"], }, }, "ogui_search": { InputType.GAMEPAD: { "paths": ["joypad/x"], }, InputType.KEYBOARD_MOUSE: { "paths": ["key/f5"], }, }, } func _init(): if Engine.is_editor_hint(): _parse_input_actions() self._mappings = discover_mappings(MAPPINGS_DIR) self._device_mappings = discover_device_mappings(MAPPINGS_DIR) # Populate mapping of device names to mapping names for mapping_name in self._mappings.keys(): var mapping_path := self._mappings[mapping_name] as String for device_name in self._device_mappings.keys(): if mapping_path != self._device_mappings[device_name]: continue self._device_name_to_mapping_name[device_name] = mapping_name # Disable when in game var on_in_game_entered := func(_from: State): self.disabled = true in_game_state.state_entered.connect(on_in_game_entered) var on_in_game_exited := func(_to: State): self.disabled = false in_game_state.state_exited.connect(on_in_game_exited) # Listen for InputPlumber device change events var on_comp_device_added := func(_device: CompositeDevice): _on_joy_connection_changed(true) input_plumber.composite_device_added.connect(on_comp_device_added) var on_comp_device_removed := func(_path: String): _on_joy_connection_changed(false) input_plumber.composite_device_removed.connect(on_comp_device_removed) # Listen for Godot joypad change events var on_godot_joy_changed := func(_device: int, connected: bool): _on_joy_connection_changed(connected) Input.joy_connection_changed.connect(on_godot_joy_changed) # Set input type to what's likely being used currently set_last_input_type(InputType.GAMEPAD) ## Discover all input icon mappings from the specified path static func discover_mappings(mappings_dir: String) -> Dictionary: var mappings := DirAccess.get_files_at(mappings_dir) var name_mappings := {} # Load all the mappings and organize them based on matching device names for filename: String in mappings: # After being exported, resources are listed with a ".remap" extension if filename.ends_with(".remap"): filename = filename.trim_suffix(".remap") var path := "/".join([MAPPINGS_DIR, filename]) var mapping := load(path) as InputIconMapping if not mapping: push_error("InputIconManager: Failed to load input icon mapping: ", path) continue name_mappings[mapping.name] = path return name_mappings ## Discover all input icon mapping devices from the specified path static func discover_device_mappings(mappings_dir: String) -> Dictionary: var mappings := DirAccess.get_files_at(mappings_dir) var device_mappings := {} # Load all the mappings and organize them based on matching device names for filename: String in mappings: # After being exported, resources are listed with a ".remap" extension if filename.ends_with(".remap"): filename = filename.trim_suffix(".remap") var path := "/".join([MAPPINGS_DIR, filename]) var mapping := load(path) as InputIconMapping if not mapping: push_error("InputIconManager: Failed to load input icon mapping: ", path) continue for dev_name: String in mapping.device_names: device_mappings[dev_name] = path return device_mappings ## Refresh all icons func refresh(): # All it takes is to signal icons to refresh paths if not self.disabled: input_type_changed.emit(last_input_type) ## Parse the given input path and return the texture(s) associated with that type of ## input. The input path can either be in the form of "joypad/south" for specific inputs, ## or the name of an event action defined in the project's input map (i.e. "ui_accept"). ## Optionally, a mapping name can be passed to get a specific icon from a specific mapping. func parse_path(path: String, mapping_name: String = "", input_type: InputType = last_input_type) -> Array[Texture]: logger.debug("Getting texture(s) for path: " + path) var paths := PackedStringArray([path]) var textures: Array[Texture] = [] # If a mapping was explicitly set, look up the icon for that mapping if mapping_name != "": logger.debug("Mapping name specified: " + mapping_name) var mapping_path := DEFAULT_MAPPING if mapping_name in self._mappings: mapping_path = self._mappings[mapping_name] as String var mapping := load(mapping_path) as InputIconMapping if not mapping: logger.warn("Failed to load input icon mapping: " + mapping_path) mapping = load(DEFAULT_MAPPING) as InputIconMapping var texture := mapping.get_texture(path) if texture == null: logger.warn("No texture for '" + path + "' found in mapping: " + mapping.name) return textures textures.push_back(texture) return textures # Determine the type of input icon texture should be returned var device_name := self.last_input_device var mapping match input_type: InputType.GAMEPAD: mapping = self.load_matching_mapping(device_name) InputType.KEYBOARD_MOUSE: mapping = load("res://assets/keyboard/icon_mappings/keyboard.tres") if not mapping: logger.warn("No mapping found for device: " + device_name) return textures # Check to see if this path is a special action with possible fallbacks if path in self._special_actions: logger.debug("Path is a special action: " + path) var data := self._special_actions[path] as Dictionary var settings := data[input_type] as Dictionary var special_paths := settings["paths"] as Array # Check that the mapping has texture(s) for this action var mapping_has_textures := !special_paths.is_empty() for special_path in special_paths: if not mapping.get_texture(special_path): mapping_has_textures = false break # If the mapping doesn't have the texture, use the fallback paths if not mapping_has_textures and "fallback" in settings: logger.debug("Unable to find texture for special action '" + path + "' in mapping: " + mapping.name + ". Using fallback.") var fallback_paths := settings["fallback"] as Array paths.clear() paths.append_array(fallback_paths) else: paths.clear() paths.append_array(special_paths) logger.debug("Converted special action to: " + str(paths)) # If the provided path is a custom input action, parse the input actions # and convert the string into an input path. (e.g. "ogui_accept" -> "joypad/a") if not path in self._special_actions and _is_path_action(path): logger.debug("Path '" + path + "' is an input action") var events := _get_matching_event(path, input_type) logger.debug("Found " + str(events.size()) + " event(s) for action '" + path + "': " + str(events)) if events.is_empty(): logger.warn("Unable to find events in input map for action: " + path) return textures paths.clear() for event: InputEvent in events: var converted_path := _convert_event_to_path(event) if converted_path.is_empty(): logger.warn("Unable to convert event " + str(event) + " into path for action: " + path) continue logger.debug("Converted input event '" + str(event) + "' to path: " + converted_path) paths.append(converted_path) # Loop through all of the input paths (i.e. ["key/ctrl", "key/f1"]) and # get the corresponding texture based on the last detected device. for input_path in paths: var texture := mapping.get_texture(input_path) as Texture if not texture: logger.warn("No texture for '" + input_path + "' found in mapping: " + mapping.name) continue textures.push_back(texture) return textures ## Load and return the mapping that matches the given device. func load_matching_mapping(device_name: String) -> InputIconMapping: # First try to do an exact match #logger.debug("Devices with mappings: " + str(self._device_mappings)) if device_name in self._device_mappings: var mapping_path := self._device_mappings[device_name] as String var mapping := load(mapping_path) as InputIconMapping return mapping # Next, try to do a substring match for pattern: String in self._device_mappings.keys(): if not pattern in device_name: continue var mapping_path := self._device_mappings[pattern] as String var mapping := load(mapping_path) as InputIconMapping return mapping # Last resort, fallback to default icon mapping logger.warn("No input icon mapping found for device: " + device_name) var mapping_path := DEFAULT_MAPPING var mapping := load(mapping_path) as InputIconMapping return mapping ## Returns the mapping name for the given device name. The mapping name is the ## "name" property of an [InputIconMapping]. func get_mapping_name_from_device(device_name: String) -> String: # First try to do an exact match #logger.debug("Devices with mappings: " + str(self._device_mappings)) if device_name in self._device_name_to_mapping_name: return self._device_name_to_mapping_name[device_name] as String # Next, try to do a substring match for pattern: String in self._device_name_to_mapping_name.keys(): if not pattern in device_name: continue return self._device_name_to_mapping_name[pattern] as String return "" ## Returns the Godot event(s) defined in the input map with the given name and ## match the given input type func _get_matching_event(path: String, input_type: InputType) -> Array[InputEvent]: var events: Array[InputEvent] = [] var matching_events: Array[InputEvent] = [] if _custom_input_actions.has(path): events = _custom_input_actions[path] else: events = InputMap.action_get_events(path) # Check if any of the events have key modifiers var mod_events: Array[InputEvent] = [] for event: InputEvent in events: if not event is InputEventKey: continue var key := event as InputEventKey if key.alt_pressed: var mod := InputEventKey.new() mod.keycode = KEY_ALT mod_events.append(mod) if key.meta_pressed: var mod := InputEventKey.new() mod.keycode = KEY_META mod_events.append(mod) if key.shift_pressed: var mod := InputEventKey.new() mod.keycode = KEY_SHIFT mod_events.append(mod) if key.ctrl_pressed: var mod := InputEventKey.new() mod.keycode = KEY_CTRL mod_events.append(mod) mod_events.append_array(events) events = mod_events for event: InputEvent in events: match event.get_class(): "InputEventKey", "InputEventMouse", "InputEventMouseMotion", "InputEventMouseButton": if input_type == InputType.KEYBOARD_MOUSE: matching_events.append(event) "InputEventJoypadButton", "InputEventJoypadMotion": if input_type == InputType.GAMEPAD: matching_events.append(event) return matching_events ## Set the last input type to the given value and emit a signal func set_last_input_type(_last_input_type: InputType): last_input_type = _last_input_type ## Signal whenever a gamepad is connected/disconnected func _on_joy_connection_changed(connected: bool) -> void: if connected: set_last_input_type(InputType.GAMEPAD) else: set_last_input_type(InputType.KEYBOARD_MOUSE) func _parse_input_actions(): # A script running at editor ("tool") level only has # the default mappings. The way to get around this is # manually parsing the project file and adding the # new input actions to lookup. var proj_file := ConfigFile.new() if proj_file.load("res://project.godot"): printerr( 'Failed to open "project.godot"! Custom input actions will not work on editor view!' ) return if proj_file.has_section("input"): for input_action in proj_file.get_section_keys("input"): var data: Dictionary = proj_file.get_value("input", input_action) _add_custom_input_action(input_action, data) func _is_path_action(path: String) -> bool: return _custom_input_actions.has(path) or InputMap.has_action(path) func _add_custom_input_action(input_action: String, data: Dictionary): _custom_input_actions[input_action] = data["events"] ## Convert the given Godot input event into an input icon path ## (e.g. "joypad/south", "key/a", etc.) func _convert_event_to_path(event: InputEvent) -> String: if event is InputEventKey: # If this is a physical key, convert to localized scancode if event.keycode == 0: return _convert_key_to_path( DisplayServer.keyboard_get_keycode_from_physical(event.physical_keycode) ) return _convert_key_to_path(event.keycode) elif event is InputEventMouseButton: return _convert_mouse_button_to_path(event.button_index) elif event is InputEventJoypadButton: return _convert_joypad_button_to_path(event.button_index) elif event is InputEventJoypadMotion: return _convert_joypad_motion_to_path(event.axis) return "" func _convert_key_to_path(scancode: int) -> String: match scancode: KEY_ESCAPE: return "key/esc" KEY_TAB: return "key/tab" KEY_BACKSPACE: return "key/backspace_alt" KEY_ENTER: return "key/enter_alt" KEY_KP_ENTER: return "key/enter_tall" KEY_INSERT: return "key/insert" KEY_DELETE: return "key/del" KEY_PRINT: return "key/print_screen" KEY_HOME: return "key/home" KEY_END: return "key/end" KEY_LEFT: return "key/arrow_left" KEY_UP: return "key/arrow_up" KEY_RIGHT: return "key/arrow_right" KEY_DOWN: return "key/arrow_down" KEY_PAGEUP: return "key/page_up" KEY_PAGEDOWN: return "key/page_down" KEY_SHIFT: return "key/shift_alt" KEY_CTRL: return "key/ctrl" KEY_META: match OS.get_name(): "OSX": return "key/command" _: return "key/meta" KEY_ALT: return "key/alt" KEY_CAPSLOCK: return "key/caps_lock" KEY_NUMLOCK: return "key/num_lock" KEY_F1: return "key/f1" KEY_F2: return "key/f2" KEY_F3: return "key/f3" KEY_F4: return "key/f4" KEY_F5: return "key/f5" KEY_F6: return "key/f6" KEY_F7: return "key/f7" KEY_F8: return "key/f8" KEY_F9: return "key/f9" KEY_F10: return "key/f10" KEY_F11: return "key/f11" KEY_F12: return "key/f12" KEY_KP_MULTIPLY, KEY_ASTERISK: return "key/asterisk" KEY_KP_SUBTRACT, KEY_MINUS: return "key/minus" KEY_KP_ADD: return "key/plus_tall" KEY_KP_0: return "key/0" KEY_KP_1: return "key/1" KEY_KP_2: return "key/2" KEY_KP_3: return "key/3" KEY_KP_4: return "key/4" KEY_KP_5: return "key/5" KEY_KP_6: return "key/6" KEY_KP_7: return "key/7" KEY_KP_8: return "key/8" KEY_KP_9: return "key/9" KEY_UNKNOWN: return "" KEY_SPACE: return "key/space" KEY_QUOTEDBL: return "key/quote" KEY_PLUS: return "key/plus" KEY_0: return "key/0" KEY_1: return "key/1" KEY_2: return "key/2" KEY_3: return "key/3" KEY_4: return "key/4" KEY_5: return "key/5" KEY_6: return "key/6" KEY_7: return "key/7" KEY_8: return "key/8" KEY_9: return "key/9" KEY_SEMICOLON: return "key/semicolon" KEY_LESS: return "key/mark_left" KEY_GREATER: return "key/mark_right" KEY_QUESTION: return "key/question" KEY_A: return "key/a" KEY_B: return "key/b" KEY_C: return "key/c" KEY_D: return "key/d" KEY_E: return "key/e" KEY_F: return "key/f" KEY_G: return "key/g" KEY_H: return "key/h" KEY_I: return "key/i" KEY_J: return "key/j" KEY_K: return "key/k" KEY_L: return "key/l" KEY_M: return "key/m" KEY_N: return "key/n" KEY_O: return "key/o" KEY_P: return "key/p" KEY_Q: return "key/q" KEY_R: return "key/r" KEY_S: return "key/s" KEY_T: return "key/t" KEY_U: return "key/u" KEY_V: return "key/v" KEY_W: return "key/w" KEY_X: return "key/x" KEY_Y: return "key/y" KEY_Z: return "key/z" KEY_BRACKETLEFT: return "key/bracket_left" KEY_BACKSLASH: return "key/slash" KEY_BRACKETRIGHT: return "key/bracket_right" KEY_ASCIITILDE: return "key/tilda" _: return "" func _convert_mouse_button_to_path(button_index: int) -> String: match button_index: MOUSE_BUTTON_LEFT: return "mouse/left" MOUSE_BUTTON_RIGHT: return "mouse/right" MOUSE_BUTTON_MIDDLE: return "mouse/middle" _: return "mouse/sample" func _convert_joypad_button_to_path(button_index: int) -> String: var path: String match button_index: JOY_BUTTON_A: path = "joypad/a" JOY_BUTTON_B: path = "joypad/b" JOY_BUTTON_X: path = "joypad/x" JOY_BUTTON_Y: path = "joypad/y" JOY_BUTTON_LEFT_SHOULDER: path = "joypad/lb" JOY_BUTTON_RIGHT_SHOULDER: path = "joypad/rb" JOY_AXIS_TRIGGER_LEFT: path = "joypad/lt" JOY_AXIS_TRIGGER_RIGHT: path = "joypad/rt" JOY_BUTTON_LEFT_STICK: path = "joypad/l_stick_click" JOY_BUTTON_RIGHT_STICK: path = "joypad/r_stick_click" JOY_BUTTON_BACK: path = "joypad/select" JOY_BUTTON_START: path = "joypad/start" JOY_BUTTON_DPAD_UP: path = "joypad/dpad_up" JOY_BUTTON_DPAD_DOWN: path = "joypad/dpad_down" JOY_BUTTON_DPAD_LEFT: path = "joypad/dpad_left" JOY_BUTTON_DPAD_RIGHT: path = "joypad/dpad_right" JOY_BUTTON_GUIDE: path = "joypad/home" JOY_BUTTON_MISC1: path = "joypad/share" _: return "" return path func _convert_joypad_motion_to_path(axis: int) -> String: var path: String match axis: JOY_AXIS_LEFT_X, JOY_AXIS_LEFT_Y: path = "joypad/l_stick" JOY_AXIS_RIGHT_X, JOY_AXIS_RIGHT_Y: path = "joypad/r_stick" JOY_AXIS_TRIGGER_LEFT: path = "joypad/lt" JOY_AXIS_TRIGGER_RIGHT: path = "joypad/rt" _: return "" return path
0
0.88869
1
0.88869
game-dev
MEDIA
0.776186
game-dev
0.801449
1
0.801449
scanberg/viamd
106,279
ext/ImGuiColorTextEdit/TextEditor.cpp
#include <algorithm> #include <chrono> #include <string> //#include <regex> #include <cmath> #include <climits> #include "TextEditor.h" #define IMGUI_DEFINE_MATH_OPERATORS #include <imgui.h> // for imGui::GetCurrentWindow() // TODO // - multiline comments vs single-line: latter is blocking start of a ML template<class InputIt1, class InputIt2, class BinaryPredicate> bool equals(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, BinaryPredicate p) { for (; first1 != last1 && first2 != last2; ++first1, ++first2) { if (!p(*first1, *first2)) return false; } return first1 == last1 && first2 == last2; } TextEditor::TextEditor() : mLineSpacing(1.0f) , mUndoIndex(0) , mTabSize(4) , mOverwrite(false) , mReadOnly(false) , mWithinRender(false) , mFocused(false) , mScrollToCursor(false) , mScrollToTop(false) , mTextChanged(false) , mColorizerEnabled(true) , mTextStart(20.0f) , mLeftMargin(10) , mCursorPositionChanged(false) , mColorRangeMin(0) , mColorRangeMax(0) , mSelectionMode(SelectionMode::Normal) , mHandleKeyboardInputs(true) , mHandleMouseInputs(true) , mIgnoreImGuiChild(false) , mShowWhitespaces(true) , mShowShortTabGlyphs(false) , mCheckComments(true) , mBreakpoints() , mMarkers() , mHoveredMarker(NULL) , mErrorMarkers() , mStartTime(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()) , mLastClick(-1.0f) { SetPalette(GetDarkPalette()); SetLanguageDefinition(LanguageDefinition::VIAMD()); mLines.push_back(Line()); } TextEditor::~TextEditor() { } void TextEditor::SetLanguageDefinition(const LanguageDefinition & aLanguageDef) { mLanguageDefinition = aLanguageDef; /* mRegexList.clear(); for (auto& r : mLanguageDefinition.mTokenRegexStrings) mRegexList.push_back(std::make_pair(std::regex(r.first, std::regex_constants::optimize), r.second)); */ Colorize(); } void TextEditor::SetPalette(const Palette & aValue) { mPaletteBase = aValue; } std::string TextEditor::GetText(const Coordinates & aStart, const Coordinates & aEnd) const { std::string result; auto lstart = aStart.mLine; auto lend = aEnd.mLine; auto istart = GetCharacterIndex(aStart); auto iend = GetCharacterIndex(aEnd); size_t s = 0; for (int i = lstart; i < lend; i++) s += mLines[i].size(); result.reserve(s + s / 8); while (istart < iend || lstart < lend) { if (lstart >= (int)mLines.size()) break; auto& line = mLines[lstart]; if (istart < (int)line.size()) { result += line[istart].mChar; istart++; } else { istart = 0; ++lstart; result += '\n'; } } return result; } TextEditor::Coordinates TextEditor::GetActualCursorCoordinates() const { return SanitizeCoordinates(mState.mCursorPosition); } TextEditor::Coordinates TextEditor::SanitizeCoordinates(const Coordinates & aValue) const { auto line = aValue.mLine; auto column = aValue.mColumn; if (line >= (int)mLines.size()) { if (mLines.empty()) { line = 0; column = 0; } else { line = (int)mLines.size() - 1; column = GetLineMaxColumn(line); } return Coordinates(line, column); } else { column = mLines.empty() ? 0 : std::min(column, GetLineMaxColumn(line)); return Coordinates(line, column); } } // https://en.wikipedia.org/wiki/UTF-8 // We assume that the char is a standalone character (<128) or a leading byte of an UTF-8 code sequence (non-10xxxxxx code) static int UTF8CharLength(TextEditor::Char c) { if ((c & 0xFE) == 0xFC) return 6; if ((c & 0xFC) == 0xF8) return 5; if ((c & 0xF8) == 0xF0) return 4; else if ((c & 0xF0) == 0xE0) return 3; else if ((c & 0xE0) == 0xC0) return 2; return 1; } // "Borrowed" from ImGui source static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { if (c < 0x80) { buf[0] = (char)c; return 1; } if (c < 0x800) { if (buf_size < 2) return 0; buf[0] = (char)(0xc0 + (c >> 6)); buf[1] = (char)(0x80 + (c & 0x3f)); return 2; } if (c >= 0xdc00 && c < 0xe000) { return 0; } if (c >= 0xd800 && c < 0xdc00) { if (buf_size < 4) return 0; buf[0] = (char)(0xf0 + (c >> 18)); buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[3] = (char)(0x80 + ((c) & 0x3f)); return 4; } //else if (c < 0x10000) { if (buf_size < 3) return 0; buf[0] = (char)(0xe0 + (c >> 12)); buf[1] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[2] = (char)(0x80 + ((c) & 0x3f)); return 3; } } void TextEditor::Advance(Coordinates & aCoordinates) const { if (aCoordinates.mLine < (int)mLines.size()) { auto& line = mLines[aCoordinates.mLine]; auto cindex = GetCharacterIndex(aCoordinates); if (cindex + 1 < (int)line.size()) { auto delta = UTF8CharLength(line[cindex].mChar); cindex = std::min(cindex + delta, (int)line.size() - 1); } else { ++aCoordinates.mLine; cindex = 0; } aCoordinates.mColumn = GetCharacterColumn(aCoordinates.mLine, cindex); } } void TextEditor::DeleteRange(const Coordinates & aStart, const Coordinates & aEnd) { assert(aEnd >= aStart); assert(!mReadOnly); //printf("D(%d.%d)-(%d.%d)\n", aStart.mLine, aStart.mColumn, aEnd.mLine, aEnd.mColumn); if (aEnd == aStart) return; auto start = GetCharacterIndex(aStart); auto end = GetCharacterIndex(aEnd); if (aStart.mLine == aEnd.mLine) { auto& line = mLines[aStart.mLine]; auto n = GetLineMaxColumn(aStart.mLine); if (aEnd.mColumn >= n) line.erase(line.begin() + start, line.end()); else line.erase(line.begin() + start, line.begin() + end); } else { auto& firstLine = mLines[aStart.mLine]; auto& lastLine = mLines[aEnd.mLine]; firstLine.erase(firstLine.begin() + start, firstLine.end()); lastLine.erase(lastLine.begin(), lastLine.begin() + end); if (aStart.mLine < aEnd.mLine) firstLine.insert(firstLine.end(), lastLine.begin(), lastLine.end()); if (aStart.mLine < aEnd.mLine) RemoveLine(aStart.mLine + 1, aEnd.mLine + 1); } mTextChanged = true; } int TextEditor::InsertTextAt(Coordinates& /* inout */ aWhere, const char * aValue) { assert(!mReadOnly); int cindex = GetCharacterIndex(aWhere); int totalLines = 0; while (*aValue != '\0') { assert(!mLines.empty()); if (*aValue == '\r') { // skip ++aValue; } else if (*aValue == '\n') { if (cindex < (int)mLines[aWhere.mLine].size()) { auto& newLine = InsertLine(aWhere.mLine + 1); auto& line = mLines[aWhere.mLine]; newLine.insert(newLine.begin(), line.begin() + cindex, line.end()); line.erase(line.begin() + cindex, line.end()); } else { InsertLine(aWhere.mLine + 1); } ++aWhere.mLine; aWhere.mColumn = 0; cindex = 0; ++totalLines; ++aValue; } else { auto& line = mLines[aWhere.mLine]; auto d = UTF8CharLength(*aValue); while (d-- > 0 && *aValue != '\0') line.insert(line.begin() + cindex++, Glyph(*aValue++, PaletteIndex::Default)); aWhere.mColumn = GetCharacterColumn(aWhere.mLine, cindex); } mTextChanged = true; } return totalLines; } void TextEditor::AddUndo(UndoRecord& aValue) { assert(!mReadOnly); //printf("AddUndo: (@%d.%d) +\'%s' [%d.%d .. %d.%d], -\'%s', [%d.%d .. %d.%d] (@%d.%d)\n", // aValue.mBefore.mCursorPosition.mLine, aValue.mBefore.mCursorPosition.mColumn, // aValue.mAdded.c_str(), aValue.mAddedStart.mLine, aValue.mAddedStart.mColumn, aValue.mAddedEnd.mLine, aValue.mAddedEnd.mColumn, // aValue.mRemoved.c_str(), aValue.mRemovedStart.mLine, aValue.mRemovedStart.mColumn, aValue.mRemovedEnd.mLine, aValue.mRemovedEnd.mColumn, // aValue.mAfter.mCursorPosition.mLine, aValue.mAfter.mCursorPosition.mColumn // ); mUndoBuffer.resize((size_t)(mUndoIndex + 1)); mUndoBuffer.back() = aValue; ++mUndoIndex; } TextEditor::Coordinates TextEditor::ScreenPosToCoordinates(const ImVec2& aPosition, bool aInsertionMode) const { ImVec2 origin = ImGui::GetCursorScreenPos(); ImVec2 local(aPosition.x - origin.x + 3.0f, aPosition.y - origin.y); float spaceSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, " ").x; int lineNo = (int)floor(local.y / mCharAdvance.y); int columnCoord = 0; if (lineNo >= 0 && lineNo < (int)mLines.size()) { auto& line = mLines.at(lineNo); int columnIndex = 0; //std::string cumulatedString = ""; float columnWidth = 0.0f; float columnX = 0.0f; int delta = 0; // First we find the hovered column coord. while (mTextStart + columnX - (aInsertionMode ? 0.5f : 0.0f) * columnWidth < local.x && (size_t)columnIndex < line.size()) { columnCoord += delta; if (line[columnIndex].mChar == '\t') { float oldX = columnX; columnX = (1.0f + std::floor((1.0f + columnX) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize); columnWidth = columnX - oldX; delta = columnCoord - (columnCoord / mTabSize) * mTabSize + mTabSize; } else { char buf[7]; auto d = UTF8CharLength(line[columnIndex].mChar); int i = 0; while (i < 6 && d-- > 0) buf[i++] = line[columnIndex].mChar; buf[i] = '\0'; columnWidth = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf).x; columnX += columnWidth; delta = 1; } ++columnIndex; } // Then we reduce by 1 column coord if cursor is on the left side of the hovered column. //if (aInsertionMode && mTextStart + columnX - columnWidth * 2.0f < local.x) // columnIndex = std::min((int)line.size() - 1, columnIndex + 1); if (columnIndex == (int)line.size()) columnCoord += 1; } return Coordinates(lineNo, columnCoord); } TextEditor::Coordinates TextEditor::FindWordStart(const Coordinates & aFrom) const { Coordinates at = aFrom; if (at.mLine >= (int)mLines.size()) return at; auto& line = mLines[at.mLine]; auto cindex = GetCharacterIndex(at); if (cindex >= (int)line.size()) return at; while (cindex > 0 && isspace(line[cindex].mChar)) --cindex; auto cstart = (PaletteIndex)line[cindex].mColorIndex; while (cindex > 0) { auto c = line[cindex].mChar; if ((c & 0xC0) != 0x80) // not UTF code sequence 10xxxxxx { if (c <= 32 && isspace(c)) { cindex++; break; } if (cstart != (PaletteIndex)line[size_t(cindex - 1)].mColorIndex) break; } --cindex; } return Coordinates(at.mLine, GetCharacterColumn(at.mLine, cindex)); } TextEditor::Coordinates TextEditor::FindWordEnd(const Coordinates & aFrom) const { Coordinates at = aFrom; if (at.mLine >= (int)mLines.size()) return at; auto& line = mLines[at.mLine]; auto cindex = GetCharacterIndex(at); if (cindex >= (int)line.size()) return at; bool prevspace = (bool)!!isspace(line[cindex].mChar); auto cstart = (PaletteIndex)line[cindex].mColorIndex; while (cindex < (int)line.size()) { auto c = line[cindex].mChar; auto d = UTF8CharLength(c); if (cstart != (PaletteIndex)line[cindex].mColorIndex) break; if (prevspace != !!isspace(c)) { if (isspace(c)) while (cindex < (int)line.size() && isspace(line[cindex].mChar)) ++cindex; break; } cindex += d; } return Coordinates(aFrom.mLine, GetCharacterColumn(aFrom.mLine, cindex)); } TextEditor::Coordinates TextEditor::FindNextWord(const Coordinates & aFrom) const { Coordinates at = aFrom; if (at.mLine >= (int)mLines.size()) return at; // skip to the next non-word character auto cindex = GetCharacterIndex(aFrom); bool isword = false; bool skip = false; if (cindex < (int)mLines[at.mLine].size()) { auto& line = mLines[at.mLine]; isword = !!isalnum(line[cindex].mChar); skip = isword; } while (!isword || skip) { if (at.mLine >= (int)mLines.size()) { auto l = std::max(0, (int) mLines.size() - 1); return Coordinates(l, GetLineMaxColumn(l)); } auto& line = mLines[at.mLine]; if (cindex < (int)line.size()) { isword = isalnum(line[cindex].mChar); if (isword && !skip) return Coordinates(at.mLine, GetCharacterColumn(at.mLine, cindex)); if (!isword) skip = false; cindex++; } else { cindex = 0; ++at.mLine; skip = false; isword = false; } } return at; } TextEditor::Coordinates TextEditor::GetCharacterCoordinates(int aIndex) const { int line_beg = 0; for (int line = 0; line < (int)mLines.size(); ++line) { int line_end = line_beg + (int)mLines[line].size(); //if (!mLines[line].empty()) { if (line_beg <= aIndex && aIndex <= line_end) return Coordinates(line, GetCharacterColumn(line, aIndex - line_beg)); //} line_beg = line_end + 1; } return {}; } int TextEditor::GetCharacterIndex(const Coordinates& aCoordinates) const { if (aCoordinates.mLine >= (int)mLines.size()) return -1; auto& line = mLines[aCoordinates.mLine]; int c = 0; int i = 0; for (; i < (int)line.size() && c < aCoordinates.mColumn;) { if (line[i].mChar == '\t') c = (c / mTabSize) * mTabSize + mTabSize; else ++c; i += UTF8CharLength(line[i].mChar); } return i; } int TextEditor::GetCharacterColumn(int aLine, int aIndex) const { if (aLine >= (int)mLines.size()) return 0; auto& line = mLines[aLine]; int col = 0; int i = 0; while (i < aIndex && i < (int)line.size()) { auto c = line[i].mChar; i += UTF8CharLength(c); if (c == '\t') col = (col / mTabSize) * mTabSize + mTabSize; else col++; } return col; } int TextEditor::GetLineCharacterCount(int aLine) const { if (aLine >= (int)mLines.size()) return 0; auto& line = mLines[aLine]; int c = 0; for (unsigned i = 0; i < line.size(); c++) i += UTF8CharLength(line[i].mChar); return c; } int TextEditor::GetLineMaxColumn(int aLine) const { if (aLine >= (int)mLines.size()) return 0; auto& line = mLines[aLine]; int col = 0; for (unsigned i = 0; i < line.size(); ) { auto c = line[i].mChar; if (c == '\t') col = (col / mTabSize) * mTabSize + mTabSize; else col++; i += UTF8CharLength(c); } return col; } bool TextEditor::IsOnWordBoundary(const Coordinates & aAt) const { if (aAt.mLine >= (int)mLines.size() || aAt.mColumn == 0) return true; auto& line = mLines[aAt.mLine]; auto cindex = GetCharacterIndex(aAt); if (cindex >= (int)line.size()) return true; if (mColorizerEnabled) return line[cindex].mColorIndex != line[size_t(cindex - 1)].mColorIndex; return isspace(line[cindex].mChar) != isspace(line[cindex - 1].mChar); } void TextEditor::RemoveLine(int aStart, int aEnd) { assert(!mReadOnly); assert(aEnd >= aStart); assert(mLines.size() > (size_t)(aEnd - aStart)); ErrorMarkers etmp; for (auto& i : mErrorMarkers) { ErrorMarkers::value_type e(i.first >= aStart ? i.first - 1 : i.first, i.second); if (e.first >= aStart && e.first <= aEnd) continue; etmp.insert(e); } mErrorMarkers = std::move(etmp); Breakpoints btmp; for (auto i : mBreakpoints) { if (i >= aStart && i <= aEnd) continue; btmp.insert(i >= aStart ? i - 1 : i); } mBreakpoints = std::move(btmp); mLines.erase(mLines.begin() + aStart, mLines.begin() + aEnd); assert(!mLines.empty()); mTextChanged = true; } void TextEditor::RemoveLine(int aIndex) { assert(!mReadOnly); assert(mLines.size() > 1); ErrorMarkers etmp; for (auto& i : mErrorMarkers) { ErrorMarkers::value_type e(i.first > aIndex ? i.first - 1 : i.first, i.second); if (e.first - 1 == aIndex) continue; etmp.insert(e); } mErrorMarkers = std::move(etmp); Breakpoints btmp; for (auto i : mBreakpoints) { if (i == aIndex) continue; btmp.insert(i >= aIndex ? i - 1 : i); } mBreakpoints = std::move(btmp); mLines.erase(mLines.begin() + aIndex); assert(!mLines.empty()); mTextChanged = true; } TextEditor::Line& TextEditor::InsertLine(int aIndex) { assert(!mReadOnly); auto& result = *mLines.insert(mLines.begin() + aIndex, Line()); ErrorMarkers etmp; for (auto& i : mErrorMarkers) etmp.insert(ErrorMarkers::value_type(i.first >= aIndex ? i.first + 1 : i.first, i.second)); mErrorMarkers = std::move(etmp); Breakpoints btmp; for (auto i : mBreakpoints) btmp.insert(i >= aIndex ? i + 1 : i); mBreakpoints = std::move(btmp); return result; } std::string TextEditor::GetWordUnderCursor() const { auto c = GetCursorPosition(); return GetWordAt(c); } std::string TextEditor::GetWordAt(const Coordinates & aCoords) const { auto start = FindWordStart(aCoords); auto end = FindWordEnd(aCoords); std::string r; auto istart = GetCharacterIndex(start); auto iend = GetCharacterIndex(end); for (auto it = istart; it < iend; ++it) r.push_back(mLines[aCoords.mLine][it].mChar); return r; } ImU32 TextEditor::GetGlyphColor(const Glyph & aGlyph) const { if (!mColorizerEnabled) return mPalette[(int)PaletteIndex::Default]; if (aGlyph.mComment) return mPalette[(int)PaletteIndex::Comment]; if (aGlyph.mMultiLineComment) return mPalette[(int)PaletteIndex::MultiLineComment]; auto const color = mPalette[(int)aGlyph.mColorIndex]; if (aGlyph.mPreprocessor) { const auto ppcolor = mPalette[(int)PaletteIndex::Preprocessor]; const int c0 = ((ppcolor & 0xff) + (color & 0xff)) / 2; const int c1 = (((ppcolor >> 8) & 0xff) + ((color >> 8) & 0xff)) / 2; const int c2 = (((ppcolor >> 16) & 0xff) + ((color >> 16) & 0xff)) / 2; const int c3 = (((ppcolor >> 24) & 0xff) + ((color >> 24) & 0xff)) / 2; return ImU32(c0 | (c1 << 8) | (c2 << 16) | (c3 << 24)); } return color; } void TextEditor::HandleKeyboardInputs() { if (ImGui::IsWindowFocused()) { if (ImGui::IsWindowHovered()) ImGui::SetMouseCursor(ImGuiMouseCursor_TextInput); //ImGui::CaptureKeyboardFromApp(true); ImGuiIO& io = ImGui::GetIO(); auto isOSX = io.ConfigMacOSXBehaviors; //auto alt = ImGui::IsKeyDown(ImGuiMod_Alt); //auto ctrl = ImGui::IsKeyDown(ImGuiMod_Ctrl);// && !alt; // @NOTE(Robin): There seems to be some wierd behaviour in recent imgui versions where the Right alt key (AltGr) is mapped to Ctrl && Alt auto alt = ImGui::IsKeyDown(ImGuiKey_LeftAlt) || ImGui::IsKeyDown(ImGuiKey_RightAlt); auto ctrl = ImGui::IsKeyDown(ImGuiKey_LeftCtrl) || ImGui::IsKeyDown(ImGuiKey_RightCtrl); auto shift = ImGui::IsKeyDown(ImGuiMod_Shift); auto super = ImGui::IsKeyDown(ImGuiMod_Super); auto isShortcut = (isOSX ? (super && !ctrl) : (ctrl && !super)) && !alt && !shift; auto isShiftShortcut = (isOSX ? (super && !ctrl) : (ctrl && !super)) && shift && !alt; auto isWordmoveKey = isOSX ? alt : ctrl; auto isAltOnly = alt && !ctrl && !shift && !super; auto isCtrlOnly = ctrl && !alt && !shift && !super; auto isShiftOnly = shift && !alt && !ctrl && !super; io.WantCaptureKeyboard = true; io.WantTextInput = true; if (!IsReadOnly() && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z)) Undo(); else if (!IsReadOnly() && isAltOnly && ImGui::IsKeyPressed(ImGuiKey_Backspace)) Undo(); else if (!IsReadOnly() && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Y)) Redo(); else if (!IsReadOnly() && isShiftShortcut && ImGui::IsKeyPressed(ImGuiKey_Z)) Redo(); else if (!alt && !ctrl && !super && ImGui::IsKeyPressed(ImGuiKey_UpArrow)) MoveUp(1, shift); else if (!alt && !ctrl && !super && ImGui::IsKeyPressed(ImGuiKey_DownArrow)) MoveDown(1, shift); else if ((isOSX ? !ctrl : !alt) && !super && ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) MoveLeft(1, shift, isWordmoveKey); else if ((isOSX ? !ctrl : !alt) && !super && ImGui::IsKeyPressed(ImGuiKey_RightArrow)) MoveRight(1, shift, isWordmoveKey); else if (!alt && !ctrl && !super && ImGui::IsKeyPressed(ImGuiKey_PageUp)) MoveUp(GetPageSize() - 4, shift); else if (!alt && !ctrl && !super && ImGui::IsKeyPressed(ImGuiKey_PageDown)) MoveDown(GetPageSize() - 4, shift); else if (ctrl && !alt && !super && ImGui::IsKeyPressed(ImGuiKey_Home)) MoveTop(shift); else if (ctrl && !alt && !super && ImGui::IsKeyPressed(ImGuiKey_End)) MoveBottom(shift); else if (!alt && !ctrl && !super && ImGui::IsKeyPressed(ImGuiKey_Home)) MoveHome(shift); else if (!alt && !ctrl && !super && ImGui::IsKeyPressed(ImGuiKey_End)) MoveEnd(shift); else if (!IsReadOnly() && !alt && !ctrl && !shift && !super && ImGui::IsKeyPressed(ImGuiKey_Delete)) Delete(); else if (!IsReadOnly() && !alt && !ctrl && !shift && !super && ImGui::IsKeyPressed(ImGuiKey_Backspace)) Backspace(); else if (!alt && !ctrl && !shift && !super && ImGui::IsKeyPressed(ImGuiKey_Insert)) mOverwrite ^= true; else if (isCtrlOnly && ImGui::IsKeyPressed(ImGuiKey_Insert)) Copy(); else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_C)) Copy(); else if (!IsReadOnly() && isShiftOnly && ImGui::IsKeyPressed(ImGuiKey_Insert)) Paste(); else if (!IsReadOnly() && isShortcut && ImGui::IsKeyPressed(ImGuiKey_V)) Paste(); else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_X)) Cut(); else if (isShiftOnly && ImGui::IsKeyPressed(ImGuiKey_Delete)) Cut(); else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_A)) SelectAll(); else if (!IsReadOnly() && !alt && !ctrl && !shift && !super && ImGui::IsKeyPressed(ImGuiKey_Enter)) EnterCharacter('\n', false); else if (!IsReadOnly() && !alt && !ctrl && !super && ImGui::IsKeyPressed(ImGuiKey_Tab)) InsertText(" "); if (!IsReadOnly() && !io.InputQueueCharacters.empty() && !ctrl && !super) { for (int i = 0; i < io.InputQueueCharacters.Size; i++) { auto c = io.InputQueueCharacters[i]; if (c != 0 && (c == '\n' || c >= 32)) EnterCharacter(c, shift); } io.InputQueueCharacters.resize(0); } } } void TextEditor::HandleMouseInputs() { ImGuiIO& io = ImGui::GetIO(); auto shift = io.KeyShift; auto ctrl = io.ConfigMacOSXBehaviors ? io.KeySuper : io.KeyCtrl; auto alt = io.ConfigMacOSXBehaviors ? io.KeyCtrl : io.KeyAlt; mState.mMouseCursorPosition = ScreenPosToCoordinates(ImGui::GetMousePos()); if (ImGui::IsWindowHovered()) { if (!shift && !alt) { auto click = ImGui::IsMouseClicked(0); auto doubleClick = ImGui::IsMouseDoubleClicked(0); auto t = ImGui::GetTime(); auto tripleClick = click && !doubleClick && (mLastClick != -1.0f && (t - mLastClick) < io.MouseDoubleClickTime); /* Left mouse button triple click */ if (tripleClick) { if (!ctrl) { mState.mCursorPosition = mInteractiveStart = mInteractiveEnd = SanitizeCoordinates(ScreenPosToCoordinates(ImGui::GetMousePos())); mSelectionMode = SelectionMode::Line; SetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode); } mLastClick = -1.0f; } /* Left mouse button double click */ else if (doubleClick) { if (!ctrl) { mState.mCursorPosition = mInteractiveStart = mInteractiveEnd = SanitizeCoordinates(ScreenPosToCoordinates(ImGui::GetMousePos())); if (mSelectionMode == SelectionMode::Line) mSelectionMode = SelectionMode::Normal; else mSelectionMode = SelectionMode::Word; SetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode); } mLastClick = (float)ImGui::GetTime(); } /* Left mouse button click */ else if (click) { mState.mCursorPosition = mInteractiveStart = mInteractiveEnd = SanitizeCoordinates(ScreenPosToCoordinates(ImGui::GetMousePos(), !mOverwrite)); if (ctrl) mSelectionMode = SelectionMode::Word; else mSelectionMode = SelectionMode::Normal; SetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode); mLastClick = (float)ImGui::GetTime(); } // Mouse left button dragging (=> update selection) else if (ImGui::IsMouseDragging(0) && ImGui::IsMouseDown(0)) { io.WantCaptureMouse = true; mState.mCursorPosition = mInteractiveEnd = SanitizeCoordinates(ScreenPosToCoordinates(ImGui::GetMousePos(), !mOverwrite)); SetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode); } } } } void TextEditor::Render() { /* Compute mCharAdvance regarding to scaled font size (Ctrl + mouse wheel)*/ const float fontSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, "#", nullptr, nullptr).x; mCharAdvance = ImVec2(fontSize, ImGui::GetTextLineHeightWithSpacing() * mLineSpacing); /* Update palette with the current alpha from style */ for (int i = 0; i < (int)PaletteIndex::Max; ++i) { auto color = ImGui::ColorConvertU32ToFloat4(mPaletteBase[i]); color.w *= ImGui::GetStyle().Alpha; mPalette[i] = ImGui::ColorConvertFloat4ToU32(color); } assert(mLineBuffer.empty()); auto contentSize = ImGui::GetWindowContentRegionMax(); auto drawList = ImGui::GetWindowDrawList(); float longest(mTextStart); if (mScrollToTop) { mScrollToTop = false; ImGui::SetScrollY(0.f); } ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos(); auto scrollX = ImGui::GetScrollX(); auto scrollY = ImGui::GetScrollY(); auto lineNo = (int)floor(scrollY / mCharAdvance.y); auto globalLineMax = (int)mLines.size(); auto lineMax = std::max(0, std::min((int)mLines.size() - 1, lineNo + (int)floor((scrollY + contentSize.y) / mCharAdvance.y))); // Deduce mTextStart by evaluating mLines size (global lineMax) plus two spaces as text width char buf[16]; snprintf(buf, 16, " %d ", globalLineMax); mTextStart = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf, nullptr, nullptr).x + mLeftMargin; mHoveredMarker = NULL; ImVec2 hoverBeg = {}; ImVec2 hoverEnd = {}; if (!mLines.empty()) { float spaceSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, " ", nullptr, nullptr).x; while (lineNo <= lineMax) { ImVec2 lineStartScreenPos = ImVec2(cursorScreenPos.x, cursorScreenPos.y + lineNo * mCharAdvance.y); ImVec2 textScreenPos = ImVec2(lineStartScreenPos.x + mTextStart, lineStartScreenPos.y); auto& line = mLines[lineNo]; longest = std::max(mTextStart + TextDistanceToLineStart(Coordinates(lineNo, GetLineMaxColumn(lineNo))), longest); auto columnNo = 0; Coordinates lineStartCoord(lineNo, 0); Coordinates lineEndCoord(lineNo, GetLineMaxColumn(lineNo)); // Draw selection for the current line float sstart = -1.0f; float ssend = -1.0f; assert(mState.mSelectionStart <= mState.mSelectionEnd); if (mState.mSelectionStart <= lineEndCoord) sstart = mState.mSelectionStart > lineStartCoord ? TextDistanceToLineStart(mState.mSelectionStart) : 0.0f; if (mState.mSelectionEnd > lineStartCoord) ssend = TextDistanceToLineStart(mState.mSelectionEnd < lineEndCoord ? mState.mSelectionEnd : lineEndCoord); if (mState.mSelectionEnd.mLine > lineNo) ssend += mCharAdvance.x; if (sstart != -1 && ssend != -1 && sstart < ssend) { ImVec2 vstart(lineStartScreenPos.x + mTextStart + sstart, lineStartScreenPos.y); ImVec2 vend(lineStartScreenPos.x + mTextStart + ssend, lineStartScreenPos.y + mCharAdvance.y); drawList->AddRectFilled(vstart, vend, mPalette[(int)PaletteIndex::Selection]); } // Draw breakpoints auto start = ImVec2(lineStartScreenPos.x + scrollX, lineStartScreenPos.y); if (mBreakpoints.count(lineNo + 1) != 0) { auto end = ImVec2(lineStartScreenPos.x + contentSize.x + 2.0f * scrollX, lineStartScreenPos.y + mCharAdvance.y); drawList->AddRectFilled(start, end, mPalette[(int)PaletteIndex::Breakpoint]); } // Draw error markers auto errorIt = mErrorMarkers.find(lineNo + 1); if (errorIt != mErrorMarkers.end()) { auto end = ImVec2(lineStartScreenPos.x + contentSize.x + 2.0f * scrollX, lineStartScreenPos.y + mCharAdvance.y); drawList->AddRectFilled(start, end, mPalette[(int)PaletteIndex::ErrorMarker]); if (!ImGui::IsAnyItemActive() && ImGui::IsMouseHoveringRect(lineStartScreenPos, end)) { ImGui::BeginTooltip(); ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.2f, 0.2f, 1.0f)); ImGui::Text("Error at line %d:", errorIt->first); ImGui::PopStyleColor(); ImGui::Separator(); ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 0.2f, 1.0f)); ImGui::Text("%s", errorIt->second.c_str()); ImGui::PopStyleColor(); ImGui::EndTooltip(); } } if (ImGui::IsWindowHovered()) { // Try to see if any marker is hovered and possibly highlight it auto markerIt = mMarkers.find(lineNo + 1); if (markerIt != mMarkers.end()) { // Keep track of the highest prio marker which is hovered. int prio = -1; for (const auto& marker : markerIt->second) { auto begCoord = Coordinates(lineNo, marker.begCol); auto endCoord = Coordinates(lineNo, marker.endCol); auto beg = ImVec2(lineStartScreenPos.x + mTextStart + TextDistanceToLineStart(begCoord), lineStartScreenPos.y); auto end = ImVec2(lineStartScreenPos.x + mTextStart + TextDistanceToLineStart(endCoord), lineStartScreenPos.y + mCharAdvance.y); drawList->AddRectFilled(beg, end, marker.bgColor); if (!ImGui::IsAnyItemActive() && ImGui::IsMouseHoveringRect(beg, end)) { if (marker.prio > prio) { prio = marker.prio; mHoveredMarker = &marker; hoverBeg = beg; hoverEnd = end; } } } } } // Draw line number (right aligned) snprintf(buf, 16, "%d ", lineNo + 1); auto lineNoWidth = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf, nullptr, nullptr).x; drawList->AddText(ImVec2(lineStartScreenPos.x + mTextStart - lineNoWidth, lineStartScreenPos.y), mPalette[(int)PaletteIndex::LineNumber], buf); if (mState.mCursorPosition.mLine == lineNo) { auto focused = ImGui::IsWindowFocused(); // Highlight the current line (where the cursor is) if (!HasSelection()) { auto end = ImVec2(start.x + contentSize.x + scrollX, start.y + mCharAdvance.y); drawList->AddRectFilled(start, end, mPalette[(int)(focused ? PaletteIndex::CurrentLineFill : PaletteIndex::CurrentLineFillInactive)]); drawList->AddRect(start, end, mPalette[(int)PaletteIndex::CurrentLineEdge], 1.0f); } // Render the cursor if (focused) { auto timeEnd = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); auto elapsed = timeEnd - mStartTime; if (elapsed > 400) { float width = 1.0f; auto cindex = GetCharacterIndex(mState.mCursorPosition); float cx = TextDistanceToLineStart(mState.mCursorPosition); if (mOverwrite && cindex < (int)line.size()) { auto c = line[cindex].mChar; if (c == '\t') { auto x = (1.0f + std::floor((1.0f + cx) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize); width = x - cx; } else { char buf2[2]; buf2[0] = line[cindex].mChar; buf2[1] = '\0'; width = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf2).x; } } ImVec2 cstart(textScreenPos.x + cx, lineStartScreenPos.y); ImVec2 cend(textScreenPos.x + cx + width, lineStartScreenPos.y + mCharAdvance.y); drawList->AddRectFilled(cstart, cend, mPalette[(int)PaletteIndex::Cursor]); if (elapsed > 800) mStartTime = timeEnd; } } } // Render colorized text auto prevColor = line.empty() ? mPalette[(int)PaletteIndex::Default] : GetGlyphColor(line[0]); ImVec2 bufferOffset; for (int i = 0; i < (int)line.size();) { auto& glyph = line[i]; auto color = GetGlyphColor(glyph); if ((color != prevColor || glyph.mChar == '\t' || glyph.mChar == ' ') && !mLineBuffer.empty()) { const ImVec2 newOffset(textScreenPos.x + bufferOffset.x, textScreenPos.y + bufferOffset.y); drawList->AddText(newOffset, prevColor, mLineBuffer.c_str()); auto textSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, mLineBuffer.c_str(), nullptr, nullptr); bufferOffset.x += textSize.x; mLineBuffer.clear(); } prevColor = color; if (glyph.mChar == '\t') { auto oldX = bufferOffset.x; bufferOffset.x = (1.0f + std::floor((1.0f + bufferOffset.x) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize); ++i; if (mShowWhitespaces) { ImVec2 p1, p2, p3, p4; if (mShowShortTabGlyphs) { const auto s = ImGui::GetFontSize(); const auto x1 = textScreenPos.x + oldX + 1.0f; const auto x2 = textScreenPos.x + oldX + mCharAdvance.x - 1.0f; const auto y = textScreenPos.y + bufferOffset.y + s * 0.5f; p1 = ImVec2(x1, y); p2 = ImVec2(x2, y); p3 = ImVec2(x2 - s * 0.16f, y - s * 0.16f); p4 = ImVec2(x2 - s * 0.16f, y + s * 0.16f); } else { const auto s = ImGui::GetFontSize(); const auto x1 = textScreenPos.x + oldX + 1.0f; const auto x2 = textScreenPos.x + bufferOffset.x - 1.0f; const auto y = textScreenPos.y + bufferOffset.y + s * 0.5f; p1 = ImVec2(x1, y); p2 = ImVec2(x2, y); p3 = ImVec2(x2 - s * 0.2f, y - s * 0.2f); p4 = ImVec2(x2 - s * 0.2f, y + s * 0.2f); } drawList->AddLine(p1, p2, 0x90909090); drawList->AddLine(p2, p3, 0x90909090); drawList->AddLine(p2, p4, 0x90909090); } } else if (glyph.mChar == ' ') { if (mShowWhitespaces) { const auto s = ImGui::GetFontSize(); const auto x = textScreenPos.x + bufferOffset.x + spaceSize * 0.5f; const auto y = textScreenPos.y + bufferOffset.y + s * 0.5f; drawList->AddCircleFilled(ImVec2(x, y), 1.5f, 0x80808080, 4); } bufferOffset.x += spaceSize; i++; } else { auto l = UTF8CharLength(glyph.mChar); while (l-- > 0) mLineBuffer.push_back(line[i++].mChar); } ++columnNo; } if (!mLineBuffer.empty()) { const ImVec2 newOffset(textScreenPos.x + bufferOffset.x, textScreenPos.y + bufferOffset.y); drawList->AddText(newOffset, prevColor, mLineBuffer.c_str()); mLineBuffer.clear(); } ++lineNo; } if (mHoveredMarker) { drawList->AddRectFilled(hoverBeg, hoverEnd,mHoveredMarker->hoverBgColor); } /* // Draw a tooltip on known identifiers/preprocessor symbols if (ImGui::IsMousePosValid()) { auto mpos = ImGui::GetMousePos(); ImVec2 origin = ImGui::GetCursorScreenPos(); ImVec2 local(mpos.x - origin.x, mpos.y - origin.y); //printf("Mouse: pos(%g, %g), origin(%g, %g), local(%g, %g)\n", mpos.x, mpos.y, origin.x, origin.y, local.x, local.y); if (local.x >= mTextStart) { auto pos = ScreenPosToCoordinates(mpos); //printf("Coord(%d, %d)\n", pos.mLine, pos.mColumn); auto id = GetWordAt(pos); if (!id.empty()) { auto it = mLanguageDefinition.mIdentifiers.find(id); if (it != mLanguageDefinition.mIdentifiers.end()) { ImGui::BeginTooltip(); ImGui::TextUnformatted(it->second.mDeclaration.c_str()); ImGui::EndTooltip(); } else { auto pi = mLanguageDefinition.mPreprocIdentifiers.find(id); if (pi != mLanguageDefinition.mPreprocIdentifiers.end()) { ImGui::BeginTooltip(); ImGui::TextUnformatted(pi->second.mDeclaration.c_str()); ImGui::EndTooltip(); } } } } } */ } ImGui::Dummy(ImVec2((longest + 2), mLines.size() * mCharAdvance.y)); if (mScrollToCursor) { EnsureCursorVisible(); ImGui::SetWindowFocus(); mScrollToCursor = false; } } void TextEditor::Render(const char* aTitle, const ImVec2& aSize, bool aBorder) { mWithinRender = true; mTextChanged = false; mCursorPositionChanged = false; mFocused = false; ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(mPalette[(int)PaletteIndex::Background])); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f)); if (!mIgnoreImGuiChild) { ImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoMove); if (ImGui::IsWindowFocused()) { mFocused = true; } } if (mHandleKeyboardInputs) { HandleKeyboardInputs(); ImGui::PushTabStop(true); } if (mHandleMouseInputs) HandleMouseInputs(); ColorizeInternal(); Render(); if (mHandleKeyboardInputs) ImGui::PopTabStop(); if (!mIgnoreImGuiChild) ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::PopStyleColor(); mWithinRender = false; } void TextEditor::SetText(const std::string & aText) { mLines.clear(); mLines.emplace_back(Line()); for (auto chr : aText) { if (chr == '\r') { // ignore the carriage return character } else if (chr == '\n') mLines.emplace_back(Line()); else { mLines.back().emplace_back(Glyph(chr, PaletteIndex::Default)); } } mTextChanged = true; mScrollToTop = true; mUndoBuffer.clear(); mUndoIndex = 0; Colorize(); } void TextEditor::SetTextLines(const std::vector<std::string> & aLines) { mLines.clear(); if (aLines.empty()) { mLines.emplace_back(Line()); } else { mLines.resize(aLines.size()); for (size_t i = 0; i < aLines.size(); ++i) { const std::string & aLine = aLines[i]; mLines[i].reserve(aLine.size()); for (size_t j = 0; j < aLine.size(); ++j) mLines[i].emplace_back(Glyph(aLine[j], PaletteIndex::Default)); } } mTextChanged = true; mScrollToTop = true; mUndoBuffer.clear(); mUndoIndex = 0; Colorize(); } void TextEditor::EnterCharacter(ImWchar aChar, bool aShift) { assert(!mReadOnly); UndoRecord u; u.mBefore = mState; if (HasSelection()) { if (aChar == '\t' && mState.mSelectionStart.mLine != mState.mSelectionEnd.mLine) { auto start = mState.mSelectionStart; auto end = mState.mSelectionEnd; auto originalEnd = end; if (start > end) std::swap(start, end); start.mColumn = 0; // end.mColumn = end.mLine < mLines.size() ? mLines[end.mLine].size() : 0; if (end.mColumn == 0 && end.mLine > 0) --end.mLine; if (end.mLine >= (int)mLines.size()) end.mLine = mLines.empty() ? 0 : (int)mLines.size() - 1; end.mColumn = GetLineMaxColumn(end.mLine); //if (end.mColumn >= GetLineMaxColumn(end.mLine)) // end.mColumn = GetLineMaxColumn(end.mLine) - 1; u.mRemovedStart = start; u.mRemovedEnd = end; u.mRemoved = GetText(start, end); bool modified = false; for (int i = start.mLine; i <= end.mLine; i++) { auto& line = mLines[i]; if (aShift) { if (!line.empty()) { if (line.front().mChar == '\t') { line.erase(line.begin()); modified = true; } else { for (int j = 0; j < mTabSize && !line.empty() && line.front().mChar == ' '; j++) { line.erase(line.begin()); modified = true; } } } } else { line.insert(line.begin(), Glyph('\t', TextEditor::PaletteIndex::Background)); modified = true; } } if (modified) { start = Coordinates(start.mLine, GetCharacterColumn(start.mLine, 0)); Coordinates rangeEnd; if (originalEnd.mColumn != 0) { end = Coordinates(end.mLine, GetLineMaxColumn(end.mLine)); rangeEnd = end; u.mAdded = GetText(start, end); } else { end = Coordinates(originalEnd.mLine, 0); rangeEnd = Coordinates(end.mLine - 1, GetLineMaxColumn(end.mLine - 1)); u.mAdded = GetText(start, rangeEnd); } u.mAddedStart = start; u.mAddedEnd = rangeEnd; u.mAfter = mState; mState.mSelectionStart = start; mState.mSelectionEnd = end; AddUndo(u); mTextChanged = true; EnsureCursorVisible(); } return; } // c == '\t' else { u.mRemoved = GetSelectedText(); u.mRemovedStart = mState.mSelectionStart; u.mRemovedEnd = mState.mSelectionEnd; DeleteSelection(); } } // HasSelection auto coord = GetActualCursorCoordinates(); u.mAddedStart = coord; assert(!mLines.empty()); if (aChar == '\n') { InsertLine(coord.mLine + 1); auto& line = mLines[coord.mLine]; auto& newLine = mLines[coord.mLine + 1]; if (mLanguageDefinition.mAutoIndentation) for (size_t it = 0; it < line.size() && isascii(line[it].mChar) && isblank(line[it].mChar); ++it) newLine.push_back(line[it]); const size_t whitespaceSize = newLine.size(); auto cindex = GetCharacterIndex(coord); newLine.insert(newLine.end(), line.begin() + cindex, line.end()); line.erase(line.begin() + cindex, line.begin() + line.size()); SetCursorPosition(Coordinates(coord.mLine + 1, GetCharacterColumn(coord.mLine + 1, (int)whitespaceSize))); u.mAdded = (char)aChar; } else { char buf[7]; int e = ImTextCharToUtf8(buf, 7, aChar); if (e > 0) { buf[e] = '\0'; auto& line = mLines[coord.mLine]; auto cindex = GetCharacterIndex(coord); if (mOverwrite && cindex < (int)line.size()) { auto d = UTF8CharLength(line[cindex].mChar); u.mRemovedStart = mState.mCursorPosition; u.mRemovedEnd = Coordinates(coord.mLine, GetCharacterColumn(coord.mLine, cindex + d)); while (d-- > 0 && cindex < (int)line.size()) { u.mRemoved += line[cindex].mChar; line.erase(line.begin() + cindex); } } for (auto p = buf; *p != '\0'; p++, ++cindex) line.insert(line.begin() + cindex, Glyph(*p, PaletteIndex::Default)); u.mAdded = buf; SetCursorPosition(Coordinates(coord.mLine, GetCharacterColumn(coord.mLine, cindex))); } else return; } mTextChanged = true; u.mAddedEnd = GetActualCursorCoordinates(); u.mAfter = mState; AddUndo(u); Colorize(coord.mLine - 1, 3); EnsureCursorVisible(); } void TextEditor::SetReadOnly(bool aValue) { mReadOnly = aValue; } void TextEditor::SetColorizerEnable(bool aValue) { mColorizerEnabled = aValue; } void TextEditor::SetCursorPosition(const Coordinates & aPosition) { if (mState.mCursorPosition != aPosition) { mState.mCursorPosition = aPosition; mCursorPositionChanged = true; EnsureCursorVisible(); } } void TextEditor::SetSelectionStart(const Coordinates & aPosition) { mState.mSelectionStart = SanitizeCoordinates(aPosition); if (mState.mSelectionStart > mState.mSelectionEnd) std::swap(mState.mSelectionStart, mState.mSelectionEnd); } void TextEditor::SetSelectionEnd(const Coordinates & aPosition) { mState.mSelectionEnd = SanitizeCoordinates(aPosition); if (mState.mSelectionStart > mState.mSelectionEnd) std::swap(mState.mSelectionStart, mState.mSelectionEnd); } void TextEditor::SetSelection(const Coordinates & aStart, const Coordinates & aEnd, SelectionMode aMode) { auto oldSelStart = mState.mSelectionStart; auto oldSelEnd = mState.mSelectionEnd; mState.mSelectionStart = SanitizeCoordinates(aStart); mState.mSelectionEnd = SanitizeCoordinates(aEnd); if (mState.mSelectionStart > mState.mSelectionEnd) std::swap(mState.mSelectionStart, mState.mSelectionEnd); switch (aMode) { case TextEditor::SelectionMode::Normal: break; case TextEditor::SelectionMode::Word: { mState.mSelectionStart = FindWordStart(mState.mSelectionStart); if (!IsOnWordBoundary(mState.mSelectionEnd)) mState.mSelectionEnd = FindWordEnd(FindWordStart(mState.mSelectionEnd)); break; } case TextEditor::SelectionMode::Line: { const auto lineNo = mState.mSelectionEnd.mLine; //const auto lineSize = (size_t)lineNo < mLines.size() ? mLines[lineNo].size() : 0; mState.mSelectionStart = Coordinates(mState.mSelectionStart.mLine, 0); mState.mSelectionEnd = Coordinates(lineNo, GetLineMaxColumn(lineNo)); break; } default: break; } if (mState.mSelectionStart != oldSelStart || mState.mSelectionEnd != oldSelEnd) mCursorPositionChanged = true; } void TextEditor::SetTabSize(int aValue) { mTabSize = std::max(0, std::min(32, aValue)); } void TextEditor::InsertText(const std::string & aValue) { InsertText(aValue.c_str()); } void TextEditor::InsertText(const char * aValue) { if (aValue == nullptr) return; auto pos = GetActualCursorCoordinates(); auto start = std::min(pos, mState.mSelectionStart); int totalLines = pos.mLine - start.mLine; totalLines += InsertTextAt(pos, aValue); SetSelection(pos, pos); SetCursorPosition(pos); Colorize(start.mLine - 1, totalLines + 2); } void TextEditor::AppendText(const std::string & aValue) { AppendText(aValue.c_str()); } void TextEditor::AppendText(const char * aValue) { if (aValue == nullptr) return; Coordinates pos = SanitizeCoordinates(Coordinates(INT_MAX, INT_MAX)); auto start = std::min(pos, mState.mSelectionStart); int totalLines = pos.mLine - start.mLine; totalLines += InsertTextAt(pos, aValue); SetSelection(pos, pos); SetCursorPosition(pos); Colorize(start.mLine - 1, totalLines + 2); } void TextEditor::DeleteSelection() { assert(mState.mSelectionEnd >= mState.mSelectionStart); if (mState.mSelectionEnd == mState.mSelectionStart) return; DeleteRange(mState.mSelectionStart, mState.mSelectionEnd); SetSelection(mState.mSelectionStart, mState.mSelectionStart); SetCursorPosition(mState.mSelectionStart); Colorize(mState.mSelectionStart.mLine, 1); } void TextEditor::MoveUp(int aAmount, bool aSelect) { auto oldPos = mState.mCursorPosition; mState.mCursorPosition.mLine = std::max(0, mState.mCursorPosition.mLine - aAmount); if (oldPos != mState.mCursorPosition) { if (aSelect) { if (oldPos == mInteractiveStart) mInteractiveStart = mState.mCursorPosition; else if (oldPos == mInteractiveEnd) mInteractiveEnd = mState.mCursorPosition; else { mInteractiveStart = mState.mCursorPosition; mInteractiveEnd = oldPos; } } else mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; SetSelection(mInteractiveStart, mInteractiveEnd); EnsureCursorVisible(); } } void TextEditor::MoveDown(int aAmount, bool aSelect) { assert(mState.mCursorPosition.mColumn >= 0); auto oldPos = mState.mCursorPosition; mState.mCursorPosition.mLine = std::max(0, std::min((int)mLines.size() - 1, mState.mCursorPosition.mLine + aAmount)); if (mState.mCursorPosition != oldPos) { if (aSelect) { if (oldPos == mInteractiveEnd) mInteractiveEnd = mState.mCursorPosition; else if (oldPos == mInteractiveStart) mInteractiveStart = mState.mCursorPosition; else { mInteractiveStart = oldPos; mInteractiveEnd = mState.mCursorPosition; } } else mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; SetSelection(mInteractiveStart, mInteractiveEnd); EnsureCursorVisible(); } } static bool IsUTFSequence(char c) { return (c & 0xC0) == 0x80; } void TextEditor::MoveLeft(int aAmount, bool aSelect, bool aWordMode) { if (mLines.empty()) return; auto oldPos = mState.mCursorPosition; mState.mCursorPosition = GetActualCursorCoordinates(); auto line = mState.mCursorPosition.mLine; auto cindex = GetCharacterIndex(mState.mCursorPosition); while (aAmount-- > 0) { if (cindex == 0) { if (line > 0) { --line; if ((int)mLines.size() > line) cindex = (int)mLines[line].size(); else cindex = 0; } } else { --cindex; if (cindex > 0) { if ((int)mLines.size() > line) { while (cindex > 0 && IsUTFSequence(mLines[line][cindex].mChar)) --cindex; } } } mState.mCursorPosition = Coordinates(line, GetCharacterColumn(line, cindex)); if (aWordMode) { mState.mCursorPosition = FindWordStart(mState.mCursorPosition); cindex = GetCharacterIndex(mState.mCursorPosition); } } mState.mCursorPosition = Coordinates(line, GetCharacterColumn(line, cindex)); assert(mState.mCursorPosition.mColumn >= 0); if (aSelect) { if (oldPos == mInteractiveStart) mInteractiveStart = mState.mCursorPosition; else if (oldPos == mInteractiveEnd) mInteractiveEnd = mState.mCursorPosition; else { mInteractiveStart = mState.mCursorPosition; mInteractiveEnd = oldPos; } } else mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; SetSelection(mInteractiveStart, mInteractiveEnd, aSelect && aWordMode ? SelectionMode::Word : SelectionMode::Normal); EnsureCursorVisible(); } void TextEditor::MoveRight(int aAmount, bool aSelect, bool aWordMode) { auto oldPos = mState.mCursorPosition; if (mLines.empty() || oldPos.mLine >= (int)mLines.size()) return; auto cindex = GetCharacterIndex(mState.mCursorPosition); while (aAmount-- > 0) { auto lindex = mState.mCursorPosition.mLine; auto& line = mLines[lindex]; if (cindex >= (int)line.size()) { if (mState.mCursorPosition.mLine < (int)mLines.size() - 1) { mState.mCursorPosition.mLine = std::max(0, std::min((int)mLines.size() - 1, mState.mCursorPosition.mLine + 1)); mState.mCursorPosition.mColumn = 0; } else return; } else { cindex += UTF8CharLength(line[cindex].mChar); mState.mCursorPosition = Coordinates(lindex, GetCharacterColumn(lindex, cindex)); if (aWordMode) mState.mCursorPosition = FindNextWord(mState.mCursorPosition); } } if (aSelect) { if (oldPos == mInteractiveEnd) mInteractiveEnd = SanitizeCoordinates(mState.mCursorPosition); else if (oldPos == mInteractiveStart) mInteractiveStart = mState.mCursorPosition; else { mInteractiveStart = oldPos; mInteractiveEnd = mState.mCursorPosition; } } else mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; SetSelection(mInteractiveStart, mInteractiveEnd, aSelect && aWordMode ? SelectionMode::Word : SelectionMode::Normal); EnsureCursorVisible(); } void TextEditor::MoveTop(bool aSelect) { auto oldPos = mState.mCursorPosition; SetCursorPosition(Coordinates(0, 0)); if (mState.mCursorPosition != oldPos) { if (aSelect) { mInteractiveEnd = oldPos; mInteractiveStart = mState.mCursorPosition; } else mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; SetSelection(mInteractiveStart, mInteractiveEnd); } } void TextEditor::TextEditor::MoveBottom(bool aSelect) { auto oldPos = GetCursorPosition(); auto newPos = Coordinates((int)mLines.size() - 1, 0); SetCursorPosition(newPos); if (aSelect) { mInteractiveStart = oldPos; mInteractiveEnd = newPos; } else mInteractiveStart = mInteractiveEnd = newPos; SetSelection(mInteractiveStart, mInteractiveEnd); } void TextEditor::MoveHome(bool aSelect) { auto oldPos = mState.mCursorPosition; SetCursorPosition(Coordinates(mState.mCursorPosition.mLine, 0)); if (mState.mCursorPosition != oldPos) { if (aSelect) { if (oldPos == mInteractiveStart) mInteractiveStart = mState.mCursorPosition; else if (oldPos == mInteractiveEnd) mInteractiveEnd = mState.mCursorPosition; else { mInteractiveStart = mState.mCursorPosition; mInteractiveEnd = oldPos; } } else mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; SetSelection(mInteractiveStart, mInteractiveEnd); } } void TextEditor::MoveEnd(bool aSelect) { auto oldPos = mState.mCursorPosition; SetCursorPosition(Coordinates(mState.mCursorPosition.mLine, GetLineMaxColumn(oldPos.mLine))); if (mState.mCursorPosition != oldPos) { if (aSelect) { if (oldPos == mInteractiveEnd) mInteractiveEnd = mState.mCursorPosition; else if (oldPos == mInteractiveStart) mInteractiveStart = mState.mCursorPosition; else { mInteractiveStart = oldPos; mInteractiveEnd = mState.mCursorPosition; } } else mInteractiveStart = mInteractiveEnd = mState.mCursorPosition; SetSelection(mInteractiveStart, mInteractiveEnd); } } void TextEditor::Delete() { assert(!mReadOnly); if (mLines.empty()) return; UndoRecord u; u.mBefore = mState; if (HasSelection()) { u.mRemoved = GetSelectedText(); u.mRemovedStart = mState.mSelectionStart; u.mRemovedEnd = mState.mSelectionEnd; DeleteSelection(); } else { auto pos = GetActualCursorCoordinates(); SetCursorPosition(pos); auto& line = mLines[pos.mLine]; if (pos.mColumn == GetLineMaxColumn(pos.mLine)) { if (pos.mLine == (int)mLines.size() - 1) return; u.mRemoved = '\n'; u.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates(); Advance(u.mRemovedEnd); auto& nextLine = mLines[pos.mLine + 1]; line.insert(line.end(), nextLine.begin(), nextLine.end()); RemoveLine(pos.mLine + 1); } else { auto cindex = GetCharacterIndex(pos); u.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates(); u.mRemovedEnd.mColumn++; u.mRemoved = GetText(u.mRemovedStart, u.mRemovedEnd); auto d = UTF8CharLength(line[cindex].mChar); while (d-- > 0 && cindex < (int)line.size()) line.erase(line.begin() + cindex); } mTextChanged = true; Colorize(pos.mLine, 1); } u.mAfter = mState; AddUndo(u); } void TextEditor::Backspace() { assert(!mReadOnly); if (mLines.empty()) return; UndoRecord u; u.mBefore = mState; if (HasSelection()) { u.mRemoved = GetSelectedText(); u.mRemovedStart = mState.mSelectionStart; u.mRemovedEnd = mState.mSelectionEnd; DeleteSelection(); } else { auto pos = GetActualCursorCoordinates(); SetCursorPosition(pos); if (mState.mCursorPosition.mColumn == 0) { if (mState.mCursorPosition.mLine == 0) return; u.mRemoved = '\n'; u.mRemovedStart = u.mRemovedEnd = Coordinates(pos.mLine - 1, GetLineMaxColumn(pos.mLine - 1)); Advance(u.mRemovedEnd); auto& line = mLines[mState.mCursorPosition.mLine]; auto& prevLine = mLines[mState.mCursorPosition.mLine - 1]; auto prevSize = GetLineMaxColumn(mState.mCursorPosition.mLine - 1); prevLine.insert(prevLine.end(), line.begin(), line.end()); ErrorMarkers etmp; for (auto& i : mErrorMarkers) etmp.insert(ErrorMarkers::value_type(i.first - 1 == mState.mCursorPosition.mLine ? i.first - 1 : i.first, i.second)); mErrorMarkers = std::move(etmp); RemoveLine(mState.mCursorPosition.mLine); --mState.mCursorPosition.mLine; mState.mCursorPosition.mColumn = prevSize; } else { auto& line = mLines[mState.mCursorPosition.mLine]; auto cindex = GetCharacterIndex(pos) - 1; auto cend = cindex + 1; while (cindex > 0 && IsUTFSequence(line[cindex].mChar)) --cindex; //if (cindex > 0 && UTF8CharLength(line[cindex].mChar) > 1) // --cindex; u.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates(); --u.mRemovedStart.mColumn; if (line[cindex].mChar == '\t') mState.mCursorPosition.mColumn -= mTabSize; else --mState.mCursorPosition.mColumn; while (cindex < (int)line.size() && cend-- > cindex) { u.mRemoved += line[cindex].mChar; line.erase(line.begin() + cindex); } } mTextChanged = true; EnsureCursorVisible(); Colorize(mState.mCursorPosition.mLine, 1); } u.mAfter = mState; AddUndo(u); } void TextEditor::SelectWordUnderCursor() { auto c = GetCursorPosition(); SetSelection(FindWordStart(c), FindWordEnd(c)); } void TextEditor::SelectAll() { SetSelection(Coordinates(0, 0), Coordinates((int)mLines.size(), 0)); } bool TextEditor::HasSelection() const { return mState.mSelectionEnd > mState.mSelectionStart; } void TextEditor::Copy() { if (HasSelection()) { ImGui::SetClipboardText(GetSelectedText().c_str()); } else { if (!mLines.empty()) { std::string str; auto& line = mLines[GetActualCursorCoordinates().mLine]; for (auto& g : line) str.push_back(g.mChar); ImGui::SetClipboardText(str.c_str()); } } } void TextEditor::Cut() { if (IsReadOnly()) { Copy(); } else { if (HasSelection()) { UndoRecord u; u.mBefore = mState; u.mRemoved = GetSelectedText(); u.mRemovedStart = mState.mSelectionStart; u.mRemovedEnd = mState.mSelectionEnd; Copy(); DeleteSelection(); u.mAfter = mState; AddUndo(u); } } } void TextEditor::Paste() { if (IsReadOnly()) return; auto clipText = ImGui::GetClipboardText(); if (clipText != nullptr && strlen(clipText) > 0) { UndoRecord u; u.mBefore = mState; if (HasSelection()) { u.mRemoved = GetSelectedText(); u.mRemovedStart = mState.mSelectionStart; u.mRemovedEnd = mState.mSelectionEnd; DeleteSelection(); } u.mAdded = clipText; u.mAddedStart = GetActualCursorCoordinates(); InsertText(clipText); u.mAddedEnd = GetActualCursorCoordinates(); u.mAfter = mState; AddUndo(u); } } bool TextEditor::CanUndo() const { return !mReadOnly && mUndoIndex > 0; } bool TextEditor::CanRedo() const { return !mReadOnly && mUndoIndex < (int)mUndoBuffer.size(); } void TextEditor::Undo(int aSteps) { while (CanUndo() && aSteps-- > 0) mUndoBuffer[--mUndoIndex].Undo(this); } void TextEditor::Redo(int aSteps) { while (CanRedo() && aSteps-- > 0) mUndoBuffer[mUndoIndex++].Redo(this); } const TextEditor::Palette & TextEditor::GetDarkPalette() { const static Palette p = { { 0xff7f7f7f, // Default 0xffd69c56, // Keyword 0xff00ff00, // Number 0xff7070e0, // String 0xff70a0e0, // Char literal 0xffffffff, // Punctuation 0xff408080, // Preprocessor 0xffaaaaaa, // Identifier 0xff9bc64d, // Known identifier 0xffc040a0, // Preproc identifier 0xff206020, // Comment (single line) 0xff406020, // Comment (multi line) 0xff101010, // Background 0xffe0e0e0, // Cursor 0x80a06020, // Selection 0x800020ff, // ErrorMarker 0x40f08000, // Breakpoint 0xff707000, // Line number 0x40000000, // Current line fill 0x40808080, // Current line fill (inactive) 0x40a0a0a0, // Current line edge } }; return p; } const TextEditor::Palette & TextEditor::GetLightPalette() { const static Palette p = { { 0xff7f7f7f, // None 0xffff0c06, // Keyword 0xff008000, // Number 0xff2020a0, // String 0xff304070, // Char literal 0xff000000, // Punctuation 0xff406060, // Preprocessor 0xff404040, // Identifier 0xff606010, // Known identifier 0xffc040a0, // Preproc identifier 0xff205020, // Comment (single line) 0xff405020, // Comment (multi line) 0xffffffff, // Background 0xff000000, // Cursor 0x80600000, // Selection 0xa00010ff, // ErrorMarker 0x80f08000, // Breakpoint 0xff505000, // Line number 0x40000000, // Current line fill 0x40808080, // Current line fill (inactive) 0x40000000, // Current line edge } }; return p; } const TextEditor::Palette & TextEditor::GetRetroBluePalette() { const static Palette p = { { 0xff00ffff, // None 0xffffff00, // Keyword 0xff00ff00, // Number 0xff808000, // String 0xff808000, // Char literal 0xffffffff, // Punctuation 0xff008000, // Preprocessor 0xff00ffff, // Identifier 0xffffffff, // Known identifier 0xffff00ff, // Preproc identifier 0xff808080, // Comment (single line) 0xff404040, // Comment (multi line) 0xff800000, // Background 0xff0080ff, // Cursor 0x80ffff00, // Selection 0xa00000ff, // ErrorMarker 0x80ff8000, // Breakpoint 0xff808000, // Line number 0x40000000, // Current line fill 0x40808080, // Current line fill (inactive) 0x40000000, // Current line edge } }; return p; } std::string TextEditor::GetText() const { auto lastLine = (int)mLines.size() - 1; auto lastLineLength = GetLineMaxColumn(lastLine); return GetText(Coordinates(), Coordinates(lastLine, lastLineLength)); } std::vector<std::string> TextEditor::GetTextLines() const { std::vector<std::string> result; result.reserve(mLines.size()); for (auto & line : mLines) { std::string text; text.resize(line.size()); for (size_t i = 0; i < line.size(); ++i) text[i] = line[i].mChar; result.emplace_back(std::move(text)); } return result; } std::string TextEditor::GetSelectedText() const { return GetText(mState.mSelectionStart, mState.mSelectionEnd); } std::string TextEditor::GetCurrentLineText()const { auto lineLength = GetLineMaxColumn(mState.mCursorPosition.mLine); return GetText( Coordinates(mState.mCursorPosition.mLine, 0), Coordinates(mState.mCursorPosition.mLine, lineLength)); } void TextEditor::ProcessInputs() { } void TextEditor::Colorize(int aFromLine, int aLines) { int toLine = aLines == -1 ? (int)mLines.size() : std::min((int)mLines.size(), aFromLine + aLines); mColorRangeMin = std::min(mColorRangeMin, aFromLine); mColorRangeMax = std::max(mColorRangeMax, toLine); mColorRangeMin = std::max(0, mColorRangeMin); mColorRangeMax = std::max(mColorRangeMin, mColorRangeMax); mCheckComments = true; } void TextEditor::ColorizeRange(int aFromLine, int aToLine) { if (mLines.empty() || aFromLine >= aToLine) return; std::string buffer; //std::cmatch results; std::string id; int endLine = std::max(0, std::min((int)mLines.size(), aToLine)); for (int i = aFromLine; i < endLine; ++i) { auto& line = mLines[i]; if (line.empty()) continue; buffer.resize(line.size()); for (size_t j = 0; j < line.size(); ++j) { auto& col = line[j]; buffer[j] = col.mChar; col.mColorIndex = PaletteIndex::Default; } const char * bufferBegin = &buffer.front(); const char * bufferEnd = bufferBegin + buffer.size(); auto last = bufferEnd; for (auto first = bufferBegin; first != last; ) { const char * token_begin = nullptr; const char * token_end = nullptr; PaletteIndex token_color = PaletteIndex::Default; bool hasTokenizeResult = false; if (mLanguageDefinition.mTokenize != nullptr) { if (mLanguageDefinition.mTokenize(first, last, token_begin, token_end, token_color)) hasTokenizeResult = true; } if (hasTokenizeResult == false) { // todo : remove //printf("using regex for %.*s\n", first + 10 < last ? 10 : int(last - first), first); /* for (auto& p : mRegexList) { if (std::regex_search(first, last, results, p.first, std::regex_constants::match_continuous)) { hasTokenizeResult = true; auto& v = *results.begin(); token_begin = v.first; token_end = v.second; token_color = p.second; break; } } */ } if (hasTokenizeResult == false) { first++; } else { const size_t token_length = token_end - token_begin; if (token_color == PaletteIndex::Identifier) { id.assign(token_begin, token_end); // todo : allmost all language definitions use lower case to specify keywords, so shouldn't this use ::tolower ? if (!mLanguageDefinition.mCaseSensitive) std::transform(id.begin(), id.end(), id.begin(), ::toupper); if (!line[first - bufferBegin].mPreprocessor) { if (mLanguageDefinition.mKeywords.count(id) != 0) token_color = PaletteIndex::Keyword; else if (mLanguageDefinition.mIdentifiers.count(id) != 0) token_color = PaletteIndex::KnownIdentifier; else if (mLanguageDefinition.mPreprocIdentifiers.count(id) != 0) token_color = PaletteIndex::PreprocIdentifier; } else { if (mLanguageDefinition.mPreprocIdentifiers.count(id) != 0) token_color = PaletteIndex::PreprocIdentifier; } } for (size_t j = 0; j < token_length; ++j) line[(token_begin - bufferBegin) + j].mColorIndex = token_color; first = token_end; } } } } void TextEditor::ColorizeInternal() { if (mLines.empty() || !mColorizerEnabled) return; if (mCheckComments) { auto endLine = (int)mLines.size(); auto endIndex = 0; auto commentStartLine = endLine; auto commentStartIndex = endIndex; auto withinString = false; auto withinSingleLineComment = false; auto withinPreproc = false; auto firstChar = true; // there is no other non-whitespace characters in the line before auto concatenate = false; // '\' on the very end of the line auto currentLine = 0; auto currentIndex = 0; while (currentLine < endLine || currentIndex < endIndex) { auto& line = mLines[currentLine]; if (currentIndex == 0 && !concatenate) { withinSingleLineComment = false; withinPreproc = false; firstChar = true; } concatenate = false; if (!line.empty()) { auto& g = line[currentIndex]; auto c = g.mChar; if (c != mLanguageDefinition.mPreprocChar && !isspace(c)) firstChar = false; if (currentIndex == (int)line.size() - 1 && line[line.size() - 1].mChar == '\\') concatenate = true; bool inComment = (commentStartLine < currentLine || (commentStartLine == currentLine && commentStartIndex <= currentIndex)); if (withinString) { line[currentIndex].mMultiLineComment = inComment; if (c == '\"') { if (currentIndex + 1 < (int)line.size() && line[currentIndex + 1].mChar == '\"') { currentIndex += 1; if (currentIndex < (int)line.size()) line[currentIndex].mMultiLineComment = inComment; } else withinString = false; } else if (c == '\\') { currentIndex += 1; if (currentIndex < (int)line.size()) line[currentIndex].mMultiLineComment = inComment; } } else { if (firstChar && c == mLanguageDefinition.mPreprocChar) withinPreproc = true; if (c == '\"') { withinString = true; line[currentIndex].mMultiLineComment = inComment; } else { auto pred = [](const char& a, const Glyph& b) { return a == b.mChar; }; auto from = line.begin() + currentIndex; auto& startStr = mLanguageDefinition.mCommentStart; auto& singleStartStr = mLanguageDefinition.mSingleLineComment; if (!withinSingleLineComment && currentIndex + startStr.size() <= line.size() && equals(startStr.begin(), startStr.end(), from, from + startStr.size(), pred)) { commentStartLine = currentLine; commentStartIndex = currentIndex; } else if (singleStartStr.size() > 0 && currentIndex + singleStartStr.size() <= line.size() && equals(singleStartStr.begin(), singleStartStr.end(), from, from + singleStartStr.size(), pred)) { withinSingleLineComment = true; } inComment = (commentStartLine < currentLine || (commentStartLine == currentLine && commentStartIndex <= currentIndex)); line[currentIndex].mMultiLineComment = inComment; line[currentIndex].mComment = withinSingleLineComment; auto& endStr = mLanguageDefinition.mCommentEnd; if (currentIndex + 1 >= (int)endStr.size() && equals(endStr.begin(), endStr.end(), from + 1 - endStr.size(), from + 1, pred)) { commentStartIndex = endIndex; commentStartLine = endLine; } } } line[currentIndex].mPreprocessor = withinPreproc; currentIndex += UTF8CharLength(c); if (currentIndex >= (int)line.size()) { currentIndex = 0; ++currentLine; } } else { currentIndex = 0; ++currentLine; } } mCheckComments = false; } if (mColorRangeMin < mColorRangeMax) { const int increment = (mLanguageDefinition.mTokenize == nullptr) ? 10 : 10000; const int to = std::min(mColorRangeMin + increment, mColorRangeMax); ColorizeRange(mColorRangeMin, to); mColorRangeMin = to; if (mColorRangeMax == mColorRangeMin) { mColorRangeMin = std::numeric_limits<int>::max(); mColorRangeMax = 0; } return; } } float TextEditor::TextDistanceToLineStart(const Coordinates& aFrom) const { auto& line = mLines[aFrom.mLine]; float distance = 0.0f; float spaceSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, " ", nullptr, nullptr).x; int colIndex = GetCharacterIndex(aFrom); for (size_t it = 0u; it < line.size() && (int)it < colIndex; ) { if (line[it].mChar == '\t') { distance = (1.0f + std::floor((1.0f + distance) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize); ++it; } else { auto d = UTF8CharLength(line[it].mChar); char tempCString[7]; int i = 0; for (; i < 6 && d-- > 0 && it < line.size(); i++, it++) tempCString[i] = line[it].mChar; tempCString[i] = '\0'; distance += ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, tempCString, nullptr, nullptr).x; } } return distance; } void TextEditor::EnsureCursorVisible() { if (!mWithinRender) { mScrollToCursor = true; return; } float scrollX = ImGui::GetScrollX(); float scrollY = ImGui::GetScrollY(); auto height = ImGui::GetWindowHeight(); auto width = ImGui::GetWindowWidth(); auto top = 1 + (int)ceil(scrollY / mCharAdvance.y); auto bottom = (int)ceil((scrollY + height) / mCharAdvance.y); auto left = (int)ceil(scrollX / mCharAdvance.x); auto right = (int)ceil((scrollX + width) / mCharAdvance.x); auto pos = GetActualCursorCoordinates(); auto len = TextDistanceToLineStart(pos); if (pos.mLine < top) ImGui::SetScrollY(std::max(0.0f, (pos.mLine - 1) * mCharAdvance.y)); if (pos.mLine > bottom - 4) ImGui::SetScrollY(std::max(0.0f, (pos.mLine + 4) * mCharAdvance.y - height)); if (len + mTextStart < left + 4) ImGui::SetScrollX(std::max(0.0f, len + mTextStart - 4)); if (len + mTextStart > right - 4) ImGui::SetScrollX(std::max(0.0f, len + mTextStart + 4 - width)); } int TextEditor::GetPageSize() const { auto height = ImGui::GetWindowHeight() - 20.0f; return (int)floor(height / mCharAdvance.y); } TextEditor::UndoRecord::UndoRecord( const std::string& aAdded, const TextEditor::Coordinates aAddedStart, const TextEditor::Coordinates aAddedEnd, const std::string& aRemoved, const TextEditor::Coordinates aRemovedStart, const TextEditor::Coordinates aRemovedEnd, TextEditor::EditorState& aBefore, TextEditor::EditorState& aAfter) : mAdded(aAdded) , mAddedStart(aAddedStart) , mAddedEnd(aAddedEnd) , mRemoved(aRemoved) , mRemovedStart(aRemovedStart) , mRemovedEnd(aRemovedEnd) , mBefore(aBefore) , mAfter(aAfter) { assert(mAddedStart <= mAddedEnd); assert(mRemovedStart <= mRemovedEnd); } void TextEditor::UndoRecord::Undo(TextEditor * aEditor) { if (!mAdded.empty()) { aEditor->DeleteRange(mAddedStart, mAddedEnd); aEditor->Colorize(mAddedStart.mLine - 1, mAddedEnd.mLine - mAddedStart.mLine + 2); } if (!mRemoved.empty()) { auto start = mRemovedStart; aEditor->InsertTextAt(start, mRemoved.c_str()); aEditor->Colorize(mRemovedStart.mLine - 1, mRemovedEnd.mLine - mRemovedStart.mLine + 2); } aEditor->mState = mBefore; aEditor->EnsureCursorVisible(); } void TextEditor::UndoRecord::Redo(TextEditor * aEditor) { if (!mRemoved.empty()) { aEditor->DeleteRange(mRemovedStart, mRemovedEnd); aEditor->Colorize(mRemovedStart.mLine - 1, mRemovedEnd.mLine - mRemovedStart.mLine + 1); } if (!mAdded.empty()) { auto start = mAddedStart; aEditor->InsertTextAt(start, mAdded.c_str()); aEditor->Colorize(mAddedStart.mLine - 1, mAddedEnd.mLine - mAddedStart.mLine + 1); } aEditor->mState = mAfter; aEditor->EnsureCursorVisible(); } static bool TokenizeCStyleString(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end) { const char * p = in_begin; if (*p == '"') { p++; while (p < in_end) { // handle end of string if (*p == '"') { out_begin = in_begin; out_end = p + 1; return true; } // handle escape character for " if (*p == '\\' && p + 1 < in_end && p[1] == '"') p++; p++; } } return false; } static bool TokenizeCStyleCharacterLiteral(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end) { const char * p = in_begin; if (*p == '\'') { p++; // handle escape characters if (p < in_end && *p == '\\') p++; if (p < in_end) p++; // handle end of character literal if (p < in_end && *p == '\'') { out_begin = in_begin; out_end = p + 1; return true; } } return false; } static bool TokenizeCStyleIdentifier(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end) { const char * p = in_begin; if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || *p == '_') { p++; while ((p < in_end) && ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '_')) p++; out_begin = in_begin; out_end = p; return true; } return false; } static bool TokenizeCStyleNumber(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end) { const char * p = in_begin; const bool startsWithNumber = *p >= '0' && *p <= '9'; if (*p != '+' && *p != '-' && !startsWithNumber) return false; p++; bool hasNumber = startsWithNumber; while (p < in_end && (*p >= '0' && *p <= '9')) { hasNumber = true; p++; } if (hasNumber == false) return false; bool isFloat = false; bool isHex = false; bool isBinary = false; if (p < in_end) { if (*p == '.') { isFloat = true; p++; while (p < in_end && (*p >= '0' && *p <= '9')) p++; } else if (*p == 'x' || *p == 'X') { // hex formatted integer of the type 0xef80 isHex = true; p++; while (p < in_end && ((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F'))) p++; } else if (*p == 'b' || *p == 'B') { // binary formatted integer of the type 0b01011101 isBinary = true; p++; while (p < in_end && (*p >= '0' && *p <= '1')) p++; } } if (isHex == false && isBinary == false) { // floating point exponent if (p < in_end && (*p == 'e' || *p == 'E')) { isFloat = true; p++; if (p < in_end && (*p == '+' || *p == '-')) p++; bool hasDigits = false; while (p < in_end && (*p >= '0' && *p <= '9')) { hasDigits = true; p++; } if (hasDigits == false) return false; } // single precision floating point type if (p < in_end && *p == 'f') p++; } if (isFloat == false) { // integer size type while (p < in_end && (*p == 'u' || *p == 'U' || *p == 'l' || *p == 'L')) p++; } out_begin = in_begin; out_end = p; return true; } static bool TokenizeCStylePunctuation(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end) { (void)in_end; switch (*in_begin) { case '[': case ']': case '{': case '}': case '!': case '%': case '^': case '&': case '*': case '(': case ')': case '-': case '+': case '=': case '~': case '|': case '<': case '>': case '?': case ':': case '/': case ';': case ',': case '.': out_begin = in_begin; out_end = in_begin + 1; return true; } return false; } static bool TokenizeLuaStyleString(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end) { const char * p = in_begin; bool is_single_quote = false; bool is_double_quotes = false; bool is_double_square_brackets = false; switch (*p) { case '\'': is_single_quote = true; break; case '"': is_double_quotes = true; break; case '[': p++; if (p < in_end && *(p) == '[') is_double_square_brackets = true; break; } if (is_single_quote || is_double_quotes || is_double_square_brackets) { p++; while (p < in_end) { // handle end of string if ((is_single_quote && *p == '\'') || (is_double_quotes && *p == '"') || (is_double_square_brackets && *p == ']' && p + 1 < in_end && *(p + 1) == ']')) { out_begin = in_begin; if (is_double_square_brackets) out_end = p + 2; else out_end = p + 1; return true; } // handle escape character for " if (*p == '\\' && p + 1 < in_end && (is_single_quote || is_double_quotes)) p++; p++; } } return false; } static bool TokenizeLuaStyleIdentifier(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end) { const char * p = in_begin; if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || *p == '_') { p++; while ((p < in_end) && ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '_')) p++; out_begin = in_begin; out_end = p; return true; } return false; } static bool TokenizeLuaStyleNumber(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end) { const char * p = in_begin; const bool startsWithNumber = *p >= '0' && *p <= '9'; if (*p != '+' && *p != '-' && !startsWithNumber) return false; p++; bool hasNumber = startsWithNumber; while (p < in_end && (*p >= '0' && *p <= '9')) { hasNumber = true; p++; } if (hasNumber == false) return false; if (p < in_end) { if (*p == '.') { p++; while (p < in_end && (*p >= '0' && *p <= '9')) p++; } // floating point exponent if (p < in_end && (*p == 'e' || *p == 'E')) { p++; if (p < in_end && (*p == '+' || *p == '-')) p++; bool hasDigits = false; while (p < in_end && (*p >= '0' && *p <= '9')) { hasDigits = true; p++; } if (hasDigits == false) return false; } } out_begin = in_begin; out_end = p; return true; } static bool TokenizeLuaStylePunctuation(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end) { (void)in_end; switch (*in_begin) { case '[': case ']': case '{': case '}': case '!': case '%': case '#': case '^': case '&': case '*': case '(': case ')': case '-': case '+': case '=': case '~': case '|': case '<': case '>': case '?': case ':': case '/': case ';': case ',': case '.': out_begin = in_begin; out_end = in_begin + 1; return true; } return false; } const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::CPlusPlus() { static bool inited = false; static LanguageDefinition langDef; if (!inited) { static const char* const cppKeywords[] = { "alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel", "atomic_commit", "atomic_noexcept", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", "compl", "concept", "const", "constexpr", "const_cast", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "import", "inline", "int", "long", "module", "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast", "requires", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "synchronized", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq" }; for (auto& k : cppKeywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "abort", "abs", "acos", "asin", "atan", "atexit", "atof", "atoi", "atol", "ceil", "clock", "cosh", "ctime", "div", "exit", "fabs", "floor", "fmod", "getchar", "getenv", "isalnum", "isalpha", "isdigit", "isgraph", "ispunct", "isspace", "isupper", "kbhit", "log10", "log2", "log", "memcmp", "modf", "pow", "printf", "sprintf", "snprintf", "putchar", "putenv", "puts", "rand", "remove", "rename", "sinh", "sqrt", "srand", "strcat", "strcmp", "strerror", "time", "tolower", "toupper", "std", "string", "vector", "map", "unordered_map", "set", "unordered_set", "min", "max" }; for (auto& k : identifiers) { Identifier id; id.mDeclaration = "Built-in function"; langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); } langDef.mTokenize = [](const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end, PaletteIndex & paletteIndex) -> bool { paletteIndex = PaletteIndex::Max; while (in_begin < in_end && isascii(*in_begin) && isblank(*in_begin)) in_begin++; if (in_begin == in_end) { out_begin = in_end; out_end = in_end; paletteIndex = PaletteIndex::Default; } else if (TokenizeCStyleString(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::String; else if (TokenizeCStyleCharacterLiteral(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::CharLiteral; else if (TokenizeCStyleIdentifier(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Identifier; else if (TokenizeCStyleNumber(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Number; else if (TokenizeCStylePunctuation(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Punctuation; return paletteIndex != PaletteIndex::Max; }; langDef.mCommentStart = "/*"; langDef.mCommentEnd = "*/"; langDef.mSingleLineComment = "//"; langDef.mCaseSensitive = true; langDef.mAutoIndentation = true; langDef.mName = "C++"; inited = true; } return langDef; } #if 0 const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::HLSL() { static bool inited = false; static LanguageDefinition langDef; if (!inited) { static const char* const keywords[] = { "AppendStructuredBuffer", "asm", "asm_fragment", "BlendState", "bool", "break", "Buffer", "ByteAddressBuffer", "case", "cbuffer", "centroid", "class", "column_major", "compile", "compile_fragment", "CompileShader", "const", "continue", "ComputeShader", "ConsumeStructuredBuffer", "default", "DepthStencilState", "DepthStencilView", "discard", "do", "double", "DomainShader", "dword", "else", "export", "extern", "false", "float", "for", "fxgroup", "GeometryShader", "groupshared", "half", "Hullshader", "if", "in", "inline", "inout", "InputPatch", "int", "interface", "line", "lineadj", "linear", "LineStream", "matrix", "min16float", "min10float", "min16int", "min12int", "min16uint", "namespace", "nointerpolation", "noperspective", "NULL", "out", "OutputPatch", "packoffset", "pass", "pixelfragment", "PixelShader", "point", "PointStream", "precise", "RasterizerState", "RenderTargetView", "return", "register", "row_major", "RWBuffer", "RWByteAddressBuffer", "RWStructuredBuffer", "RWTexture1D", "RWTexture1DArray", "RWTexture2D", "RWTexture2DArray", "RWTexture3D", "sample", "sampler", "SamplerState", "SamplerComparisonState", "shared", "snorm", "stateblock", "stateblock_state", "static", "string", "struct", "switch", "StructuredBuffer", "tbuffer", "technique", "technique10", "technique11", "texture", "Texture1D", "Texture1DArray", "Texture2D", "Texture2DArray", "Texture2DMS", "Texture2DMSArray", "Texture3D", "TextureCube", "TextureCubeArray", "true", "typedef", "triangle", "triangleadj", "TriangleStream", "uint", "uniform", "unorm", "unsigned", "vector", "vertexfragment", "VertexShader", "void", "volatile", "while", "bool1","bool2","bool3","bool4","double1","double2","double3","double4", "float1", "float2", "float3", "float4", "int1", "int2", "int3", "int4", "in", "out", "inout", "uint1", "uint2", "uint3", "uint4", "dword1", "dword2", "dword3", "dword4", "half1", "half2", "half3", "half4", "float1x1","float2x1","float3x1","float4x1","float1x2","float2x2","float3x2","float4x2", "float1x3","float2x3","float3x3","float4x3","float1x4","float2x4","float3x4","float4x4", "half1x1","half2x1","half3x1","half4x1","half1x2","half2x2","half3x2","half4x2", "half1x3","half2x3","half3x3","half4x3","half1x4","half2x4","half3x4","half4x4", }; for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "abort", "abs", "acos", "all", "AllMemoryBarrier", "AllMemoryBarrierWithGroupSync", "any", "asdouble", "asfloat", "asin", "asint", "asint", "asuint", "asuint", "atan", "atan2", "ceil", "CheckAccessFullyMapped", "clamp", "clip", "cos", "cosh", "countbits", "cross", "D3DCOLORtoUBYTE4", "ddx", "ddx_coarse", "ddx_fine", "ddy", "ddy_coarse", "ddy_fine", "degrees", "determinant", "DeviceMemoryBarrier", "DeviceMemoryBarrierWithGroupSync", "distance", "dot", "dst", "errorf", "EvaluateAttributeAtCentroid", "EvaluateAttributeAtSample", "EvaluateAttributeSnapped", "exp", "exp2", "f16tof32", "f32tof16", "faceforward", "firstbithigh", "firstbitlow", "floor", "fma", "fmod", "frac", "frexp", "fwidth", "GetRenderTargetSampleCount", "GetRenderTargetSamplePosition", "GroupMemoryBarrier", "GroupMemoryBarrierWithGroupSync", "InterlockedAdd", "InterlockedAnd", "InterlockedCompareExchange", "InterlockedCompareStore", "InterlockedExchange", "InterlockedMax", "InterlockedMin", "InterlockedOr", "InterlockedXor", "isfinite", "isinf", "isnan", "ldexp", "length", "lerp", "lit", "log", "log10", "log2", "mad", "max", "min", "modf", "msad4", "mul", "noise", "normalize", "pow", "printf", "Process2DQuadTessFactorsAvg", "Process2DQuadTessFactorsMax", "Process2DQuadTessFactorsMin", "ProcessIsolineTessFactors", "ProcessQuadTessFactorsAvg", "ProcessQuadTessFactorsMax", "ProcessQuadTessFactorsMin", "ProcessTriTessFactorsAvg", "ProcessTriTessFactorsMax", "ProcessTriTessFactorsMin", "radians", "rcp", "reflect", "refract", "reversebits", "round", "rsqrt", "saturate", "sign", "sin", "sincos", "sinh", "smoothstep", "sqrt", "step", "tan", "tanh", "tex1D", "tex1D", "tex1Dbias", "tex1Dgrad", "tex1Dlod", "tex1Dproj", "tex2D", "tex2D", "tex2Dbias", "tex2Dgrad", "tex2Dlod", "tex2Dproj", "tex3D", "tex3D", "tex3Dbias", "tex3Dgrad", "tex3Dlod", "tex3Dproj", "texCUBE", "texCUBE", "texCUBEbias", "texCUBEgrad", "texCUBElod", "texCUBEproj", "transpose", "trunc" }; for (auto& k : identifiers) { Identifier id; id.mDeclaration = "Built-in function"; langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); } langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Preprocessor)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::String)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("\\'\\\\?[^\\']\\'", PaletteIndex::CharLiteral)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[\\[\\]\\{\\}\\!\\%\\^\\&\\*\\(\\)\\-\\+\\=\\~\\|\\<\\>\\?\\/\\;\\,\\.]", PaletteIndex::Punctuation)); langDef.mCommentStart = "/*"; langDef.mCommentEnd = "*/"; langDef.mSingleLineComment = "//"; langDef.mCaseSensitive = true; langDef.mAutoIndentation = true; langDef.mName = "HLSL"; inited = true; } return langDef; } const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::GLSL() { static bool inited = false; static LanguageDefinition langDef; if (!inited) { static const char* const keywords[] = { "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while", "_Alignas", "_Alignof", "_Atomic", "_Bool", "_Complex", "_Generic", "_Imaginary", "_Noreturn", "_Static_assert", "_Thread_local" }; for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "abort", "abs", "acos", "asin", "atan", "atexit", "atof", "atoi", "atol", "ceil", "clock", "cosh", "ctime", "div", "exit", "fabs", "floor", "fmod", "getchar", "getenv", "isalnum", "isalpha", "isdigit", "isgraph", "ispunct", "isspace", "isupper", "kbhit", "log10", "log2", "log", "memcmp", "modf", "pow", "putchar", "putenv", "puts", "rand", "remove", "rename", "sinh", "sqrt", "srand", "strcat", "strcmp", "strerror", "time", "tolower", "toupper" }; for (auto& k : identifiers) { Identifier id; id.mDeclaration = "Built-in function"; langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); } langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[ \\t]*#[ \\t]*[a-zA-Z_]+", PaletteIndex::Preprocessor)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::String)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("\\'\\\\?[^\\']\\'", PaletteIndex::CharLiteral)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[\\[\\]\\{\\}\\!\\%\\^\\&\\*\\(\\)\\-\\+\\=\\~\\|\\<\\>\\?\\/\\;\\,\\.]", PaletteIndex::Punctuation)); langDef.mCommentStart = "/*"; langDef.mCommentEnd = "*/"; langDef.mSingleLineComment = "//"; langDef.mCaseSensitive = true; langDef.mAutoIndentation = true; langDef.mName = "GLSL"; inited = true; } return langDef; } #endif const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::C() { static bool inited = false; static LanguageDefinition langDef; if (!inited) { static const char* const keywords[] = { "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while", "_Alignas", "_Alignof", "_Atomic", "_Bool", "_Complex", "_Generic", "_Imaginary", "_Noreturn", "_Static_assert", "_Thread_local" }; for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "abort", "abs", "acos", "asin", "atan", "atexit", "atof", "atoi", "atol", "ceil", "clock", "cosh", "ctime", "div", "exit", "fabs", "floor", "fmod", "getchar", "getenv", "isalnum", "isalpha", "isdigit", "isgraph", "ispunct", "isspace", "isupper", "kbhit", "log10", "log2", "log", "memcmp", "modf", "pow", "putchar", "putenv", "puts", "rand", "remove", "rename", "sinh", "sqrt", "srand", "strcat", "strcmp", "strerror", "time", "tolower", "toupper" }; for (auto& k : identifiers) { Identifier id; id.mDeclaration = "Built-in function"; langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); } langDef.mTokenize = [](const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end, PaletteIndex & paletteIndex) -> bool { paletteIndex = PaletteIndex::Max; while (in_begin < in_end && isascii(*in_begin) && isblank(*in_begin)) in_begin++; if (in_begin == in_end) { out_begin = in_end; out_end = in_end; paletteIndex = PaletteIndex::Default; } else if (TokenizeCStyleString(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::String; else if (TokenizeCStyleCharacterLiteral(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::CharLiteral; else if (TokenizeCStyleIdentifier(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Identifier; else if (TokenizeCStyleNumber(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Number; else if (TokenizeCStylePunctuation(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Punctuation; return paletteIndex != PaletteIndex::Max; }; langDef.mCommentStart = "/*"; langDef.mCommentEnd = "*/"; langDef.mSingleLineComment = "//"; langDef.mCaseSensitive = true; langDef.mAutoIndentation = true; langDef.mName = "C"; inited = true; } return langDef; } const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::VIAMD() { static bool inited = false; static LanguageDefinition langDef; if (!inited) { static const char* const keywords[] = { "and", "or", "not", "in", "out" }; for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "sqrt", "cbrt", "abs", "floor", "ceil", "cos", "sin", "asin", "acos", "atan", "log", "exp", "log2", "exp2", "log10", "atan", "atan2", "pow", "dot", "cross", "mul", "vec2", "vec3", "vec4", "atoms", "residues", "chains", "all", "type", "name", "label", "element", "atom", "resname", "residue", "resid", "chain", "x", "y", "z", "within", "distance", "distance_min", "distance_max", "distance_pair", "angle", "dihedral", "rmsd", "rdf", "sdf", "com", "plane" }; for (auto& k : identifiers) { Identifier id; id.mDeclaration = "Built-in function"; langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); } langDef.mTokenize = [](const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end, PaletteIndex & paletteIndex) -> bool { paletteIndex = PaletteIndex::Max; while (in_begin < in_end && isascii(*in_begin) && isblank(*in_begin)) in_begin++; if (in_begin == in_end) { out_begin = in_end; out_end = in_end; paletteIndex = PaletteIndex::Default; } else if (TokenizeCStyleString(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::String; else if (TokenizeCStyleCharacterLiteral(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::CharLiteral; else if (TokenizeCStyleIdentifier(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Identifier; else if (TokenizeCStyleNumber(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Number; else if (TokenizeCStylePunctuation(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Punctuation; return paletteIndex != PaletteIndex::Max; }; langDef.mPreprocChar = -1; langDef.mSingleLineComment = "#"; langDef.mCommentStart = "AHusihdaushdy/(Y12hdjihas78dyhasuihdjn"; langDef.mCommentEnd = "AHusihdaushdy/(Y12hdjihas78dyhasuihdjn"; langDef.mCaseSensitive = true; langDef.mAutoIndentation = true; langDef.mName = "VIAMD"; inited = true; } return langDef; } #if 0 const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::SQL() { static bool inited = false; static LanguageDefinition langDef; if (!inited) { static const char* const keywords[] = { "ADD", "EXCEPT", "PERCENT", "ALL", "EXEC", "PLAN", "ALTER", "EXECUTE", "PRECISION", "AND", "EXISTS", "PRIMARY", "ANY", "EXIT", "PRINT", "AS", "FETCH", "PROC", "ASC", "FILE", "PROCEDURE", "AUTHORIZATION", "FILLFACTOR", "PUBLIC", "BACKUP", "FOR", "RAISERROR", "BEGIN", "FOREIGN", "READ", "BETWEEN", "FREETEXT", "READTEXT", "BREAK", "FREETEXTTABLE", "RECONFIGURE", "BROWSE", "FROM", "REFERENCES", "BULK", "FULL", "REPLICATION", "BY", "FUNCTION", "RESTORE", "CASCADE", "GOTO", "RESTRICT", "CASE", "GRANT", "RETURN", "CHECK", "GROUP", "REVOKE", "CHECKPOINT", "HAVING", "RIGHT", "CLOSE", "HOLDLOCK", "ROLLBACK", "CLUSTERED", "IDENTITY", "ROWCOUNT", "COALESCE", "IDENTITY_INSERT", "ROWGUIDCOL", "COLLATE", "IDENTITYCOL", "RULE", "COLUMN", "IF", "SAVE", "COMMIT", "IN", "SCHEMA", "COMPUTE", "INDEX", "SELECT", "CONSTRAINT", "INNER", "SESSION_USER", "CONTAINS", "INSERT", "SET", "CONTAINSTABLE", "INTERSECT", "SETUSER", "CONTINUE", "INTO", "SHUTDOWN", "CONVERT", "IS", "SOME", "CREATE", "JOIN", "STATISTICS", "CROSS", "KEY", "SYSTEM_USER", "CURRENT", "KILL", "TABLE", "CURRENT_DATE", "LEFT", "TEXTSIZE", "CURRENT_TIME", "LIKE", "THEN", "CURRENT_TIMESTAMP", "LINENO", "TO", "CURRENT_USER", "LOAD", "TOP", "CURSOR", "NATIONAL", "TRAN", "DATABASE", "NOCHECK", "TRANSACTION", "DBCC", "NONCLUSTERED", "TRIGGER", "DEALLOCATE", "NOT", "TRUNCATE", "DECLARE", "NULL", "TSEQUAL", "DEFAULT", "NULLIF", "UNION", "DELETE", "OF", "UNIQUE", "DENY", "OFF", "UPDATE", "DESC", "OFFSETS", "UPDATETEXT", "DISK", "ON", "USE", "DISTINCT", "OPEN", "USER", "DISTRIBUTED", "OPENDATASOURCE", "VALUES", "DOUBLE", "OPENQUERY", "VARYING","DROP", "OPENROWSET", "VIEW", "DUMMY", "OPENXML", "WAITFOR", "DUMP", "OPTION", "WHEN", "ELSE", "OR", "WHERE", "END", "ORDER", "WHILE", "ERRLVL", "OUTER", "WITH", "ESCAPE", "OVER", "WRITETEXT" }; for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "ABS", "ACOS", "ADD_MONTHS", "ASCII", "ASCIISTR", "ASIN", "ATAN", "ATAN2", "AVG", "BFILENAME", "BIN_TO_NUM", "BITAND", "CARDINALITY", "CASE", "CAST", "CEIL", "CHARTOROWID", "CHR", "COALESCE", "COMPOSE", "CONCAT", "CONVERT", "CORR", "COS", "COSH", "COUNT", "COVAR_POP", "COVAR_SAMP", "CUME_DIST", "CURRENT_DATE", "CURRENT_TIMESTAMP", "DBTIMEZONE", "DECODE", "DECOMPOSE", "DENSE_RANK", "DUMP", "EMPTY_BLOB", "EMPTY_CLOB", "EXP", "EXTRACT", "FIRST_VALUE", "FLOOR", "FROM_TZ", "GREATEST", "GROUP_ID", "HEXTORAW", "INITCAP", "INSTR", "INSTR2", "INSTR4", "INSTRB", "INSTRC", "LAG", "LAST_DAY", "LAST_VALUE", "LEAD", "LEAST", "LENGTH", "LENGTH2", "LENGTH4", "LENGTHB", "LENGTHC", "LISTAGG", "LN", "LNNVL", "LOCALTIMESTAMP", "LOG", "LOWER", "LPAD", "LTRIM", "MAX", "MEDIAN", "MIN", "MOD", "MONTHS_BETWEEN", "NANVL", "NCHR", "NEW_TIME", "NEXT_DAY", "NTH_VALUE", "NULLIF", "NUMTODSINTERVAL", "NUMTOYMINTERVAL", "NVL", "NVL2", "POWER", "RANK", "RAWTOHEX", "REGEXP_COUNT", "REGEXP_INSTR", "REGEXP_REPLACE", "REGEXP_SUBSTR", "REMAINDER", "REPLACE", "ROUND", "ROWNUM", "RPAD", "RTRIM", "SESSIONTIMEZONE", "SIGN", "SIN", "SINH", "SOUNDEX", "SQRT", "STDDEV", "SUBSTR", "SUM", "SYS_CONTEXT", "SYSDATE", "SYSTIMESTAMP", "TAN", "TANH", "TO_CHAR", "TO_CLOB", "TO_DATE", "TO_DSINTERVAL", "TO_LOB", "TO_MULTI_BYTE", "TO_NCLOB", "TO_NUMBER", "TO_SINGLE_BYTE", "TO_TIMESTAMP", "TO_TIMESTAMP_TZ", "TO_YMINTERVAL", "TRANSLATE", "TRIM", "TRUNC", "TZ_OFFSET", "UID", "UPPER", "USER", "USERENV", "VAR_POP", "VAR_SAMP", "VARIANCE", "VSIZE " }; for (auto& k : identifiers) { Identifier id; id.mDeclaration = "Built-in function"; langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); } langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::String)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("\\\'[^\\\']*\\\'", PaletteIndex::String)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[\\[\\]\\{\\}\\!\\%\\^\\&\\*\\(\\)\\-\\+\\=\\~\\|\\<\\>\\?\\/\\;\\,\\.]", PaletteIndex::Punctuation)); langDef.mCommentStart = "/*"; langDef.mCommentEnd = "*/"; langDef.mSingleLineComment = "//"; langDef.mCaseSensitive = false; langDef.mAutoIndentation = false; langDef.mName = "SQL"; inited = true; } return langDef; } const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::AngelScript() { static bool inited = false; static LanguageDefinition langDef; if (!inited) { static const char* const keywords[] = { "and", "abstract", "auto", "bool", "break", "case", "cast", "class", "const", "continue", "default", "do", "double", "else", "enum", "false", "final", "float", "for", "from", "funcdef", "function", "get", "if", "import", "in", "inout", "int", "interface", "int8", "int16", "int32", "int64", "is", "mixin", "namespace", "not", "null", "or", "out", "override", "private", "protected", "return", "set", "shared", "super", "switch", "this ", "true", "typedef", "uint", "uint8", "uint16", "uint32", "uint64", "void", "while", "xor" }; for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "cos", "sin", "tab", "acos", "asin", "atan", "atan2", "cosh", "sinh", "tanh", "log", "log10", "pow", "sqrt", "abs", "ceil", "floor", "fraction", "closeTo", "fpFromIEEE", "fpToIEEE", "complex", "opEquals", "opAddAssign", "opSubAssign", "opMulAssign", "opDivAssign", "opAdd", "opSub", "opMul", "opDiv" }; for (auto& k : identifiers) { Identifier id; id.mDeclaration = "Built-in function"; langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); } langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("L?\\\"(\\\\.|[^\\\"])*\\\"", PaletteIndex::String)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("\\'\\\\?[^\\']\\'", PaletteIndex::String)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[+-]?[0-9]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("0[0-7]+[Uu]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?", PaletteIndex::Number)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[a-zA-Z_][a-zA-Z0-9_]*", PaletteIndex::Identifier)); langDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>("[\\[\\]\\{\\}\\!\\%\\^\\&\\*\\(\\)\\-\\+\\=\\~\\|\\<\\>\\?\\/\\;\\,\\.]", PaletteIndex::Punctuation)); langDef.mCommentStart = "/*"; langDef.mCommentEnd = "*/"; langDef.mSingleLineComment = "//"; langDef.mCaseSensitive = true; langDef.mAutoIndentation = true; langDef.mName = "AngelScript"; inited = true; } return langDef; } #endif const TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::Lua() { static bool inited = false; static LanguageDefinition langDef; if (!inited) { static const char* const keywords[] = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" }; for (auto& k : keywords) langDef.mKeywords.insert(k); static const char* const identifiers[] = { "assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs", "loadfile", "load", "loadstring", "next", "pairs", "pcall", "print", "rawequal", "rawlen", "rawget", "rawset", "select", "setmetatable", "tonumber", "tostring", "type", "xpcall", "_G", "_VERSION","arshift", "band", "bnot", "bor", "bxor", "btest", "extract", "lrotate", "lshift", "replace", "rrotate", "rshift", "create", "resume", "running", "status", "wrap", "yield", "isyieldable", "debug","getuservalue", "gethook", "getinfo", "getlocal", "getregistry", "getmetatable", "getupvalue", "upvaluejoin", "upvalueid", "setuservalue", "sethook", "setlocal", "setmetatable", "setupvalue", "traceback", "close", "flush", "input", "lines", "open", "output", "popen", "read", "tmpfile", "type", "write", "close", "flush", "lines", "read", "seek", "setvbuf", "write", "__gc", "__tostring", "abs", "acos", "asin", "atan", "ceil", "cos", "deg", "exp", "tointeger", "floor", "fmod", "ult", "log", "max", "min", "modf", "rad", "random", "randomseed", "sin", "sqrt", "string", "tan", "type", "atan2", "cosh", "sinh", "tanh", "pow", "frexp", "ldexp", "log10", "pi", "huge", "maxinteger", "mininteger", "loadlib", "searchpath", "seeall", "preload", "cpath", "path", "searchers", "loaded", "module", "require", "clock", "date", "difftime", "execute", "exit", "getenv", "remove", "rename", "setlocale", "time", "tmpname", "byte", "char", "dump", "find", "format", "gmatch", "gsub", "len", "lower", "match", "rep", "reverse", "sub", "upper", "pack", "packsize", "unpack", "concat", "maxn", "insert", "pack", "unpack", "remove", "move", "sort", "offset", "codepoint", "char", "len", "codes", "charpattern", "coroutine", "table", "io", "os", "string", "utf8", "bit32", "math", "debug", "package" }; for (auto& k : identifiers) { Identifier id; id.mDeclaration = "Built-in function"; langDef.mIdentifiers.insert(std::make_pair(std::string(k), id)); } langDef.mTokenize = [](const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end, PaletteIndex & paletteIndex) -> bool { paletteIndex = PaletteIndex::Max; while (in_begin < in_end && isascii(*in_begin) && isblank(*in_begin)) in_begin++; if (in_begin == in_end) { out_begin = in_end; out_end = in_end; paletteIndex = PaletteIndex::Default; } else if (TokenizeLuaStyleString(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::String; else if (TokenizeLuaStyleIdentifier(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Identifier; else if (TokenizeLuaStyleNumber(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Number; else if (TokenizeLuaStylePunctuation(in_begin, in_end, out_begin, out_end)) paletteIndex = PaletteIndex::Punctuation; return paletteIndex != PaletteIndex::Max; }; langDef.mCommentStart = "--[["; langDef.mCommentEnd = "]]"; langDef.mSingleLineComment = "--"; langDef.mCaseSensitive = true; langDef.mAutoIndentation = false; langDef.mName = "Lua"; inited = true; } return langDef; }
0
0.90906
1
0.90906
game-dev
MEDIA
0.367778
game-dev
0.974415
1
0.974415
bates64/papermario-dx
8,997
src/trigger.c
#include "common.h" #include "vars_access.h" s16 gTriggerCount; BSS TriggerList wTriggerList; BSS TriggerList bTriggerList; BSS TriggerList* gCurrentTriggerListPtr; void default_trigger_on_activate(Trigger* self) { self->flags |= TRIGGER_ACTIVATED; } void clear_trigger_data(void) { CollisionStatus* collisionStatus = &gCollisionStatus; s32 i; if (gGameStatusPtr->context == CONTEXT_WORLD) { gCurrentTriggerListPtr = &wTriggerList; } else { gCurrentTriggerListPtr = &bTriggerList; } for (i = 0; i < ARRAY_COUNT(*gCurrentTriggerListPtr); i++) { (*gCurrentTriggerListPtr)[i] = NULL; } gTriggerCount = 0; collisionStatus->pushingAgainstWall = NO_COLLIDER; collisionStatus->curFloor = NO_COLLIDER; collisionStatus->lastTouchedFloor = NO_COLLIDER; collisionStatus->curCeiling = NO_COLLIDER; collisionStatus->curInspect = NO_COLLIDER; collisionStatus->unk_0C = -1; collisionStatus->unk_0E = -1; collisionStatus->unk_10 = -1; collisionStatus->curWall = NO_COLLIDER; collisionStatus->lastWallHammered = NO_COLLIDER; collisionStatus->touchingWallTrigger = 0; collisionStatus->bombetteExploded = -1; collisionStatus->bombetteExplosionPos.x = 0.0f; collisionStatus->bombetteExplosionPos.y = 0.0f; collisionStatus->bombetteExplosionPos.z = 0.0f; } void init_trigger_list(void) { if (gGameStatusPtr->context == CONTEXT_WORLD) { gCurrentTriggerListPtr = &wTriggerList; } else { gCurrentTriggerListPtr = &bTriggerList; } gTriggerCount = 0; } Trigger* create_trigger(TriggerBlueprint* bp) { Trigger* trigger; s32 i; for (i = 0; i < ARRAY_COUNT(*gCurrentTriggerListPtr); i++) { Trigger* listTrigger = (*gCurrentTriggerListPtr)[i]; if (listTrigger == NULL) { break; } } ASSERT(i < ARRAY_COUNT(*gCurrentTriggerListPtr)); (*gCurrentTriggerListPtr)[i] = trigger = heap_malloc(sizeof(*trigger)); gTriggerCount++; ASSERT(trigger != NULL); trigger->flags = bp->flags | TRIGGER_ACTIVE; trigger->varIndex = bp->varIndex; trigger->location.colliderID = bp->colliderID; trigger->itemList = bp->itemList; trigger->tattleMsg = bp->tattleMsg; trigger->hasPlayerInteractPrompt = bp->hasPlayerInteractPrompt; trigger->onActivateFunc = bp->onActivateFunc; if (trigger->onActivateFunc == NULL) { trigger->onActivateFunc = (s32 (*) (Trigger*)) default_trigger_on_activate; } return trigger; } void update_triggers(void) { CollisionStatus* collisionStatus = &gCollisionStatus; Trigger* listTrigger; s32 i; collisionStatus->touchingWallTrigger = 0; for (i = 0; i < ARRAY_COUNT(*gCurrentTriggerListPtr); i++) { listTrigger = (*gCurrentTriggerListPtr)[i]; if (listTrigger == NULL) { continue; } if (!(listTrigger->flags & TRIGGER_ACTIVE)) { continue; } if (listTrigger->flags & TRIGGER_FORCE_ACTIVATE) { listTrigger->flags |= TRIGGER_ACTIVATED; continue; } if (listTrigger->flags & TRIGGER_WALL_PUSH) { if (listTrigger->location.colliderID == collisionStatus->curWall) { func_800E06C0(1); } if (listTrigger->location.colliderID == collisionStatus->pushingAgainstWall) { func_800E06C0(0); } else { continue; } } if (listTrigger->flags & TRIGGER_FLOOR_TOUCH) { if (listTrigger->location.colliderID != collisionStatus->curFloor) { continue; } } if (listTrigger->flags & TRIGGER_FLOOR_ABOVE) { if (listTrigger->location.colliderID != collisionStatus->floorBelow) { continue; } } if (listTrigger->flags & TRIGGER_WALL_PRESS_A) { if (listTrigger->location.colliderID == collisionStatus->curWall) { collisionStatus->touchingWallTrigger = 1; } if ((listTrigger->location.colliderID != collisionStatus->curInspect) || !phys_can_player_interact()) { continue; } } if (listTrigger->flags & TRIGGER_WALL_TOUCH) { if (listTrigger->location.colliderID != collisionStatus->curWall) { continue; } } if (listTrigger->flags & TRIGGER_FLOOR_JUMP) { if (listTrigger->location.colliderID != collisionStatus->lastTouchedFloor) { continue; } } if (listTrigger->flags & TRIGGER_FLOOR_PRESS_A) { if ((listTrigger->location.colliderID != collisionStatus->curFloor) || !(gGameStatusPtr->pressedButtons[0] & BUTTON_A) || (gPlayerStatus.flags & PS_FLAG_INPUT_DISABLED)) { continue; } } if (listTrigger->flags & TRIGGER_WALL_HAMMER) { if (listTrigger->location.colliderID != collisionStatus->lastWallHammered) { continue; } } if (listTrigger->flags & TRIGGER_CEILING_TOUCH) { if (listTrigger->location.colliderID != collisionStatus->curCeiling) { continue; } } if (listTrigger->flags & TRIGGER_FLAG_2000) { if (listTrigger->location.colliderID != collisionStatus->unk_0C) { continue; } } if (listTrigger->flags & TRIGGER_FLAG_4000) { if (listTrigger->location.colliderID != collisionStatus->unk_0E) { continue; } } if (listTrigger->flags & TRIGGER_FLAG_8000) { if (listTrigger->location.colliderID != collisionStatus->unk_10) { continue; } } if (listTrigger->flags & TRIGGER_POINT_BOMB) { BombTrigger* bombPos; f32 dist; if (collisionStatus->bombetteExploded < 0) { continue; } bombPos = listTrigger->location.blast; dist = dist3D(bombPos->pos.x, bombPos->pos.y, bombPos->pos.z, collisionStatus->bombetteExplosionPos.x, collisionStatus->bombetteExplosionPos.y, collisionStatus->bombetteExplosionPos.z); if ((bombPos->diameter * 0.5f) + 50.0f < dist) { continue; } } if (listTrigger->flags & TRIGGER_GAME_FLAG_SET && get_global_flag(listTrigger->varIndex) == 0) { continue; } if (listTrigger->flags & TRIGGER_AREA_FLAG_SET && get_area_flag(listTrigger->varIndex) == 0) { continue; } listTrigger->flags |= TRIGGER_ACTIVATED; } for (i = 0; i < ARRAY_COUNT(*gCurrentTriggerListPtr); i++) { listTrigger = (*gCurrentTriggerListPtr)[i]; if (listTrigger == NULL) { continue; } if (listTrigger->flags & TRIGGER_ACTIVE) { if (listTrigger->flags & TRIGGER_ACTIVATED) { if (listTrigger->onActivateFunc(listTrigger) == 0) { listTrigger->flags &= ~TRIGGER_ACTIVATED; } } } } } void delete_trigger(Trigger* toDelete) { s32 i; for (i = 0; i < ARRAY_COUNT(*gCurrentTriggerListPtr); i++) { if ((*gCurrentTriggerListPtr)[i] == toDelete) { break; } } if (i < ARRAY_COUNT(*gCurrentTriggerListPtr)) { heap_free((*gCurrentTriggerListPtr)[i]); (*gCurrentTriggerListPtr)[i] = NULL; } } s32 is_another_trigger_bound(Trigger* trigger, EvtScript* script) { s32 i; for (i = 0; i < ARRAY_COUNT(*gCurrentTriggerListPtr); i++) { Trigger* listTrigger = (*gCurrentTriggerListPtr)[i]; if (listTrigger == NULL || listTrigger == trigger) { continue; } if (listTrigger->flags & TRIGGER_ACTIVE) { if (listTrigger->flags & TRIGGER_ACTIVATED) { if (listTrigger->onTriggerEvt == script) { return TRUE; } } } } return FALSE; } Trigger* get_trigger_by_id(s32 triggerID) { return (*gCurrentTriggerListPtr)[triggerID]; } /// @returns TRUE if colliderID is bound to an interaction trigger (press A) and the player can use it. s32 should_collider_allow_interact(s32 colliderID) { s32 i; if (!phys_can_player_interact()) { return FALSE; } for (i = 0; i < ARRAY_COUNT(*gCurrentTriggerListPtr); i++) { Trigger* trigger = (*gCurrentTriggerListPtr)[i]; if (trigger != NULL && trigger->hasPlayerInteractPrompt != 0 && trigger->location.colliderID == colliderID && trigger->flags & TRIGGER_WALL_PRESS_A ) { return TRUE; } } return FALSE; }
0
0.898586
1
0.898586
game-dev
MEDIA
0.878922
game-dev
0.815114
1
0.815114
pagefaultgames/pokerogue
8,547
test/moves/protect.test.ts
import { allMoves } from "#data/data-lists"; import { AbilityId } from "#enums/ability-id"; import { BattlerIndex } from "#enums/battler-index"; import { MoveId } from "#enums/move-id"; import { MoveResult } from "#enums/move-result"; import { MoveUseMode } from "#enums/move-use-mode"; import { SpeciesId } from "#enums/species-id"; import { Stat } from "#enums/stat"; import { GameManager } from "#test/test-utils/game-manager"; import Phaser from "phaser"; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; describe("Moves - Protect", () => { let phaserGame: Phaser.Game; let game: GameManager; beforeAll(() => { phaserGame = new Phaser.Game({ type: Phaser.HEADLESS, }); }); afterEach(() => { game.phaseInterceptor.restoreOg(); }); beforeEach(() => { game = new GameManager(phaserGame); game.override .battleStyle("single") .moveset([MoveId.PROTECT, MoveId.SPIKY_SHIELD, MoveId.ENDURE, MoveId.SPLASH]) .enemySpecies(SpeciesId.SNORLAX) .enemyAbility(AbilityId.INSOMNIA) .enemyMoveset(MoveId.LUMINA_CRASH) .startingLevel(100) .enemyLevel(100); }); it("should protect the user from attacks and their secondary effects", async () => { await game.classicMode.startBattle([SpeciesId.CHARIZARD]); const charizard = game.field.getPlayerPokemon(); game.move.select(MoveId.PROTECT); await game.phaseInterceptor.to("BerryPhase", false); expect(charizard.hp).toBe(charizard.getMaxHp()); expect(charizard.getStatStage(Stat.SPDEF)).toBe(0); expect(charizard); }); it.each<{ numTurns: number; chance: number }>([ { numTurns: 1, chance: 3 }, { numTurns: 2, chance: 9 }, { numTurns: 3, chance: 27 }, { numTurns: 4, chance: 81 }, ])("should have a 1/$chance success rate after $numTurns successful uses", async ({ numTurns, chance }) => { await game.classicMode.startBattle([SpeciesId.CHARIZARD]); const charizard = game.scene.getPlayerPokemon()!; // mock RNG roll to suceed unless exactly the desired chance is hit vi.spyOn(charizard, "randBattleSeedInt").mockImplementation(range => (range !== chance ? 0 : 1)); const conditionSpy = vi.spyOn(allMoves[MoveId.PROTECT]["conditions"][0], "apply"); // click protect many times for (let x = 0; x < numTurns; x++) { game.move.select(MoveId.PROTECT); await game.toNextTurn(); expect(charizard.hp).toBe(charizard.getMaxHp()); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.SUCCESS); expect(conditionSpy).toHaveLastReturnedWith(true); } game.move.select(MoveId.PROTECT); await game.toNextTurn(); expect(charizard.hp).toBeLessThan(charizard.getMaxHp()); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.FAIL); expect(conditionSpy).toHaveLastReturnedWith(false); }); it("should share fail chance with all move variants", async () => { await game.classicMode.startBattle([SpeciesId.CHARIZARD]); const charizard = game.field.getPlayerPokemon(); charizard.summonData.moveHistory = [ { move: MoveId.ENDURE, result: MoveResult.SUCCESS, targets: [BattlerIndex.PLAYER], useMode: MoveUseMode.NORMAL }, { move: MoveId.SPIKY_SHIELD, result: MoveResult.SUCCESS, targets: [BattlerIndex.PLAYER], useMode: MoveUseMode.NORMAL, }, ]; // force protect to fail on anything >=2 uses (1/9 chance) vi.spyOn(charizard, "randBattleSeedInt").mockImplementation(range => (range >= 9 ? 1 : 0)); game.move.select(MoveId.PROTECT); await game.toNextTurn(); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.FAIL); }); it("should reset fail chance on move failure", async () => { await game.classicMode.startBattle([SpeciesId.CHARIZARD]); const charizard = game.scene.getPlayerPokemon()!; // force protect to always fail if RNG roll attempt is made vi.spyOn(charizard, "randBattleSeedInt").mockReturnValue(1); game.move.select(MoveId.PROTECT); await game.toNextTurn(); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.SUCCESS); game.move.select(MoveId.SPIKY_SHIELD); await game.toNextTurn(); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.FAIL); game.move.select(MoveId.SPIKY_SHIELD); await game.toNextTurn(); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.SUCCESS); }); it("should reset fail chance on using another move", async () => { await game.classicMode.startBattle([SpeciesId.CHARIZARD]); const charizard = game.scene.getPlayerPokemon()!; // force protect to always fail if RNG roll attempt is made vi.spyOn(charizard, "randBattleSeedInt").mockReturnValue(1); game.move.select(MoveId.PROTECT); await game.toNextTurn(); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.SUCCESS); game.move.select(MoveId.SPLASH); await game.toNextTurn(); game.move.select(MoveId.PROTECT); await game.toNextTurn(); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.SUCCESS); }); it("should reset fail chance on starting a new wave", async () => { await game.classicMode.startBattle([SpeciesId.CHARIZARD]); const charizard = game.field.getPlayerPokemon(); // force protect to always fail if RNG roll attempt is made vi.spyOn(charizard, "randBattleSeedInt").mockReturnValue(1); game.move.select(MoveId.PROTECT); // Wait until move end phase to kill opponent to ensure protect doesn't fail due to going last await game.phaseInterceptor.to("MoveEndPhase"); await game.doKillOpponents(); await game.toNextWave(); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.SUCCESS); game.move.select(MoveId.SPIKY_SHIELD); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.SUCCESS); }); it("should not be blocked by Psychic Terrain", async () => { game.override.ability(AbilityId.PSYCHIC_SURGE); await game.classicMode.startBattle([SpeciesId.CHARIZARD]); const charizard = game.scene.getPlayerPokemon()!; game.move.select(MoveId.PROTECT); await game.toNextTurn(); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.SUCCESS); }); it("should stop subsequent hits of multi-hit moves", async () => { game.override.enemyMoveset([MoveId.TACHYON_CUTTER]); await game.classicMode.startBattle([SpeciesId.CHARIZARD]); const charizard = game.field.getPlayerPokemon(); const enemyPokemon = game.field.getEnemyPokemon(); game.move.select(MoveId.PROTECT); await game.phaseInterceptor.to("BerryPhase", false); expect(charizard.hp).toBe(charizard.getMaxHp()); expect(enemyPokemon.turnData.hitCount).toBe(1); }); it("should fail if the user moves last in the turn", async () => { game.override.enemyMoveset(MoveId.PROTECT); await game.classicMode.startBattle([SpeciesId.CHARIZARD]); const charizard = game.field.getPlayerPokemon(); const enemyPokemon = game.field.getEnemyPokemon(); game.move.select(MoveId.PROTECT); await game.setTurnOrder([BattlerIndex.ENEMY, BattlerIndex.PLAYER]); await game.phaseInterceptor.to("BerryPhase", false); expect(enemyPokemon.getLastXMoves()[0].result).toBe(MoveResult.SUCCESS); expect(charizard.getLastXMoves()[0].result).toBe(MoveResult.FAIL); }); it("should not block Protection-bypassing moves or Future Sight", async () => { game.override.enemyMoveset([MoveId.FUTURE_SIGHT, MoveId.MIGHTY_CLEAVE, MoveId.SPORE]); await game.classicMode.startBattle([SpeciesId.AGGRON]); const aggron = game.scene.getPlayerPokemon()!; vi.spyOn(aggron, "randBattleSeedInt").mockReturnValue(0); // Turn 1: setup future sight game.move.select(MoveId.PROTECT); await game.move.forceEnemyMove(MoveId.FUTURE_SIGHT); await game.toNextTurn(); // Turn 2: mighty cleave game.move.select(MoveId.PROTECT); await game.move.forceEnemyMove(MoveId.MIGHTY_CLEAVE); await game.toNextTurn(); expect(aggron.hp).toBeLessThan(aggron.getMaxHp()); aggron.hp = aggron.getMaxHp(); // turn 3: Future Sight hits game.move.select(MoveId.PROTECT); await game.move.forceEnemyMove(MoveId.SPORE); await game.toNextTurn(); expect(aggron.hp).toBeLessThan(aggron.getMaxHp()); expect(aggron.status?.effect).toBeUndefined(); // check that protect actually worked }); // TODO: Add test it.todo("should not reset counter when throwing balls"); });
0
0.938094
1
0.938094
game-dev
MEDIA
0.966007
game-dev
0.980988
1
0.980988
IrvKalb/Object-Oriented-Python-Code
2,690
Chapter_15/RockPaperScissorsWithScenes/ScenePlay.py
# The Play scene # The player chooses among rock, paper, or scissors import pygwidgets import pyghelpers import pygame from Constants import * import random class ScenePlay(pyghelpers.Scene): def __init__(self, window): self.window = window self.RPSTuple = (ROCK, PAPER, SCISSORS) self.titleField = pygwidgets.DisplayText(self.window, (15, 40), ' Rock Paper Scissors', fontSize=50, textColor=WHITE, width=610, justified='center') self.messageField = pygwidgets.DisplayText(self.window, (30, 395), 'Choose!', fontSize=50, textColor=WHITE, width=610, justified='center') self.rockButton = pygwidgets.CustomButton(self.window, (25, 120), up="images/Rock.png", over="images/RockOver.png", down="images/RockDown.png") self.paperButton = pygwidgets.CustomButton(self.window, (225, 120), up="images/Paper.png", over="images/PaperOver.png", down="images/PaperDown.png") self.scissorButton = pygwidgets.CustomButton(self.window, (425, 120), up="images/Scissors.png", over="images/ScissorsOver.png", down="images/ScissorsDown.png") def getSceneKey(self): return SCENE_PLAY def handleInputs(self, eventsList, keyPressedList): playerChoice = None for event in eventsList: if self.rockButton.handleEvent(event): playerChoice = ROCK if self.paperButton.handleEvent(event): playerChoice = PAPER if self.scissorButton.handleEvent(event): playerChoice = SCISSORS if playerChoice is not None: # user has made a choice computerChoice = random.choice(self.RPSTuple) # computer chooses dataDict = {'player': playerChoice, 'computer': computerChoice} self.goToScene(SCENE_RESULTS, dataDict) # go to Results scene # No need to include update method, defaults to inherited one which does nothing def draw(self): self.window.fill(GRAY) self.titleField.draw() self.rockButton.draw() self.paperButton.draw() self.scissorButton.draw() self.messageField.draw()
0
0.679968
1
0.679968
game-dev
MEDIA
0.920598
game-dev
0.805523
1
0.805523
OreCruncher/DynamicSurroundings
2,405
src/main/java/org/orecruncher/dsurround/client/handlers/fog/HolisticFogColorCalculator.java
/* * This file is part of Dynamic Surroundings, licensed under the MIT License (MIT). * * Copyright (c) OreCruncher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.orecruncher.dsurround.client.handlers.fog; import javax.annotation.Nonnull; import org.orecruncher.lib.Color; import org.orecruncher.lib.collections.ObjectArray; import net.minecraftforge.client.event.EntityViewRenderEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class HolisticFogColorCalculator implements IFogColorCalculator { protected ObjectArray<IFogColorCalculator> calculators = new ObjectArray<>(4); protected Color cached; public void add(@Nonnull final IFogColorCalculator calc) { this.calculators.add(calc); } @Nonnull @Override public Color calculate(@Nonnull final EntityViewRenderEvent.FogColors event) { Color result = null; for (int i = 0; i < this.calculators.size(); i++) { final Color color = this.calculators.get(i).calculate(event); if (result == null) result = color; else result = result.mix(color); } return this.cached = result; } @Override public void tick() { this.calculators.forEach(IFogColorCalculator::tick); } @Override public String toString() { return this.cached != null ? this.cached.toString() : "<NOT SET>"; } }
0
0.683874
1
0.683874
game-dev
MEDIA
0.629877
game-dev
0.957724
1
0.957724
sezero/uhexen2
10,917
gamecode/hc-unused/siege/soldier.hc
/* * $Header: /HexenWorld/Siege/Soldier.hc 3 5/25/98 1:39p Mgummelt $ */ /* ============================================================================== SOLDIER / PLAYER ============================================================================== */ $cd id1/models/soldier3 $origin 0 -6 24 $base base $skin skin $frame stand1 stand2 stand3 stand4 stand5 stand6 stand7 stand8 $frame death1 death2 death3 death4 death5 death6 death7 death8 $frame death9 death10 $frame deathc1 deathc2 deathc3 deathc4 deathc5 deathc6 deathc7 deathc8 $frame deathc9 deathc10 deathc11 $frame load1 load2 load3 load4 load5 load6 load7 load8 load9 load10 load11 $frame pain1 pain2 pain3 pain4 pain5 pain6 $frame painb1 painb2 painb3 painb4 painb5 painb6 painb7 painb8 painb9 painb10 $frame painb11 painb12 painb13 painb14 $frame painc1 painc2 painc3 painc4 painc5 painc6 painc7 painc8 painc9 painc10 $frame painc11 painc12 painc13 $frame run1 run2 run3 run4 run5 run6 run7 run8 $frame shoot1 shoot2 shoot3 shoot4 shoot5 shoot6 shoot7 shoot8 shoot9 $frame prowl_1 prowl_2 prowl_3 prowl_4 prowl_5 prowl_6 prowl_7 prowl_8 $frame prowl_9 prowl_10 prowl_11 prowl_12 prowl_13 prowl_14 prowl_15 prowl_16 $frame prowl_17 prowl_18 prowl_19 prowl_20 prowl_21 prowl_22 prowl_23 prowl_24 /* ============================================================================== SOLDIER CODE ============================================================================== */ void() army_fire; void() army_stand1 =[ $stand1, army_stand2 ] {ai_stand();}; void() army_stand2 =[ $stand2, army_stand3 ] {ai_stand();}; void() army_stand3 =[ $stand3, army_stand4 ] {ai_stand();}; void() army_stand4 =[ $stand4, army_stand5 ] {ai_stand();}; void() army_stand5 =[ $stand5, army_stand6 ] {ai_stand();}; void() army_stand6 =[ $stand6, army_stand7 ] {ai_stand();}; void() army_stand7 =[ $stand7, army_stand8 ] {ai_stand();}; void() army_stand8 =[ $stand8, army_stand1 ] {ai_stand();}; void() army_walk1 =[ $prowl_1, army_walk2 ] { if (random() < 0.2) sound (self, CHAN_VOICE, "soldier/idle.wav", 1, ATTN_IDLE); ai_walk(1);}; void() army_walk2 =[ $prowl_2, army_walk3 ] {ai_walk(1);}; void() army_walk3 =[ $prowl_3, army_walk4 ] {ai_walk(1);}; void() army_walk4 =[ $prowl_4, army_walk5 ] {ai_walk(1);}; void() army_walk5 =[ $prowl_5, army_walk6 ] {ai_walk(2);}; void() army_walk6 =[ $prowl_6, army_walk7 ] {ai_walk(3);}; void() army_walk7 =[ $prowl_7, army_walk8 ] {ai_walk(4);}; void() army_walk8 =[ $prowl_8, army_walk9 ] {ai_walk(4);}; void() army_walk9 =[ $prowl_9, army_walk10 ] {ai_walk(2);}; void() army_walk10 =[ $prowl_10, army_walk11 ] {ai_walk(2);}; void() army_walk11 =[ $prowl_11, army_walk12 ] {ai_walk(2);}; void() army_walk12 =[ $prowl_12, army_walk13 ] {ai_walk(1);}; void() army_walk13 =[ $prowl_13, army_walk14 ] {ai_walk(0);}; void() army_walk14 =[ $prowl_14, army_walk15 ] {ai_walk(1);}; void() army_walk15 =[ $prowl_15, army_walk16 ] {ai_walk(1);}; void() army_walk16 =[ $prowl_16, army_walk17 ] {ai_walk(1);}; void() army_walk17 =[ $prowl_17, army_walk18 ] {ai_walk(3);}; void() army_walk18 =[ $prowl_18, army_walk19 ] {ai_walk(3);}; void() army_walk19 =[ $prowl_19, army_walk20 ] {ai_walk(3);}; void() army_walk20 =[ $prowl_20, army_walk21 ] {ai_walk(3);}; void() army_walk21 =[ $prowl_21, army_walk22 ] {ai_walk(2);}; void() army_walk22 =[ $prowl_22, army_walk23 ] {ai_walk(1);}; void() army_walk23 =[ $prowl_23, army_walk24 ] {ai_walk(1);}; void() army_walk24 =[ $prowl_24, army_walk1 ] {ai_walk(1);}; void() army_run1 =[ $run1, army_run2 ] { if (random() < 0.2) sound (self, CHAN_VOICE, "soldier/idle.wav", 1, ATTN_IDLE); ai_run(11);}; void() army_run2 =[ $run2, army_run3 ] {ai_run(15);}; void() army_run3 =[ $run3, army_run4 ] {ai_run(10);}; void() army_run4 =[ $run4, army_run5 ] {ai_run(10);}; void() army_run5 =[ $run5, army_run6 ] {ai_run(8);}; void() army_run6 =[ $run6, army_run7 ] {ai_run(15);}; void() army_run7 =[ $run7, army_run8 ] {ai_run(10);}; void() army_run8 =[ $run8, army_run1 ] {ai_run(8);}; void() army_atk1 =[ $shoot1, army_atk2 ] {ai_face();}; void() army_atk2 =[ $shoot2, army_atk3 ] {ai_face();}; void() army_atk3 =[ $shoot3, army_atk4 ] {ai_face();}; void() army_atk4 =[ $shoot4, army_atk5 ] {ai_face();}; void() army_atk5 =[ $shoot5, army_atk6 ] {ai_face();army_fire(); self.effects = self.effects | EF_MUZZLEFLASH;}; void() army_atk6 =[ $shoot6, army_atk7 ] {ai_face();}; void() army_atk7 =[ $shoot7, army_atk8 ] {ai_face();SUB_CheckRefire (army_atk1);}; void() army_atk8 =[ $shoot8, army_atk9 ] {ai_face();}; void() army_atk9 =[ $shoot9, army_run1 ] {ai_face();}; void() army_pain1 =[ $pain1, army_pain2 ] {}; void() army_pain2 =[ $pain2, army_pain3 ] {}; void() army_pain3 =[ $pain3, army_pain4 ] {}; void() army_pain4 =[ $pain4, army_pain5 ] {}; void() army_pain5 =[ $pain5, army_pain6 ] {}; void() army_pain6 =[ $pain6, army_run1 ] {ai_pain(1);}; void() army_painb1 =[ $painb1, army_painb2 ] {}; void() army_painb2 =[ $painb2, army_painb3 ] {ai_painforward(13);}; void() army_painb3 =[ $painb3, army_painb4 ] {ai_painforward(9);}; void() army_painb4 =[ $painb4, army_painb5 ] {}; void() army_painb5 =[ $painb5, army_painb6 ] {}; void() army_painb6 =[ $painb6, army_painb7 ] {}; void() army_painb7 =[ $painb7, army_painb8 ] {}; void() army_painb8 =[ $painb8, army_painb9 ] {}; void() army_painb9 =[ $painb9, army_painb10] {}; void() army_painb10=[ $painb10, army_painb11] {}; void() army_painb11=[ $painb11, army_painb12] {}; void() army_painb12=[ $painb12, army_painb13] {ai_pain(2);}; void() army_painb13=[ $painb13, army_painb14] {}; void() army_painb14=[ $painb14, army_run1 ] {}; void() army_painc1 =[ $painc1, army_painc2 ] {}; void() army_painc2 =[ $painc2, army_painc3 ] {ai_pain(1);}; void() army_painc3 =[ $painc3, army_painc4 ] {}; void() army_painc4 =[ $painc4, army_painc5 ] {}; void() army_painc5 =[ $painc5, army_painc6 ] {ai_painforward(1);}; void() army_painc6 =[ $painc6, army_painc7 ] {ai_painforward(1);}; void() army_painc7 =[ $painc7, army_painc8 ] {}; void() army_painc8 =[ $painc8, army_painc9 ] {ai_pain(1);}; void() army_painc9 =[ $painc9, army_painc10] {ai_painforward(4);}; void() army_painc10=[ $painc10, army_painc11] {ai_painforward(3);}; void() army_painc11=[ $painc11, army_painc12] {ai_painforward(6);}; void() army_painc12=[ $painc12, army_painc13] {ai_painforward(8);}; void() army_painc13=[ $painc13, army_run1] {}; void() army_coma =[ $stand1, army_coma ] {}; void(entity attacker, float damage) army_pain = { local float r; if (self.pain_finished > time) return; r = random(); if (r < 0.2) { self.pain_finished = time + 0.6; army_pain1 (); sound (self, CHAN_VOICE, "soldier/pain1.wav", 1, ATTN_NORM); } else if (r < 0.6) { self.pain_finished = time + 1.1; army_painb1 (); sound (self, CHAN_VOICE, "soldier/pain2.wav", 1, ATTN_NORM); } else { self.pain_finished = time + 1.1; army_painc1 (); sound (self, CHAN_VOICE, "soldier/pain2.wav", 1, ATTN_NORM); } }; void() army_fire = { local vector dir; local entity en; ai_face(); sound (self, CHAN_WEAPON, "soldier/sattck1.wav", 1, ATTN_NORM); // fire somewhat behind the player, so a dodging player is harder to hit en = self.enemy; dir = en.origin - en.velocity*0.2; dir = normalize (dir - self.origin); FireBullets (4, dir, '0.1 0.1 0'); }; void() army_die1 =[ $death1, army_die2 ] {}; void() army_die2 =[ $death2, army_die3 ] {}; void() army_die3 =[ $death3, army_die4 ] {self.solid = SOLID_NOT;self.ammo_shells = 5;DropBackpack();}; void() army_die4 =[ $death4, army_die5 ] {}; void() army_die5 =[ $death5, army_die6 ] {}; void() army_die6 =[ $death6, army_die7 ] {}; void() army_die7 =[ $death7, army_die8 ] {}; void() army_die8 =[ $death8, army_die9 ] {}; void() army_die9 =[ $death9, army_die10 ] {}; void() army_die10 =[ $death10, army_die10 ] {}; void() army_cdie1 =[ $deathc1, army_cdie2 ] {}; void() army_cdie2 =[ $deathc2, army_cdie3 ] {ai_back(5);}; void() army_cdie3 =[ $deathc3, army_cdie4 ] {self.solid = SOLID_NOT;self.ammo_shells = 5;DropBackpack();ai_back(4);}; void() army_cdie4 =[ $deathc4, army_cdie5 ] {ai_back(13);}; void() army_cdie5 =[ $deathc5, army_cdie6 ] {ai_back(3);}; void() army_cdie6 =[ $deathc6, army_cdie7 ] {ai_back(4);}; void() army_cdie7 =[ $deathc7, army_cdie8 ] {}; void() army_cdie8 =[ $deathc8, army_cdie9 ] {}; void() army_cdie9 =[ $deathc9, army_cdie10 ] {}; void() army_cdie10 =[ $deathc10, army_cdie11 ] {}; void() army_cdie11 =[ $deathc11, army_cdie11 ] {}; void() army_die = { // check for gib if (self.health < -35) { sound (self, CHAN_VOICE, "player/udeath.wav", 1, ATTN_NORM); ThrowHead ("progs/h_guard.mdl", self.health); ThrowGib ("progs/gib1.mdl", self.health); ThrowGib ("progs/gib2.mdl", self.health); ThrowGib ("progs/gib3.mdl", self.health); return; } // regular death sound (self, CHAN_VOICE, "soldier/death1.wav", 1, ATTN_NORM); if (random() < 0.5) army_die1 (); else army_cdie1 (); }; /*QUAK-ED monster_army (1 0 0) (-16 -16 -24) (16 16 40) Ambush */ void() monster_army = { if (deathmatch) { remove(self); return; } precache_model ("progs/soldier.mdl"); precache_model ("progs/h_guard.mdl"); precache_model ("progs/gib1.mdl"); precache_model ("progs/gib2.mdl"); precache_model ("progs/gib3.mdl"); precache_sound ("soldier/death1.wav"); precache_sound ("soldier/idle.wav"); precache_sound ("soldier/pain1.wav"); precache_sound ("soldier/pain2.wav"); precache_sound ("soldier/sattck1.wav"); precache_sound ("soldier/sight1.wav"); precache_sound ("player/udeath.wav"); // gib death self.solid = SOLID_SLIDEBOX; self.movetype = MOVETYPE_STEP; setmodel (self, "progs/soldier.mdl"); setsize (self, '-16 -16 -24', '16 16 40'); self.health = 30; self.th_stand = army_stand1; self.th_walk = army_walk1; self.th_run = army_run1; self.th_missile = army_atk1; self.th_pain = army_pain; self.th_die = army_die; walkmonster_start (); }; /*QUAKED monster_coma_soldier (1 0 0) (-16 -16 -24) (16 16 40) */ void() monster_coma_soldier = { if (deathmatch) { remove(self); return; } precache_model ("progs/soldier.mdl"); precache_model ("progs/h_guard.mdl"); precache_model ("progs/gib1.mdl"); precache_model ("progs/gib2.mdl"); precache_model ("progs/gib3.mdl"); precache_sound ("soldier/death1.wav"); precache_sound ("soldier/idle.wav"); precache_sound ("soldier/pain1.wav"); precache_sound ("soldier/pain2.wav"); precache_sound ("soldier/sattck1.wav"); precache_sound ("soldier/sight1.wav"); precache_sound ("player/udeath.wav"); // gib death self.solid = SOLID_SLIDEBOX; self.movetype = MOVETYPE_STEP; setmodel (self, "progs/soldier.mdl"); setsize (self, '-16 -16 -24', '16 16 40'); self.health = 30; self.th_stand = army_coma; self.th_walk = army_coma; self.th_run = army_coma; self.th_missile = army_coma; self.th_pain = army_coma; self.th_die = army_die; };
0
0.671832
1
0.671832
game-dev
MEDIA
0.991201
game-dev
0.892142
1
0.892142
face-hh/griddycode
7,182
Scripts/settings.gd
extends CodeEdit @onready var code: CodeEdit = %Code @onready var editor: FileManager = $".." const VARIABLE = preload("res://Icons/variable.png") const FUNCTION = preload("res://Icons/function.png") @onready var rich_text_labels: Array[RichTextLabel] = [ %FileDialog, ]; var file_modified = false; var _show = false; var active_overlay: Variant; var node_is_transitioning: bool; func _ready() -> void: grab_focus() LuaSingleton.on_theme_load.connect(setup_theme) tween_fade(%FileDialog, 0) tween_fade(%Settings, 0) setup_theme() func setup_theme() -> void: setup_highlighter() %Background.color = LuaSingleton.gui.background_color; %ExternalBackground.color = LuaSingleton.gui.background_color; code.add_theme_color_override("background_color", LuaSingleton.gui.background_color) code.add_theme_color_override("current_line_color", LuaSingleton.gui.current_line_color) code.add_theme_color_override("selection_color", LuaSingleton.gui.selection_color) code.add_theme_color_override("font_color", LuaSingleton.gui.font_color) code.add_theme_color_override("word_highlighted_color", LuaSingleton.gui.word_highlighted_color) code.add_theme_color_override("completion_background_color", LuaSingleton.gui.completion_background_color) code.add_theme_color_override("completion_selected_color", LuaSingleton.gui.completion_selected_color) code.add_theme_color_override("caret_color", LuaSingleton.gui.caret_color) for label in rich_text_labels: label.add_theme_color_override("default_color", LuaSingleton.gui.font_color) func setup_highlighter() -> void: var CH: CodeHighlighter = CodeHighlighter.new(); syntax_highlighter = CH; CH.number_color = LuaSingleton.keywords.binary; CH.symbol_color = LuaSingleton.keywords.symbol; CH.function_color = LuaSingleton.keywords.function; CH.member_variable_color = LuaSingleton.keywords.member; # i dont remember why this was here, but the code works without it now #await LuaSingleton.done_parsing; var kth = LuaSingleton.keywords_to_highlight; var crth = LuaSingleton.color_regions_to_highlight; for key in kth: CH.add_keyword_color(key, LuaSingleton.keywords[kth[key]]) for entry in crth: if CH.has_color_region(entry[0]): continue CH.add_color_region(entry[0], entry[1], LuaSingleton.keywords[entry[2]], entry[3]) # CodeEdit functionality func _on_code_completion_requested() -> void: var function_names = LuaSingleton.lua.call_function("detect_functions", [text, get_caret_line(), get_caret_column()]) var variable_names = LuaSingleton.lua.call_function("detect_variables", [text, get_caret_line(), get_caret_column()]) if typeof(function_names) == Variant.Type.TYPE_ARRAY: for each in unique_array(function_names): add_code_completion_option(CodeEdit.KIND_FUNCTION, each, each+"()", LuaSingleton.keywords.function, FUNCTION) if typeof(variable_names) == Variant.Type.TYPE_ARRAY: for each in unique_array(variable_names): add_code_completion_option(CodeEdit.KIND_VARIABLE, each, each, LuaSingleton.keywords.variable, VARIABLE) update_code_completion_options(true) func unique_array(arr: Array) -> Array: var out := {} for element in arr: out[element] = element return out.values() func _on_text_changed() -> void: file_modified = true; request_code_completion() # UI animations func toggle(node: Object, apply_background: bool = true, factor: float = (18 * 7.5)) -> void: # fuck me # _show is a boolean to show the editor # _show is NOT a boolean to show the overlay # i dont know what the fuck is happening here, but ill try explaining it if active_overlay != node and active_overlay != null: return # we already have an overlay active, and this function call isn't from it trying to hide, so fuck off if active_overlay == node && !_show: return # if the active overlay is the node trying to toggle, and it wants to show even tho it's already shown, it shall fuck off if node_is_transitioning: return # node is already trying to go, stop spamming the keys; DO NOT FUCKING REMOVE. var opacity = 0 if _show else 1; tween_fade(node, opacity) var future_pos = slide_from_left(node, opacity, factor) if node is FileDialogType: node.active = !_show; if _show && !editor.current_file: editor.warn("[color=yellow]WARNING[/color]: You are currently in an empty file. No autosave will be performed.") if apply_background: tween_fade(%Background, opacity, !_show) elif not apply_background and !_show: node.grab_focus() if _show: %Cam.focus_die() if !node is FileDialogType: code.grab_focus() else: if node.name == "Info": future_pos.x += 700 future_pos.y += 500 if node.name == "Settings": future_pos.x += 200 future_pos.y += 300 if node.name == "Comments": future_pos.x += 200 future_pos.y += 300 %Cam.focus_on(future_pos, node.zoom if ("zoom" in node) else Vector2(1,1)) code.release_focus() _show = !_show; func tween_fade(node: Object, opacity: float, ignore_gui: bool = false) -> void: var tween = create_tween() var color = node.modulate; if opacity == 1: node.show() color.a = opacity tween.tween_property(node, "modulate", color, 0.2) tween.tween_callback(func() -> void: if opacity == 0: node.hide() if !ignore_gui: active_overlay = null; if node is CommentsOverlay: node.container.setup() else: node.show() if !ignore_gui: active_overlay = node; ) func slide_from_left(node: Object, __show: bool, factor: float) -> Vector2: node_is_transitioning = true; var tween = create_tween() var pos = node.global_position; var future_pos = Vector2(pos.x + factor, pos.y) if __show else Vector2(pos.x - factor, pos.y) tween.tween_property(node, "position", future_pos, 0.2) tween.tween_callback(func() -> void: node_is_transitioning = false; ) return future_pos func _on_file_dialog_ui_close(): toggle(%FileDialog) # MISC func get_longest_line(lines: Array = text.split("\n")) -> String: var longestLine := "" for line in lines: if line.length() > longestLine.length(): longestLine = line return longestLine func _process(_delta): if Input.is_action_just_pressed("ui_open"): toggle(%FileDialog) if Input.is_action_just_pressed("ui_settings"): toggle(%Settings, true, (18 * 7.5) * 2) if Input.is_action_just_pressed("ui_info"): toggle(%Info, true, 1500) if Input.is_action_just_pressed("ui_theme"): toggle(%ThemeChooser, false, (18 * 28)) if Input.is_action_just_pressed("ui_cancel"): toggle(%FileDialog) if Input.is_action_just_pressed("ui_comments"): toggle(%Comments, false, -(18 * 7.5)) func _on_gui_input(_event): if Input.is_action_just_pressed("ui_open"): accept_event(); toggle(%FileDialog) if Input.is_action_just_pressed("ui_settings"): accept_event(); toggle(%Settings, true, (18 * 7.5) * 2) if Input.is_action_just_pressed("ui_info"): accept_event(); toggle(%Info, true, 1500) if Input.is_action_just_pressed("ui_theme"): accept_event(); toggle(%ThemeChooser, false, (18 * 28)) if Input.is_action_just_pressed("ui_cancel"): accept_event(); toggle(%FileDialog) if Input.is_action_just_pressed("ui_comments"): accept_event(); toggle(%Comments, false, -(18 * 7.5))
0
0.918214
1
0.918214
game-dev
MEDIA
0.636972
game-dev,desktop-app
0.980941
1
0.980941
BingBu1/DeltaForceHack
1,378
include/SDK/DFMFoliage_struct.h
#ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace Dumper { // Enum DFMFoliage.EFoliageCollisionName enum class EFoliageCollisionName : int { FoliageCollisionName_None = 0, FoliageCollisionName_AI = 1, FoliageCollisionName_Sound = 2, FoliageCollisionType_Max = 3, EFoliageCollisionName_MAX = 4 }; // Enum DFMFoliage.EFoliageCollisionType enum class EFoliageCollisionType : int { FoliageCollisionType_BoundBox = 0, FoliageCollisionType_Voxel = 1, FoliageCollisionType_Max = 2 }; // ScriptStruct DFMFoliage.FoliageData // Size: 0x90 (Inherited: 0x00) struct FFoliageData { public: struct FName Category; // 0x00(0x08) char pad_8[0x8]; // 0x08(0x08) struct FTransform Transform; // 0x10(0x30) struct FBox Box; // 0x40(0x1c) char pad_5C[0x4]; // 0x5c(0x04) /*struct TSoftObjectPtr<UStaticMesh>*/char FoliageMesh[0x28]; // 0x60(0x28) char pad_88[0x8]; // 0x88(0x08) static UClass* StaticClass(); // Dumper_Generated_Function // () // @ game+0x000000 }; // ScriptStruct DFMFoliage.FoliageCollisionCategory // Size: 0x58 (Inherited: 0x00) struct FFoliageCollisionCategory { public: struct FName Category; // 0x00(0x08) /*struct TSet<struct TSoftObjectPtr<UStaticMesh>>*/char ImportFoliageTypes[0x50]; // 0x08(0x50) static UClass* StaticClass(); // Dumper_Generated_Function // () // @ game+0x000000 }; } #ifdef _MSC_VER #pragma pack(pop) #endif
0
0.547783
1
0.547783
game-dev
MEDIA
0.739179
game-dev
0.581637
1
0.581637
bbradson/Fishery
12,421
Source/FisheryLib/FishPatch.cs
// Copyright (c) 2022 bradson // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. /*using System.Collections; using System.Linq; using System.Linq.Expressions; using Verse; namespace FisheryLib; internal class FishPatchManager { internal const string FISHERY = "fishery"; internal FishPatchManager(Assembly assembly) { Assembly = assembly; ModContentPack = LoadedModManager.RunningModsListForReading.Find(pack => pack.assemblies.loadedAssemblies.Contains(assembly)); ModName = ModContentPack?.Name ?? assembly.GetName().Name; ModPackageID = ModContentPack?.PackageIdPlayerFacing; Harmony = new($"{FISHERY}.{ModPackageID ?? ModName.ToLowerInvariant()}"); } public Assembly Assembly { get; } public ModContentPack? ModContentPack { get; } public string? ModPackageID { get; } public string ModName { get; } public Harmony Harmony { get; } } public abstract class FishPatch : IExposable, IHasDescription { public string ModName = "Fishery"; public Harmony Harmony { get; } = new("bs.fishery"); public void PatchAll() { foreach (var patch in AllPatchClasses) { try { if (!patch.RequiresLoadedGameForPatching) patch.Patches.PatchAll(); } catch (Exception ex) { Log.Error($"{ModName} encountered an exception while patching:\n{ex}"); } } } public bool Enabled { get => _enabled; set { _enabled = value; if (value) { if (ShouldBePatched) TryPatch(); } else { var shouldBePatched = ShouldBePatched; TryUnpatch(); ShouldBePatched = shouldBePatched; } } } private bool _enabled = true; public virtual bool DefaultState => true; public virtual int PrefixMethodPriority => TryGetPriority(PrefixMethodInfo); public virtual int PostfixMethodPriority => TryGetPriority(PostfixMethodInfo); public virtual int TranspilerMethodPriority => TryGetPriority(TranspilerMethodInfo); public virtual int FinalizerMethodPriority => TryGetPriority(FinalizerMethodInfo); public MethodInfo? HarmonyMethodInfo { get; private set; } private bool Patched { get; set; } private bool ShouldBePatched { get; set; } public virtual string Name => GetType().Name; public virtual string? Description => null; public virtual bool ShowSettings => true; public virtual Delegate? TargetMethodGroup => null; public virtual IEnumerable<Delegate>? TargetMethodGroups => null; public virtual Expression<Action>? TargetMethod => null; public virtual IEnumerable<Expression<Action>>? TargetMethods => null; public virtual MethodBase TargetMethodInfo => TargetMethod != null ? SymbolExtensions.GetMethodInfo(TargetMethod) : TargetMethodGroup?.Method ?? throw new MissingMethodException(GetType().ToString()); public virtual IEnumerable<MethodBase> TargetMethodInfos => TargetMethods?.Select(m => SymbolExtensions.GetMethodInfo(m)) ?? TargetMethodGroups?.Select(m => m.Method) ?? (TargetMethodInfo != null ? new MethodBase[] { TargetMethodInfo }.AsEnumerable() : throw new MissingMethodException(GetType().ToString())); public virtual MethodInfo ReversePatchMethodInfo => GetType().GetMethods(AccessTools.allDeclared) .FirstOrDefault(m => m.Name.ToUpperInvariant() == "REVERSEPATCH" || (m.HasAttribute<HarmonyReversePatch>() && !m.HasAttribute<HarmonyTranspiler>())); public virtual MethodInfo ReversePatchTranspilerMethodInfo => GetType().GetMethods(AccessTools.allDeclared) .FirstOrDefault(m => m.Name.ToUpperInvariant() == "REVERSEPATCHTRANSPILER" || (m.HasAttribute<HarmonyTranspiler>() && m.HasAttribute<HarmonyReversePatch>())); public virtual MethodInfo PrefixMethodInfo => GetType().GetMethods(AccessTools.allDeclared) .FirstOrDefault(m => m.Name.ToUpperInvariant() == "PREFIX" || m.HasAttribute<HarmonyPrefix>()); public virtual MethodInfo PostfixMethodInfo => GetType().GetMethods(AccessTools.allDeclared) .FirstOrDefault(m => m.Name.ToUpperInvariant() == "POSTFIX" || m.HasAttribute<HarmonyPostfix>()); public virtual MethodInfo TranspilerMethodInfo => GetType().GetMethods(AccessTools.allDeclared) .FirstOrDefault(m => m.Name.ToUpperInvariant() == "TRANSPILER" || (m.HasAttribute<HarmonyTranspiler>() && !m.HasAttribute<HarmonyReversePatch>())); public virtual MethodInfo FinalizerMethodInfo => GetType().GetMethods(AccessTools.allDeclared) .FirstOrDefault(m => m.Name.ToUpperInvariant() == "FINALIZER" || m.HasAttribute<HarmonyFinalizer>()); public virtual MethodInfo PrepareMethodInfo => GetType().GetMethods(AccessTools.allDeclared) .FirstOrDefault(m => m.Name.ToUpperInvariant() == "PREPARE" || m.HasAttribute<HarmonyPrepare>()); public virtual MethodInfo CleanupMethodInfo => GetType().GetMethods(AccessTools.allDeclared) .FirstOrDefault(m => m.Name.ToUpperInvariant() == "CLEANUP" || m.HasAttribute<HarmonyCleanup>()); public FishPatch() => _enabled = DefaultState; public virtual MethodInfo? TryPatch() { if (TargetMethodInfos is null || !TargetMethodInfos.Any()) { Log.Error($"Tried to apply patches for {GetType().Name}, but it lacks a target method for patching."); return null; } if (PrefixMethodInfo is null && PostfixMethodInfo is null && TranspilerMethodInfo is null && FinalizerMethodInfo is null && ReversePatchMethodInfo is null) { Log.Error($"Tried to apply patches for {GetType().Name}, but there are none. This is likely not intended."); return null; } ShouldBePatched = true; if (Enabled && !Patched) { Patched = true; PrepareMethodInfo?.Invoke(null, null); foreach (var method in TargetMethodInfos) { try { if (ReversePatchMethodInfo != null) HarmonyMethodInfo = Harmony.ReversePatch(method, new(ReversePatchMethodInfo), ReversePatchTranspilerMethodInfo); if (PrefixMethodInfo != null || PostfixMethodInfo != null || TranspilerMethodInfo != null || FinalizerMethodInfo != null) { HarmonyMethodInfo = Harmony.Patch(method, prefix: PrefixMethodInfo != null ? new(PrefixMethodInfo, PrefixMethodPriority) : null, postfix: PostfixMethodInfo != null ? new(PostfixMethodInfo, PostfixMethodPriority) : null, transpiler: TranspilerMethodInfo != null ? new(TranspilerMethodInfo, TranspilerMethodPriority) : null, finalizer: FinalizerMethodInfo != null ? new(FinalizerMethodInfo, FinalizerMethodPriority) : null); } } catch (Exception e) { Log.Error($"{ModName} encountered an exception while trying to patch {method.FullDescription()} with {PrefixMethodInfo.FullDescription()}" + $", {PostfixMethodInfo.FullDescription()}, {TranspilerMethodInfo.FullDescription()}, {FinalizerMethodInfo.FullDescription()}:\n{e}"); } #if DEBUG Log.Message($"{ModName} applied {GetType().Name} on {method.FullDescription()}"); #endif } } return HarmonyMethodInfo; } public virtual void TryUnpatch() { ShouldBePatched = false; if (Patched) { Patched = false; foreach (var method in TargetMethodInfos) { if (PrefixMethodInfo != null) { try { Harmony.Unpatch(method, PrefixMethodInfo); } catch (Exception e) { Log.Error($"{ModName} encountered an exception when unpatching {PrefixMethodInfo.FullDescription()} from {method.FullDescription()}:\n{e}"); } } if (PostfixMethodInfo != null) { try { Harmony.Unpatch(method, PostfixMethodInfo); } catch (Exception e) { Log.Error($"{ModName} encountered an exception when unpatching {PostfixMethodInfo.FullDescription()} from {method.FullDescription()}:\n{e}"); } } if (TranspilerMethodInfo != null) { try { Harmony.Unpatch(method, TranspilerMethodInfo); } catch (Exception e) { Log.Error($"{ModName} encountered an exception when unpatching {TranspilerMethodInfo.FullDescription()} from {method.FullDescription()}:\n{e}"); } } if (FinalizerMethodInfo != null) { try { Harmony.Unpatch(method, FinalizerMethodInfo); } catch (Exception e) { Log.Error($"{ModName} encountered an exception when unpatching {FinalizerMethodInfo.FullDescription()} from {method.FullDescription()}:\n{e}"); } } } CleanupMethodInfo?.Invoke(null, null); } } private static int TryGetPriority(MethodInfo info) => info?.TryGetAttribute<HarmonyPriority>()?.info.priority ?? Priority.Normal; public static T Get<T>() => TryGet<T>() ?? throw new KeyNotFoundException($"Couldn't find FishPatch or IHasFishPatch class {typeof(T).Name}"); public static T? TryGet<T>() { if (typeof(IHasFishPatch).IsAssignableFrom(typeof(T))) { foreach (var patch in AllPatchClasses) { if (patch is T patchOfT) return patchOfT; } } else if (typeof(FishPatch).IsAssignableFrom(typeof(T))) { foreach (var patchClass in AllPatchClasses) { if (patchClass.Patches.TryGet(typeof(T)) is T patch) return patch; } } return default; } public static IHasFishPatch[] AllPatchClasses { get; } = Assembly.GetExecutingAssembly().GetTypes() .Where(t => typeof(IHasFishPatch).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract) .Select(t => (IHasFishPatch)Activator.CreateInstance(t)).ToArray(); public void ExposeData() => Scribe_Values.Look(ref _enabled, GetType().Name, DefaultState); } public abstract class FirstPriorityFishPatch : FishPatch { public override int PrefixMethodPriority => Priority.First; public override int PostfixMethodPriority => Priority.First; public override int TranspilerMethodPriority => Priority.First; public override int FinalizerMethodPriority => Priority.First; } public static class FishPatchExtensions { public static void PatchAll(this IEnumerable<FishPatch> patches) { foreach (var patch in patches) patch.TryPatch(); } public static void UnpatchAll(this IEnumerable<FishPatch> patches) { foreach (var patch in patches) patch.TryUnpatch(); } } public class FishPatchHolder : IExposable, IEnumerable<FishPatch> { public Dictionary<Type, FishPatch> All => _all; public T Get<T>() where T : FishPatch => (T)All[typeof(T)]; public FishPatch Get(Type type) => All[type]; public T? TryGet<T>() where T : FishPatch => All!.TryGetValue(typeof(T)) as T; public FishPatch? TryGet(Type type) => All!.TryGetValue(type); public void Add(FishPatch patch) => All[patch.GetType()] = patch; public void PatchAll() { AddPatchesRecursively(_type); All.Values.PatchAll(); } public void UnpatchAll() => All.Values.UnpatchAll(); public FishPatch this[Type type] => All[type]; public FishPatchHolder(Type type) => _type = type; public void ExposeData() => Scribe_Collections.Look(ref _all, "patches", valueLookMode: LookMode.Deep); private void AddPatchesRecursively(Type type) { if (typeof(FishPatch).IsAssignableFrom(type) && !All.ContainsKey(type)) { var dupeClasses = FishPatch.AllPatchClasses.Where(patchClass => patchClass.GetType() != _type && patchClass.Patches.All.ContainsKey(type)); if (dupeClasses.Any()) { foreach (var patchClass in dupeClasses) { patchClass.Patches[type].Enabled = false; patchClass.Patches.All.Remove(type); Log.Warning($"{FishPatchManager.FISHERY} removed a duplicate patch from {patchClass.GetType().FullName}. This is likely caused by no longer valid mod configs"); } } All.Add(type, (FishPatch)Activator.CreateInstance(type)); } foreach (var nestedType in type.GetNestedTypes(AccessTools.all)) AddPatchesRecursively(nestedType); } public IEnumerator<FishPatch> GetEnumerator() => All.Values.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => All.Values.GetEnumerator(); private Dictionary<Type, FishPatch> _all = new(); private Type _type; } public interface IHasFishPatch { public FishPatchHolder Patches { get; } public FishPatchHolder? PatchHolder { get; set; } public bool RequiresLoadedGameForPatching { get; } } public interface IHasDescription { public string? Description { get; } } public abstract class ClassWithFishPatches : IHasFishPatch { public virtual FishPatchHolder Patches => _patchHolder ??= new(GetType()); public virtual FishPatchHolder? PatchHolder { get => _patchHolder; set => _patchHolder = value; } public virtual bool RequiresLoadedGameForPatching => false; private FishPatchHolder? _patchHolder; }*/
0
0.821168
1
0.821168
game-dev
MEDIA
0.155896
game-dev
0.890252
1
0.890252
Vawlpe/BakuganDotC-decomp
10,574
src/TODO/FUN_0887b044@0887b044.c
#include "ULUS10536_MYTHREAD-MAIN.BIN.h" void FUN_0887b044(undefined4 param_1,int param_2,undefined4 param_3,undefined4 param_4) { undefined auVar1 [12]; undefined auVar2 [12]; undefined auVar3 [16]; undefined auVar4 [12]; uint uVar5; undefined auVar6 [16]; undefined4 uVar7; undefined auVar8 [12]; undefined auVar9 [12]; undefined auVar10 [16]; int iVar11; int iVar12; undefined (*pauVar13) [16]; undefined (*pauVar14) [12]; float fVar15; float fVar16; float fVar17; undefined4 uVar18; float fVar19; undefined4 in_V73; undefined4 in_V7C; undefined4 in_V7D; undefined4 uVar20; undefined4 local_100; undefined4 local_fc; undefined4 local_f8; if (0x3c < *(int *)(param_2 + 0xf4)) { FUN_08876ee0(param_2); return; } iVar11 = FUN_08860344(*(undefined4 *)(param_2 + 0xb0)); if (*(int *)(param_2 + 0xf4) == 0) { *(undefined4 *)(param_2 + 0x20) = param_1; auVar1 = vscl_t(*(undefined (*) [12])(param_2 + 0x70),param_1); *(int *)*(undefined (*) [12])(param_2 + 0x70) = auVar1._0_4_; *(int *)(param_2 + 0x74) = auVar1._4_4_; *(int *)(param_2 + 0x78) = auVar1._8_4_; *(undefined4 *)(param_2 + 0x7c) = in_V7D; fVar16 = 1.0; if (*(float *)(param_2 + 0x10c) != 0.0) { fVar16 = 1.8; } fVar15 = *(float *)(*(int *)(*(int *)(param_2 + 0xb0) + 0x168) + 4) - *(float *)(*(int *)(param_2 + 0xb0) + 0x34); fVar15 = fVar15 - (float)(int)(fVar15 * 0.3183099) * 6.283185; if (fVar15 < 0.0) { fVar15 = fVar15 + 6.283185; } if (3.141593 <= fVar15) { fVar15 = 6.283185 - fVar15; } else { fVar15 = -fVar15; } if (0.0 < fVar15) { fVar15 = -0.5654867; } else { fVar15 = 0.5654867; } *(float *)(param_2 + 0x104) = fVar16 * fVar15; *(undefined4 *)(param_2 + 0x10c) = 0x3f800000; *(float *)(param_2 + 0x108) = fVar16 * 0.1570796; *(undefined4 *)(param_2 + 0x24) = 0x7f800000; if (iVar11 != 0) { uVar18 = *(undefined4 *)(iVar11 + 0x24); uVar20 = *(undefined4 *)(iVar11 + 0x28); uVar7 = *(undefined4 *)(iVar11 + 0x2c); *(undefined4 *)(param_2 + 0x90) = *(undefined4 *)(iVar11 + 0x20); *(undefined4 *)(param_2 + 0x94) = uVar18; *(undefined4 *)(param_2 + 0x98) = uVar20; *(undefined4 *)(param_2 + 0x9c) = uVar7; } iVar12 = *(int *)(param_2 + 0xbc); } else { iVar12 = *(int *)(param_2 + 0xbc); } if (iVar12 == 0) { iVar11 = *(int *)(param_2 + 0xf4); } else { if ((iVar11 == 0) || (*(int *)(param_2 + 0xfc) != 0)) { FUN_08877af0(*(undefined4 *)(param_2 + 0x20),0x42dc0000,param_2,1,0); *(undefined4 *)(param_2 + 0xfc) = 1; } else { pauVar13 = (undefined (*) [16])(param_2 + 0x90); auVar1 = vsub_t(*(undefined (*) [12])(iVar11 + 0x20),*(undefined (*) [12])*pauVar13); auVar1 = vscl_t(auVar1,0x3e99999a); local_100 = auVar1._0_4_; local_fc = auVar1._4_4_; local_f8 = auVar1._8_4_; fVar16 = (float)vdot_t(auVar1,auVar1); pauVar14 = (undefined (*) [12])(param_2 + 0x70); if (400.0 < fVar16) { uVar18 = vdot_t(auVar1,auVar1); uVar20 = vcmp_s(8,uVar18,local_100); vrsq_s(uVar18); uVar18 = vcmovt_s(in_V7D,(byte)uVar20 & 1); uVar18 = vmul_s(uVar18,0x41a00000); auVar1 = vscl_t(auVar1,uVar18); local_100 = auVar1._0_4_; local_fc = auVar1._4_4_; local_f8 = auVar1._8_4_; } uVar18 = *(undefined4 *)(param_2 + 0x9c); auVar1._4_4_ = local_fc; auVar1._0_4_ = local_100; auVar1._8_4_ = local_f8; auVar1 = vadd_t(*(undefined (*) [12])*pauVar13,auVar1); *(int *)*pauVar13 = auVar1._0_4_; *(int *)(param_2 + 0x94) = auVar1._4_4_; *(int *)(param_2 + 0x98) = auVar1._8_4_; *(undefined4 *)(param_2 + 0x9c) = uVar18; auVar4._4_4_ = *(float *)(param_2 + 0x94) + 100.0; auVar4._0_4_ = *(undefined4 *)*pauVar13; auVar4._8_4_ = *(undefined4 *)(param_2 + 0x98); auVar1 = vsub_t(auVar4,*(undefined (*) [12])(param_2 + 0x60)); fVar16 = auVar1._0_4_; fVar15 = auVar1._8_4_; fVar17 = (float)vdot_t(auVar1,auVar1); if ((*(float *)(param_2 + 0x24) < fVar17) || (fVar17 < 40000.0)) { *(undefined4 *)(param_2 + 0xfc) = 1; uVar18 = vdot_t(*pauVar14,*pauVar14); uVar20 = vcmp_s(8,uVar18,*(undefined4 *)*pauVar14); vrsq_s(uVar18); uVar18 = vcmovt_s(in_V7D,(byte)uVar20 & 1); vpfxd(4,4,4,5); auVar1 = vscl_t(*pauVar14,uVar18); *(int *)(param_2 + 0x80) = auVar1._0_4_; *(int *)(param_2 + 0x84) = auVar1._4_4_; *(int *)(param_2 + 0x88) = auVar1._8_4_; *(undefined4 *)(param_2 + 0x8c) = in_V7D; FUN_08877af0(*(undefined4 *)(param_2 + 0x20),0x42480000,param_2,1,0); *(undefined4 *)(param_2 + 0xe0) = 0x3da3d70a; } else { *(float *)(param_2 + 0x24) = fVar17; auVar3 = vsub_q(*(undefined (*) [16])(*(int *)(param_2 + 0xb0) + 0x20),*pauVar13); uVar18 = vdot_t(auVar3._0_12_,auVar3._0_12_); fVar19 = (float)vsqrt_s(uVar18); fVar17 = *(float *)(param_2 + 0x10c) + (SQRT(fVar17) / fVar19 - *(float *)(param_2 + 0x10c)) * 0.2; *(float *)(param_2 + 0x10c) = fVar17; if (fVar17 < 0.0) { *(undefined4 *)(param_2 + 0x10c) = 0; } fVar17 = (float)atan2f(fVar15,fVar16); fVar17 = fVar17 + *(float *)(param_2 + 0x104) * *(float *)(param_2 + 0x10c); fVar16 = (float)atan2f(auVar1._4_4_,SQRT(fVar16 * fVar16 + fVar15 * fVar15)); fVar16 = fVar16 + *(float *)(param_2 + 0x108) * *(float *)(param_2 + 0x10c); uVar18 = vmul_s(fVar16,in_V7C); fVar15 = (float)vcos_s(uVar18); uVar18 = vmul_s(fVar17,in_V7C); fVar19 = (float)vcos_s(uVar18); uVar18 = vmul_s(fVar16,in_V7C); uVar18 = vsin_s(uVar18); uVar20 = vmul_s(fVar17,in_V7C); fVar16 = (float)vsin_s(uVar20); *(float *)(param_2 + 0x70) = fVar19 * fVar15; *(undefined4 *)(param_2 + 0x74) = uVar18; *(float *)(param_2 + 0x78) = fVar16 * fVar15; *(undefined4 *)(param_2 + 0x7c) = 0; auVar1 = vscl_t(*pauVar14,*(undefined4 *)(param_2 + 0x20)); *(int *)*pauVar14 = auVar1._0_4_; *(int *)(param_2 + 0x74) = auVar1._4_4_; *(int *)(param_2 + 0x78) = auVar1._8_4_; *(undefined4 *)(param_2 + 0x7c) = in_V7D; } } if (iVar11 != 0) { auVar1 = vsub_t(*(undefined (*) [12])(iVar11 + 0x20), *(undefined (*) [12])(*(int *)(param_2 + 0xb0) + 0x20)); vpfxs(0x12,1,0,3); auVar4 = vmov_t(auVar1); uVar5 = auVar4._0_4_; uVar18 = auVar4._8_4_; auVar9._4_4_ = 0; auVar9._0_4_ = uVar5; auVar9._8_4_ = uVar18; auVar8._4_4_ = 0; auVar8._0_4_ = uVar5; auVar8._8_4_ = uVar18; auVar2._4_4_ = 0; auVar2._0_4_ = uVar5; auVar2._8_4_ = uVar18; uVar18 = vdot_t(auVar2,auVar8); uVar20 = vcmp_s(8,uVar18,uVar5); vrsq_s(uVar18); uVar18 = vcmovt_s(in_V7D,(byte)uVar20 & 1); vpfxd(4,4,4,5); auVar4 = vscl_t(auVar9,uVar18); uVar18 = vcst_s(6); uVar18 = vmul_s(uVar18,0x3fc90fdb); uVar20 = vcos_s(uVar18); uVar18 = vsin_s(uVar18); auVar4 = vscl_t(auVar4,uVar18); auVar10._12_4_ = uVar20; auVar10._0_12_ = auVar4; auVar6._12_4_ = uVar20; auVar6._0_12_ = auVar4; vpfxs(0x10,0x11,0x12,3); auVar6 = vmov_q(auVar6); uVar18 = vmov_s(in_V73); auVar3._12_4_ = uVar18; auVar3._8_4_ = auVar1._8_4_; auVar3._4_4_ = auVar1._4_4_; auVar3._0_4_ = auVar1._0_4_; auVar3 = vqmul_q(auVar10,auVar3); auVar3 = vqmul_q(auVar3,auVar6); auVar4 = auVar3._0_12_; uVar18 = vdot_t(auVar4,auVar4); uVar20 = vcmp_s(8,uVar18,auVar3._0_4_); vrsq_s(uVar18); uVar18 = vcmovt_s(in_V7D,(byte)uVar20 & 1); uVar18 = vmul_s(uVar18,0x43e10000); auVar4 = vscl_t(auVar4,uVar18); auVar1 = vscl_t(auVar1,0x3f000000); auVar1 = vadd_t(*(undefined (*) [12])(*(int *)(param_2 + 0xb0) + 0x20),auVar1); auVar1 = vadd_t(auVar4,auVar1); auVar1 = vsub_t(auVar1,*(undefined (*) [12])(param_2 + 0x60)); iVar11 = *(int *)(param_2 + 0xbc); pauVar14 = (undefined (*) [12])(param_2 + 0x70); uVar18 = vdot_t(*pauVar14,*pauVar14); uVar20 = vcmp_s(8,uVar18,auVar3._0_4_); vrsq_s(uVar18); uVar18 = vcmovt_s(in_V7D,(byte)uVar20 & 1); vpfxd(4,4,4,5); auVar4 = vscl_t(*pauVar14,uVar18); auVar1 = vcrsp_t(auVar1,auVar4); uVar18 = vdot_t(auVar1,auVar1); uVar20 = vcmp_s(8,uVar18,auVar1._0_4_); vrsq_s(uVar18); uVar18 = vcmovt_s(in_V7D,(byte)uVar20 & 1); vpfxd(4,4,4,5); auVar1 = vscl_t(auVar1,uVar18); auVar2 = vcrsp_t(auVar4,auVar1); auVar3 = vidt_q(); auVar6 = vidt_q(); *(int *)(iVar11 + 0x20) = auVar1._0_4_; *(int *)(iVar11 + 0x24) = auVar1._4_4_; *(int *)(iVar11 + 0x28) = auVar1._8_4_; *(int *)(iVar11 + 0x2c) = auVar3._0_4_; *(int *)(iVar11 + 0x30) = auVar2._0_4_; *(int *)(iVar11 + 0x34) = auVar2._4_4_; *(int *)(iVar11 + 0x38) = auVar2._8_4_; *(int *)(iVar11 + 0x3c) = auVar3._4_4_; *(int *)(iVar11 + 0x40) = auVar4._0_4_; *(int *)(iVar11 + 0x44) = auVar4._4_4_; *(int *)(iVar11 + 0x48) = auVar4._8_4_; *(int *)(iVar11 + 0x4c) = auVar3._8_4_; *(int *)(iVar11 + 0x50) = auVar6._0_4_; *(int *)(iVar11 + 0x54) = auVar6._4_4_; *(int *)(iVar11 + 0x58) = auVar6._8_4_; *(int *)(iVar11 + 0x5c) = auVar6._12_4_; } iVar11 = *(int *)(param_2 + 0xf4); } if (iVar11 != 0) { iVar11 = FUN_0887979c(param_2,param_3); if (iVar11 != 0) { return; } iVar11 = FUN_08878084(*(undefined4 *)(param_2 + 0xcc),param_2,param_2 + 0x60,param_2 + 0x70, param_4,3,0,0x31bf337e); if (iVar11 != 0) { if (DAT_08aba940 == 0) { FUN_08878cc4(param_2,param_3,&DAT_08aba930); return; } FUN_08878cc4(param_2,param_3,&DAT_08aba930); return; } } uVar18 = *(undefined4 *)(param_2 + 0x6c); auVar1 = vadd_t(*(undefined (*) [12])(param_2 + 0x60),*(undefined (*) [12])(param_2 + 0x70)); *(int *)*(undefined (*) [12])(param_2 + 0x60) = auVar1._0_4_; *(int *)(param_2 + 100) = auVar1._4_4_; *(int *)(param_2 + 0x68) = auVar1._8_4_; *(undefined4 *)(param_2 + 0x6c) = uVar18; return; }
0
0.556226
1
0.556226
game-dev
MEDIA
0.577729
game-dev,graphics-rendering
0.52691
1
0.52691
RedPandaProjects/STALKERonUE
2,601
Source/StalkerEditor/Importer/Scene/Entitys/GroupObject/RBMKSceneGroupObject.cpp
#include "RBMKSceneGroupObject.h" FRBMKSceneGroupObject::FRBMKSceneGroupObject(const FString&Name):FRBMKSceneObjectBase(Name) { ObjectType = ERBMKSceneObjectType::Group; } FRBMKSceneGroupObject::~FRBMKSceneGroupObject() { } bool FRBMKSceneGroupObject::LoadLTX(CInifile& INIFile, const FString& SectionName) { const uint32 Version = INIFile.r_u32(TCHAR_TO_ANSI(*SectionName), "version"); if (Version < 0x0011) { UE_LOG(LogXRayImporter,Error,TEXT("FRBMKSceneGroupObject: unsupported file version. Object can't load.")); return false; } FRBMKSceneObjectBase::LoadLTX(INIFile, SectionName); Flags32 TempFlags;TempFlags.zero(); if(Version<0x0012) { TempFlags.assign(INIFile.r_u32(TCHAR_TO_ANSI(*SectionName), "flags") ); } if(TempFlags.test((1<<0))) { return false; } else { FRMBKSceneAppendObjectDelegate AppendObjectDelegate; AppendObjectDelegate.BindLambda([this](TSharedPtr<FRBMKSceneObjectBase> Object) { ObjectsInGroup.Add(Object); GRBMKScene->AppendObject (Object); } ); GRBMKScene->ReadObjectsLTX(INIFile, SectionName, TEXT("ingroup"), AppendObjectDelegate); } return true; } void* FRBMKSceneGroupObject::QueryInterface(ERBMKSceneObjectType InClassID) { if (InClassID == ERBMKSceneObjectType::Group) return this; return FRBMKSceneObjectBase::QueryInterface(InClassID); } bool FRBMKSceneGroupObject::LoadStream(IReader& F) { enum { GROUPOBJ_CURRENT_VERSION = 0x0012, GROUPOBJ_CHUNK_VERSION = 0x0000, GROUPOBJ_CHUNK_OBJECT_LIST = 0x0001, GROUPOBJ_CHUNK_FLAGS = 0x0003, GROUPOBJ_CHUNK_REFERENCE = 0x0004, GROUPOBJ_CHUNK_OPEN_OBJECT_LIST = 0x0005, }; uint16 Version=0; if(!ensure(F.r_chunk(GROUPOBJ_CHUNK_VERSION,&Version))) { return false; } if (Version<0x0011) { UE_LOG(LogXRayImporter,Error,TEXT("FRBMKSceneGroupObject: unsupported file version. Object can't load.")); return false; } FRBMKSceneObjectBase::LoadStream(F); Flags32 TempFlags; TempFlags.zero(); if(Version<0x0012) { F.r_chunk(GROUPOBJ_CHUNK_FLAGS,&TempFlags); } if (TempFlags.test(1<<0)) { return false; } else { FRMBKSceneAppendObjectDelegate AppendObjectDelegate; AppendObjectDelegate.BindLambda([this](TSharedPtr<FRBMKSceneObjectBase> Object) { ObjectsInGroup.Add(Object); GRBMKScene->AppendObject(Object); } ); GRBMKScene->ReadObjectsStream(F,GROUPOBJ_CHUNK_OBJECT_LIST, AppendObjectDelegate); } return true; }
0
0.796135
1
0.796135
game-dev
MEDIA
0.621406
game-dev,graphics-rendering
0.857842
1
0.857842
manisha-v/Number-Cruncher
4,513
Codes/Minor2d/Library/PackageCache/com.unity.ugui@1.0.0/Editor/UI/SliderEditor.cs
using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace UnityEditor.UI { [CustomEditor(typeof(Slider), true)] [CanEditMultipleObjects] /// <summary> /// Custom Editor for the Slider Component. /// Extend this class to write a custom editor for a component derived from Slider. /// </summary> public class SliderEditor : SelectableEditor { SerializedProperty m_Direction; SerializedProperty m_FillRect; SerializedProperty m_HandleRect; SerializedProperty m_MinValue; SerializedProperty m_MaxValue; SerializedProperty m_WholeNumbers; SerializedProperty m_Value; SerializedProperty m_OnValueChanged; protected override void OnEnable() { base.OnEnable(); m_FillRect = serializedObject.FindProperty("m_FillRect"); m_HandleRect = serializedObject.FindProperty("m_HandleRect"); m_Direction = serializedObject.FindProperty("m_Direction"); m_MinValue = serializedObject.FindProperty("m_MinValue"); m_MaxValue = serializedObject.FindProperty("m_MaxValue"); m_WholeNumbers = serializedObject.FindProperty("m_WholeNumbers"); m_Value = serializedObject.FindProperty("m_Value"); m_OnValueChanged = serializedObject.FindProperty("m_OnValueChanged"); } public override void OnInspectorGUI() { base.OnInspectorGUI(); EditorGUILayout.Space(); serializedObject.Update(); EditorGUILayout.PropertyField(m_FillRect); EditorGUILayout.PropertyField(m_HandleRect); if (m_FillRect.objectReferenceValue != null || m_HandleRect.objectReferenceValue != null) { EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_Direction); if (EditorGUI.EndChangeCheck()) { Slider.Direction direction = (Slider.Direction)m_Direction.enumValueIndex; foreach (var obj in serializedObject.targetObjects) { Slider slider = obj as Slider; slider.SetDirection(direction, true); } } EditorGUI.BeginChangeCheck(); float newMin = EditorGUILayout.FloatField("Min Value", m_MinValue.floatValue); if (EditorGUI.EndChangeCheck() && newMin <= m_MaxValue.floatValue) { m_MinValue.floatValue = newMin; } EditorGUI.BeginChangeCheck(); float newMax = EditorGUILayout.FloatField("Max Value", m_MaxValue.floatValue); if (EditorGUI.EndChangeCheck() && newMax >= m_MinValue.floatValue) { m_MaxValue.floatValue = newMax; } EditorGUILayout.PropertyField(m_WholeNumbers); EditorGUILayout.Slider(m_Value, m_MinValue.floatValue, m_MaxValue.floatValue); bool warning = false; foreach (var obj in serializedObject.targetObjects) { Slider slider = obj as Slider; Slider.Direction dir = slider.direction; if (dir == Slider.Direction.LeftToRight || dir == Slider.Direction.RightToLeft) warning = (slider.navigation.mode != Navigation.Mode.Automatic && (slider.FindSelectableOnLeft() != null || slider.FindSelectableOnRight() != null)); else warning = (slider.navigation.mode != Navigation.Mode.Automatic && (slider.FindSelectableOnDown() != null || slider.FindSelectableOnUp() != null)); } if (warning) EditorGUILayout.HelpBox("The selected slider direction conflicts with navigation. Not all navigation options may work.", MessageType.Warning); // Draw the event notification options EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_OnValueChanged); } else { EditorGUILayout.HelpBox("Specify a RectTransform for the slider fill or the slider handle or both. Each must have a parent RectTransform that it can slide within.", MessageType.Info); } serializedObject.ApplyModifiedProperties(); } } }
0
0.960307
1
0.960307
game-dev
MEDIA
0.854202
game-dev
0.988853
1
0.988853
smell-of-curry/mcbe-anti-cheat
1,081
src/modules/managers/ban.ts
import { world } from "@minecraft/server"; import { TABLES } from "../../tables.js"; import { kick, getConfigId, msToRelativeTime } from "../../utils.js"; import { Log } from "../models/Log.js"; world.afterEvents.playerSpawn.subscribe((data) => { TABLES.ids.onLoad(() => { const { player } = data; const banData = TABLES.bans.get(player.id); if (!banData) return; if (banData.expire && banData.expire < Date.now()) return TABLES.bans.delete(player.id); kick( player, [ `§cYou have been banned!`, `§aReason: §f${banData.reason}`, `§fExpiry: §b${ banData.expire ? msToRelativeTime(banData.expire - Date.now()) : "Forever" }`, `§fAppeal at: §b${getConfigId("appealLink")}`, ], () => { console.warn(new Error("Failed to kick player")); TABLES.bans.delete(player.id); } ); new Log({ message: `Banned Player: ${player.name} tried to join the world during his ban duration.`, playerName: player.name, }); }); });
0
0.635805
1
0.635805
game-dev
MEDIA
0.564077
game-dev
0.938907
1
0.938907
KoshakMineDEV/Lumi
2,756
src/main/java/cn/nukkit/recipe/impl/MultiRecipe.java
package cn.nukkit.recipe.impl; import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.recipe.Recipe; import cn.nukkit.recipe.descriptor.ItemDescriptor; import cn.nukkit.recipe.RecipeType; import cn.nukkit.registry.RecipeRegistry; import java.util.Collection; import java.util.UUID; public class MultiRecipe implements Recipe { private final UUID id; private final int networkId; public static final UUID TYPE_REPAIR_ITEM = UUID.fromString("00000000-0000-0000-0000-000000000001"); public static final UUID TYPE_MAP_EXTENDING = UUID.fromString("D392B075-4BA1-40AE-8789-AF868D56F6CE"); public static final UUID TYPE_MAP_CLONING = UUID.fromString("85939755-BA10-4D9D-A4CC-EFB7A8E943C4"); public static final UUID TYPE_MAP_UPGRADING = UUID.fromString("AECD2294-4B94-434B-8667-4499BB2C9327"); public static final UUID TYPE_BOOK_CLONING = UUID.fromString("D1CA6B84-338E-4F2F-9C6B-76CC8B4BD98D"); public static final UUID TYPE_DECORATED_POT_RECIPE = UUID.fromString("685a742a-c42e-4a4e-88ea-5eb83fc98e5b"); public static final UUID TYPE_BANNER_DUPLICATE = UUID.fromString("B5C5D105-75A2-4076-AF2B-923EA2BF4BF0"); public static final UUID TYPE_BANNER_ADD_PATTERN = UUID.fromString("D81AAEAF-E172-4440-9225-868DF030D27B"); public static final UUID TYPE_FIREWORKS = UUID.fromString("00000000-0000-0000-0000-000000000002"); // already done by recipe json files // TODO: Unused. implement when cartography table will work public static final UUID TYPE_MAP_EXTENDING_CARTOGRAPHY = UUID.fromString("8B36268C-1829-483C-A0F1-993B7156A8F2"); public static final UUID TYPE_MAP_UPGRADING_CARTOGRAPHY = UUID.fromString("98C84B38-1085-46BD-B1CE-DD38C159E6CC"); public static final UUID TYPE_MAP_CLONING_CARTOGRAPHY = UUID.fromString("442D85ED-8272-4543-A6F1-418F90DED05D"); public static final UUID TYPE_MAP_LOCKING_CARTOGRAPHY = UUID.fromString("602234E4-CAC1-4353-8BB7-B1EBFF70024B"); public MultiRecipe(UUID id) { this.id = id; this.networkId = ++RecipeRegistry.NEXT_NETWORK_ID; } @Override public Item getResult() { throw new UnsupportedOperationException(); } @Override public RecipeType getType() { return RecipeType.MULTI; } public UUID getId() { return this.id; } public int getNetworkId() { return this.networkId; } public boolean canExecute(Player player, Item outputItem, Collection<ItemDescriptor> inputs) { return false; } @Override public boolean isValidRecipe(int protocol) { return true; } public Recipe toRecipe(Item outputItem, Collection<ItemDescriptor> inputs) { return new ShapelessRecipe(outputItem, inputs); } }
0
0.514762
1
0.514762
game-dev
MEDIA
0.833111
game-dev
0.556911
1
0.556911
PhoenixBladez/SpiritMod
2,451
Projectiles/Magic/Spit.cs
using Microsoft.Xna.Framework; using System; using Terraria; using Terraria.ModLoader; using Terraria.ID; namespace SpiritMod.Projectiles.Magic { public class Spit : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Diseased Spit"); } public override void SetDefaults() { projectile.hostile = false; projectile.magic = true; projectile.width = 10; projectile.height = 10; projectile.aiStyle = -1; projectile.friendly = true; projectile.penetrate = 1; projectile.alpha = 255; projectile.timeLeft = 60; } int counter; public override bool PreAI() { int num = 5; for (int k = 0; k < 6; k++) { int index2 = Dust.NewDust(projectile.position, 1, 1, DustID.ScourgeOfTheCorruptor, 0.0f, 0.0f, 0, new Color(), 1f); Main.dust[index2].position = projectile.Center - projectile.velocity / num * (float)k; Main.dust[index2].scale = .75f; Main.dust[index2].velocity *= 0f; Main.dust[index2].noGravity = true; Main.dust[index2].noLight = false; } counter++; if (counter >= 1440) { counter = -1440; } for (int i = 0; i < 20; i++) { float x = projectile.Center.X - projectile.velocity.X / 10f * (float)i; float y = projectile.Center.Y - projectile.velocity.Y / 10f * (float)i; int num2121 = Dust.NewDust(projectile.Center + new Vector2(0, (float)Math.Cos(counter / 4.2f) * 9.2f).RotatedBy(projectile.rotation), 6, 6, DustID.ScourgeOfTheCorruptor, 0f, 0f, 0, default, 1f); Main.dust[num2121].velocity *= 0f; Main.dust[num2121].scale *= .75f; Main.dust[num2121].noGravity = true; } return true; } public override void OnHitNPC(NPC target, int damage, float knockback, bool crit) { if (target.life <= 0) { int num24 = 307; int num3 = Main.rand.Next(0, 360); for (int j = 0; j < 1; j++) { float num4 = MathHelper.ToRadians((float)(270 / 1 * j + num3)); Vector2 vector = new Vector2(base.projectile.velocity.X, base.projectile.velocity.Y).RotatedBy((double)num4, default); vector.Normalize(); vector.X *= 4.5f; vector.Y *= 4.5f; int p = Projectile.NewProjectile(base.projectile.Center.X, base.projectile.Center.Y, vector.X, vector.Y, num24, projectile.damage / 5 * 4, 0f, 0); Main.projectile[p].hostile = false; Main.projectile[p].friendly = true; Main.projectile[p].magic = true; Main.projectile[p].melee = false; } } } } }
0
0.828991
1
0.828991
game-dev
MEDIA
0.990977
game-dev
0.990623
1
0.990623
NegInfinity/ProjectExodus
1,342
ExodusImport/Source/ExodusImport/Private/JsonGameObjectRegistry.h
#pragma once #include "JsonTypes.h" #include "InstanceIdMap.h" #include "ImportedObject.h" class JsonGameObjectRegistry{ protected: InstanceIdMap instanceIdMap; //InstanceToIdMap instanceIdMap; JsonGameObjectArray objects; void registerInstanceId(const JsonGameObject &obj); bool isValidIndex(int index) const; public: using ConstIterator = JsonGameObjectArray::RangedForConstIteratorType; const JsonGameObject* resolveObjectReference(const JsonObjectReference &ref) const; const JsonGameObjectArray& getObjects() const{ return objects; } const InstanceIdMap& getInstanceMap() const{ return instanceIdMap; } const int getNumInstanceIds() const{ return instanceIdMap.size(); } /* ConstIterator begin() const{ return objects.begin(); } ConstIterator end() const{ return objects.end(); } */ void rebuildInstanceIdMap(); int size() const{ return objects.Num(); } int num() const{ return size(); } bool siEmpty() const{ return size() == 0; } void clear(); //This function must be called in strictly sequential fashion! void addObject(const JsonGameObject &newObj); void buildFrom(const JsonGameObjectArray &objects); const JsonGameObject* findByInstanceId(InstanceId instId) const; const JsonGameObject* findByIndex(int index) const; const JsonGameObject& operator[](int index) const; };
0
0.69342
1
0.69342
game-dev
MEDIA
0.916471
game-dev
0.624316
1
0.624316
harrycomeon/ur5-gazebo-grasping
36,858
ur5-gazebo-grasping/gazebo_grasp_plugin/src/GazeboGraspFix.cpp
#include <boost/bind.hpp> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <gazebo/physics/ContactManager.hh> #include <gazebo/physics/Contact.hh> #include <gazebo/common/common.hh> #include <stdio.h> #include <gazebo_grasp_plugin/GazeboGraspFix.h> using gazebo::GazeboGraspFix; #define DEFAULT_FORCES_ANGLE_TOLERANCE 120 #define DEFAULT_UPDATE_RATE 5 #define DEFAULT_MAX_GRIP_COUNT 10 #define DEFAULT_RELEASE_TOLERANCE 0.005 #define DEFAULT_DISABLE_COLLISIONS_ON_ATTACH false // Register this plugin with the simulator GZ_REGISTER_MODEL_PLUGIN(GazeboGraspFix) GazeboGraspFix::GazeboGraspFix(){ InitValues(); } GazeboGraspFix::GazeboGraspFix(physics::ModelPtr _model) { InitValues(); } GazeboGraspFix::~GazeboGraspFix() { this->update_connection.reset(); if (this->node) this->node->Fini(); this->node.reset(); } void GazeboGraspFix::Init() { this->prevUpdateTime = common::Time::GetWallTime(); } void GazeboGraspFix::InitValues() { #if GAZEBO_MAJOR_VERSION > 2 gazebo::common::Console::SetQuiet(false); #endif // float timeDiff=0.25; // this->releaseTolerance=0.005; // this->updateRate = common::Time(0, common::Time::SecToNano(timeDiff)); this->prevUpdateTime = common::Time::GetWallTime(); //float graspedSecs=2; //this->maxGripCount=floor(graspedSecs/timeDiff); //this->gripCountThreshold=floor(this->maxGripCount/2); this->node = transport::NodePtr(new transport::Node()); } void GazeboGraspFix::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf) { std::cout<<"Loading grasp-fix plugin"<<std::endl; // ++++++++++++ Read parameters and initialize fields +++++++++++++++ physics::ModelPtr model = _parent; this->world = model->GetWorld(); sdf::ElementPtr disableCollisionsOnAttachElem = _sdf->GetElement("disable_collisions_on_attach"); if (!disableCollisionsOnAttachElem){ std::cout<<"GazeboGraspFix: Using default "<<DEFAULT_DISABLE_COLLISIONS_ON_ATTACH<<" because no <disable_collisions_on_attach> element specified."<<std::endl; this->disableCollisionsOnAttach = DEFAULT_DISABLE_COLLISIONS_ON_ATTACH; } else { std::string str = disableCollisionsOnAttachElem->Get<std::string>(); bool bVal = false; if ((str=="true") || (str=="1")) bVal = true; this->disableCollisionsOnAttach = bVal; std::cout<<"GazeboGraspFix: Using disable_collisions_on_attach "<<this->disableCollisionsOnAttach<<std::endl; } sdf::ElementPtr forcesAngleToleranceElem = _sdf->GetElement("forces_angle_tolerance"); if (!forcesAngleToleranceElem){ std::cout<<"GazeboGraspFix: Using default tolerance of "<<DEFAULT_FORCES_ANGLE_TOLERANCE<<" because no <forces_angle_tolerance> element specified."<<std::endl; this->forcesAngleTolerance = DEFAULT_FORCES_ANGLE_TOLERANCE * M_PI/180; } else { this->forcesAngleTolerance = forcesAngleToleranceElem->Get<float>() * M_PI/180; } sdf::ElementPtr updateRateElem = _sdf->GetElement("update_rate"); double _updateSecs; if (!updateRateElem){ std::cout<<"GazeboGraspFix: Using "<<DEFAULT_UPDATE_RATE<<" because no <updateRate_tag> element specified."<<std::endl; _updateSecs = 1.0 / DEFAULT_UPDATE_RATE; } else { int _rate = updateRateElem->Get<int>(); double _updateRate = _rate; _updateSecs = 1.0/_updateRate; std::cout<<"GazeboGraspFix: Using update rate "<<_rate<<std::endl; } this->updateRate = common::Time(0, common::Time::SecToNano(_updateSecs)); sdf::ElementPtr maxGripCountElem = _sdf->GetElement("max_grip_count"); if (!maxGripCountElem){ std::cout<<"GazeboGraspFix: Using "<<DEFAULT_MAX_GRIP_COUNT<<" because no <max_grip_count> element specified."<<std::endl; this->maxGripCount = DEFAULT_MAX_GRIP_COUNT; } else { this->maxGripCount = maxGripCountElem->Get<int>(); std::cout<<"GazeboGraspFix: Using max_grip_count "<<this->maxGripCount<<std::endl; } sdf::ElementPtr gripCountThresholdElem = _sdf->GetElement("grip_count_threshold"); if (!gripCountThresholdElem){ this->gripCountThreshold=floor(this->maxGripCount/2.0); std::cout<<"GazeboGraspFix: Using "<<this->gripCountThreshold<<" because no <grip_count_threshold> element specified."<<std::endl; } else { this->gripCountThreshold = gripCountThresholdElem->Get<int>(); std::cout<<"GazeboGraspFix: Using grip_count_threshold "<<this->gripCountThreshold<<std::endl; } sdf::ElementPtr releaseToleranceElem = _sdf->GetElement("release_tolerance"); if (!releaseToleranceElem){ std::cout<<"GazeboGraspFix: Using "<<DEFAULT_RELEASE_TOLERANCE<<" because no <release_tolerance> element specified."<<std::endl; this->releaseTolerance = DEFAULT_RELEASE_TOLERANCE; } else { this->releaseTolerance = releaseToleranceElem->Get<float>(); std::cout<<"GazeboGraspFix: Using release_tolerance "<<this->releaseTolerance<<std::endl; } // will contain all names of collision entities involved from all arms std::vector<std::string> collisionNames; sdf::ElementPtr armElem=_sdf->GetElement("arm"); if (!armElem) { gzerr <<"GazeboGraspFix: Cannot load the GazeboGraspFix without any <arm> declarations"<<std::endl; return; } // add all arms: for (; armElem != NULL; armElem = armElem->GetNextElement("arm")) { sdf::ElementPtr armNameElem = armElem->GetElement("arm_name"); sdf::ElementPtr handLinkElem = armElem->GetElement("palm_link"); sdf::ElementPtr fingerLinkElem = armElem->GetElement("gripper_link"); if (!handLinkElem || !fingerLinkElem || !armNameElem) { gzerr << "ERROR: GazeboGraspFix: Cannot use a GazeboGraspFix arm because " << "not all of <arm_name>, <palm_link> and <gripper_link> elements specified in URDF/SDF. Skipping."<<std::endl; continue; } std::string armName = armNameElem->Get<std::string>(); std::string palmName = handLinkElem->Get<std::string>(); // collect all finger names: std::vector<std::string> fingerLinkNames; for (; fingerLinkElem != NULL; fingerLinkElem = fingerLinkElem->GetNextElement("gripper_link")) { std::string linkName = fingerLinkElem->Get<std::string>(); fingerLinkNames.push_back(linkName); } // add new gripper if (grippers.find(armName)!=grippers.end()) { gzerr<<"GazeboGraspFix: Arm named "<<armName<<" was already added, cannot add it twice."<<std::endl; } GazeboGraspGripper& gripper = grippers[armName]; std::map<std::string, physics::CollisionPtr> _collisions; if (!gripper.Init(_parent, armName, palmName, fingerLinkNames, disableCollisionsOnAttach, _collisions)) { gzerr<<"GazeboGraspFix: Could not initialize arm "<<armName<<". Skipping."<<std::endl; grippers.erase(armName); continue; } // add all the grippers's collision elements for (std::map<std::string, physics::CollisionPtr>::iterator collIt = _collisions.begin(); collIt != _collisions.end(); ++collIt) { const std::string& collName=collIt->first; //physics::CollisionPtr& coll=collIt->second; std::map<std::string, std::string>::iterator collIter = this->collisions.find(collName); if (collIter != this->collisions.end()) { //this collision was already added before gzwarn <<"GazeboGraspFix: Adding Gazebo collision link element "<<collName<<" multiple times, the grasp plugin may not work properly"<<std::endl; continue; } std::cout<<"GazeboGraspFix: Adding collision scoped name "<<collName<<std::endl; this->collisions[collName] = armName; collisionNames.push_back(collName); } } if (grippers.empty()) { gzerr << "ERROR: GazeboGraspFix: Cannot use a GazeboGraspFix because " << "no arms were configured successfully. Plugin will not work."<<std::endl; return; } // ++++++++++++ start up things +++++++++++++++ physics::PhysicsEnginePtr physics = this->world->GetPhysicsEngine(); this->node->Init(this->world->GetName()); physics::ContactManager * contactManager = physics->GetContactManager(); contactManager->PublishContacts(); //XXX not sure I need this? std::string topic = contactManager->CreateFilter(model->GetScopedName(), collisionNames); if (!this->contactSub) { std::cout<<"Subscribing contact manager to topic "<<topic<<std::endl; bool latching=false; this->contactSub = this->node->Subscribe(topic,&GazeboGraspFix::OnContact, this, latching); } update_connection=event::Events::ConnectWorldUpdateEnd(boost::bind(&GazeboGraspFix::OnUpdate, this)); } class GazeboGraspFix::ObjectContactInfo { public: // all forces effecting on the object std::vector<gazebo::math::Vector3> appliedForces; // all grippers involved in the process, along with // a number counting the number of contact points with the // object per gripper std::map<std::string, int> grippersInvolved; // maximum number of contacts of *any one* gripper // (any in grippersInvolved) int maxGripperContactCnt; // the gripper for maxGripperContactCnt std::string maxContactGripper; }; bool GazeboGraspFix::isGripperLink(const std::string& linkName, std::string& gripperName) const { for (std::map<std::string, GazeboGraspGripper>::const_iterator it=grippers.begin(); it!=grippers.end(); ++it) { if (it->second.hasLink(linkName)) { gripperName=it->first; return true; } } return false; } std::map<std::string, std::string> GazeboGraspFix::getAttachedObjects() const { std::map<std::string, std::string> ret; for (std::map<std::string, GazeboGraspGripper>::const_iterator it=grippers.begin(); it!=grippers.end(); ++it) { const std::string& gripperName = it->first; const GazeboGraspGripper& gripper = it->second; if (gripper.isObjectAttached()) { ret[gripper.attachedObject()]=gripperName; } } return ret; } bool GazeboGraspFix::objectAttachedToGripper(const ObjectContactInfo& objContInfo, std::string& attachedToGripper) const { for (std::map<std::string, int>::const_iterator gripInvIt=objContInfo.grippersInvolved.begin(); gripInvIt != objContInfo.grippersInvolved.end(); ++gripInvIt) { const std::string& gripperName=gripInvIt->first; if (objectAttachedToGripper(gripperName, attachedToGripper)) { return true; } } return false; } bool GazeboGraspFix::objectAttachedToGripper(const std::string& gripperName, std::string& attachedToGripper) const { std::map<std::string, GazeboGraspGripper>::const_iterator gIt=grippers.find(gripperName); if (gIt == grippers.end()) { gzerr << "GazeboGraspFix: Inconsistency, gripper "<<gripperName<<" not found in GazeboGraspFix grippers"<<std::endl; return false; } const GazeboGraspGripper& gripper = gIt->second; // std::cout<<"Gripper "<<gripperName<<" is involved in the grasp"<<std::endl; if (gripper.isObjectAttached()) { attachedToGripper = gripperName; return true; } return false; } /** * Helper class to encapsulate a collision information. * One contact has two bodies, and only * the ones where one of the bodies is a gripper link are considered. * Each contact consists of a *list* of forces with their own origin/position each * (e.g. when the object and gripper are colliding at several places). * The averages of each contact's force vectors along with their origins are * *accumulated* in the given Vector3 \e pos and \eforce objects. * The number of additions is stored in \e sum. * This is to get the average force application over time between link and object. * * \author Jennifer Buehler */ class GazeboGraspFix::CollidingPoint{ public: CollidingPoint(): sum(0) {} CollidingPoint(const CollidingPoint& o): gripperName(o.gripperName), collLink(o.collLink), collObj(o.collObj), force(o.force), pos(o.pos), objPos(o.objPos), sum(o.sum){} // Name of the gripper/arm involved in contact point // This is not the specific link, but the name of the // whole gripper std::string gripperName; // the collision physics::CollisionPtr collLink, collObj; // average force vector of the colliding point gazebo::math::Vector3 force; // position (relative to reference frame of gripper // collision surface) where the contact happens on collision surface gazebo::math::Vector3 pos; // position (relative to reference frame of *gripper* collision surface) // where the object center is located during collision. gazebo::math::Vector3 objPos; // sum of force and pose (they are actually summed // up from several contact points). // Divide both \e force and \e pos by this to obtain average int sum; }; void GazeboGraspFix::OnUpdate() { if ((common::Time::GetWallTime() - this->prevUpdateTime) < this->updateRate) return; // first, copy all contact data into local struct. Don't do the complex grip check (checkGrip) // within the mutex, because that slows down OnContact(). this->mutexContacts.lock(); std::map<std::string, std::map<std::string, CollidingPoint> > contPoints(this->contacts); this->contacts.clear(); // clear so it can be filled anew by OnContact(). this->mutexContacts.unlock(); // contPoints now contains CollidingPoint objects for each *object* and *link*. // Iterate through all contact points to gather all summed forces // (and other useful information) for all the objects (so we have all forces on one object). std::map<std::string, std::map<std::string, CollidingPoint> >::iterator objIt; std::map<std::string, ObjectContactInfo> objectContactInfo; for (objIt=contPoints.begin(); objIt!=contPoints.end(); ++objIt) { std::string objName=objIt->first; //std::cout<<"Examining object collisions with "<<objName<<std::endl; // create new entry in accumulated results map and get reference to fill in: ObjectContactInfo& objContInfo = objectContactInfo[objName]; // for all links colliding with this object... std::map<std::string, CollidingPoint>::iterator lIt; for (lIt=objIt->second.begin(); lIt!=objIt->second.end(); ++lIt){ std::string linkName=lIt->first; CollidingPoint& collP=lIt->second; gazebo::math::Vector3 avgForce=collP.force/collP.sum; // std::cout << "Found collision with "<<linkName<<": "<<avgForce.x<<", "<<avgForce.y<<", "<<avgForce.z<<" (avg over "<<collP.sum<<")"<<std::endl; objContInfo.appliedForces.push_back(avgForce); // insert the gripper (if it doesn't exist yet) and increase contact counter int& gContactCnt = objContInfo.grippersInvolved[collP.gripperName]; gContactCnt++; int& _maxGripperContactCnt=objContInfo.maxGripperContactCnt; if (gContactCnt > _maxGripperContactCnt) { _maxGripperContactCnt = gContactCnt; objContInfo.maxContactGripper=collP.gripperName; } } } // ++++++++++++++++++++ Handle Attachment +++++++++++++++++++++++++++++++ // collect of all objects which are found to be "gripped" at the current stage. // if they are gripped, increase the grip counter. If the grip count exceeds the // threshold, attach the object to the gripper which has most contact points with the // object. std::set<std::string> grippedObjects; for (std::map<std::string, ObjectContactInfo>::iterator ocIt=objectContactInfo.begin(); ocIt!=objectContactInfo.end(); ++ocIt) { const std::string& objName=ocIt->first; const ObjectContactInfo& objContInfo = ocIt->second; // std::cout<<"Number applied forces on "<<objName<<": "<<objContInfo.appliedForces.size()<<std::endl; float minAngleDiff= this->forcesAngleTolerance; //120 * M_PI/180; if (!checkGrip(objContInfo.appliedForces, minAngleDiff, 0.3)) continue; // add to "gripped objects" grippedObjects.insert(objName); //std::cout<<"Grasp Held: "<<objName<<" grip count: "<<this->gripCounts[objName]<<std::endl; int& counts = this->gripCounts[objName]; if (counts < this->maxGripCount) ++counts; // only need to attach object if the grip count threshold is exceeded if (counts <= this->gripCountThreshold) continue; //std::cout<<"GRIPPING "<<objName<<", grip count "<<counts<<" (threshold "<<this->gripCountThreshold<<")"<<std::endl; // find out if any of the grippers involved in the grasp is already grasping the object. // If there is no such gripper, attach it to the gripper which has most contact points. std::string attachedToGripper; bool isAttachedToGripper=objectAttachedToGripper(objContInfo, attachedToGripper); if (isAttachedToGripper) { // the object is already attached to a gripper, so it does not need to be attached. // std::cout << "GazeboGraspFix has found that object "<< // gripper.attachedObject()<<" is already attached to gripper "<<gripperName; continue; } // attach the object to the gripper with most contact counts const std::string& graspingGripperName = objContInfo.maxContactGripper; std::map<std::string, GazeboGraspGripper>::iterator gIt=grippers.find(graspingGripperName); if (gIt == grippers.end()) { gzerr << "GazeboGraspFix: Inconsistency, gripper '"<<graspingGripperName << "' not found in GazeboGraspFix grippers, so cannot do attachment of object " << objName << std::endl; continue; } GazeboGraspGripper& graspingGripper = gIt->second; if (graspingGripper.isObjectAttached()) { gzerr<<"GazeboGraspFix has found that object "<< graspingGripper.attachedObject()<<" is already attached to gripper "<< graspingGripperName<<", so can't grasp '"<<objName<<"'!"<<std::endl; continue; } std::cout<<"GazeboGraspFix: Attaching "<<objName<<" to gripper "<<graspingGripperName<<"!!!!!!!"<<std::endl; // Store the array of contact poses which played part in the grip, sorted by colliding link. // Filter out all link names of other grippers, otherwise if the other gripper moves // away, this is going to trigger the release condition. // XXX this does not consider full support for an object being gripped by two grippers (e.g. // one left, one right). // this->attachGripContacts[objName]=contPoints[objName]; const std::map<std::string, CollidingPoint>& contPointsTmp = contPoints[objName]; std::map<std::string, CollidingPoint>& attGripConts = this->attachGripContacts[objName]; attGripConts.clear(); std::map<std::string, CollidingPoint>::const_iterator contPointsIt; for (contPointsIt=contPointsTmp.begin(); contPointsIt!=contPointsTmp.end(); ++contPointsIt) { const std::string& collidingLink = contPointsIt->first; const CollidingPoint& collidingPoint = contPointsIt->second; // std::cout<<"Checking initial contact with "<<collidingLink<<" and "<<graspingGripperName<<std::endl; if (graspingGripper.hasCollisionLink(collidingLink)) { // std::cout<<"Insert initial contact with "<<collidingLink<<std::endl; attGripConts[collidingLink] = collidingPoint; } } if (!graspingGripper.HandleAttach(objName)){ gzerr<<"GazeboGraspFix: Could not attach object "<<objName<<" to gripper "<<graspingGripperName<<std::endl; } this->OnAttach(objName, graspingGripperName); } // for all objects // ++++++++++++++++++++ Handle Detachment +++++++++++++++++++++++++++++++ std::map<std::string, std::string> attachedObjects = getAttachedObjects(); // now, for all objects that are not currently gripped, // decrease grip counter, and possibly release object. std::map<std::string, int>::iterator gripCntIt; for (gripCntIt = this->gripCounts.begin(); gripCntIt != this->gripCounts.end(); ++gripCntIt){ const std::string& objName=gripCntIt->first; if (grippedObjects.find(objName) != grippedObjects.end()) { // this object is one we just detected as "gripped", so no need to check for releasing it... // std::cout<<"NOT considering "<<objName<<" for detachment."<<std::endl; continue; } // the object does not satisfy "gripped" criteria, so potentially has to be released. // std::cout<<"NOT-GRIPPING "<<objName<<", grip count "<<gripCntIt->second<<" (threshold "<<this->gripCountThreshold<<")"<<std::endl; if (gripCntIt->second > 0) --(gripCntIt->second); std::map<std::string, std::string>::iterator attIt = attachedObjects.find(objName); bool isAttached = (attIt != attachedObjects.end()); // std::cout<<"is attached: "<<isAttached<<std::endl; if (!isAttached || (gripCntIt->second > this->gripCountThreshold)) continue; const std::string& graspingGripperName=attIt->second; // std::cout<<"Considering "<<objName<<" for detachment."<<std::endl; // Object should potentially be detached now. // However, this happens too easily when just considering the count, as the fingers // in gazebo start wobbling as the arm moves around, and although they are still // close to the object, the grip is not detected any more. So to be sure, we will // check that the collision point (the place on the link where the contact originally // was detected) has not moved too far from where it originally was, relative to the object. // get the initial set of CollidingPoints for this object // note that it is enough to use the initial contact points, because the object won't // have "slipped" after being attached, and the location of the original contact point // on the link itself is considered as a fixed point on the link, regardless whether this // point is currently still colliding with the object or not. We only want to know whether // this fixed point on the link has increased in distance from the corresponding fixed // point (where the contact originally happened) on the object. std::map<std::string, std::map<std::string, CollidingPoint> >::iterator initCollIt=this->attachGripContacts.find(objName); if (initCollIt == this->attachGripContacts.end()) { std::cerr<<"ERROR: Consistency: Could not find attachGripContacts for "<<objName<<std::endl; continue; } std::map<std::string, CollidingPoint>& initColls=initCollIt->second; int cntRelease=0; // for all links which have initially been detected to collide: std::map<std::string, CollidingPoint>::iterator pointIt; for (pointIt=initColls.begin(); pointIt!=initColls.end(); ++pointIt) { CollidingPoint& cpInfo=pointIt->second; // initial distance from link to contact point (relative to link) gazebo::math::Vector3 relContactPos=cpInfo.pos/cpInfo.sum; // initial distance from link to object (relative to link) gazebo::math::Vector3 relObjPos=cpInfo.objPos/cpInfo.sum; // get current world pose of object gazebo::math::Pose currObjWorldPose=cpInfo.collObj->GetLink()->GetWorldPose(); // get world pose of link gazebo::math::Pose currLinkWorldPose=cpInfo.collLink->GetLink()->GetWorldPose(); // Get transform for currLinkWorldPose as matrix gazebo::math::Matrix4 worldToLink=currLinkWorldPose.rot.GetAsMatrix4(); worldToLink.SetTranslate(currLinkWorldPose.pos); // Get the transform from collision link to contact point gazebo::math::Matrix4 linkToContact=gazebo::math::Matrix4::IDENTITY; linkToContact.SetTranslate(relContactPos); // the current world position of the contact point right now is: gazebo::math::Matrix4 _currContactWorldPose=worldToLink*linkToContact; gazebo::math::Vector3 currContactWorldPose=_currContactWorldPose.GetTranslation(); // the initial contact point location on the link should still correspond // to the initial contact point location on the object. // initial vector from object center to contact point (relative to link, // because relObjPos and relContactPos are from center of link) gazebo::math::Vector3 oldObjDist= relContactPos - relObjPos; // the same vector as \e oldObjDist, but calculated by the current world pose // of object and the current location of the initial contact location on the link. gazebo::math::Vector3 newObjDist= currContactWorldPose - currObjWorldPose.pos; // new distance from contact to object //std::cout<<"Obj Trans "<<cpInfo.collLink->GetName()<<": "<<relObjPos.x<<", "<<relObjPos.y<<", "<<relObjPos.z<<std::endl; //std::cout<<"Cont Trans "<<cpInfo.collLink->GetName()<<": "<<relContactPos.x<<", "<<relContactPos.y<<", "<<relContactPos.z<<std::endl; // the difference between these vectors should not be too large... float diff=fabs(oldObjDist.GetLength() - newObjDist.GetLength()); //std::cout<<"Diff for link "<<cpInfo.collLink->GetName()<<": "<<diff<<std::endl; if (diff > releaseTolerance) { ++cntRelease; } } if (cntRelease > 0) { // sufficient links did not meet the criteria to be close enough to the object. // First, get the grasping gripper: std::map<std::string, GazeboGraspGripper>::iterator gggIt = grippers.find(graspingGripperName); if (gggIt == grippers.end()) { gzerr << "GazeboGraspFix: Inconsistency: Gazebo gripper '"<<graspingGripperName<<"' not found when checking for detachment" << std::endl; continue; } GazeboGraspGripper& graspingGripper = gggIt->second; // Now, detach the object: std::cout<<"GazeboGraspFix: Detaching "<<objName<<" from gripper "<<graspingGripperName<<"!!!!!!!"<<std::endl; graspingGripper.HandleDetach(objName); this->OnDetach(objName,graspingGripperName); gripCntIt->second=0; this->attachGripContacts.erase(initCollIt); } } this->prevUpdateTime = common::Time::GetWallTime(); } double angularDistance(const gazebo::math::Vector3& _v1, const gazebo::math::Vector3& _v2) { gazebo::math::Vector3 v1=_v1; gazebo::math::Vector3 v2=_v2; v1.Normalize(); v2.Normalize(); return acos(v1.Dot(v2)); } bool GazeboGraspFix::checkGrip(const std::vector<gazebo::math::Vector3>& forces, float minAngleDiff, float lengthRatio){ if (((lengthRatio > 1) || (lengthRatio < 0)) && (lengthRatio > 1e-04 && (fabs(lengthRatio-1) > 1e-04))) { std::cerr<<"ERROR: checkGrip: always specify a lengthRatio of [0..1]"<<std::endl; return false; } if (minAngleDiff < M_PI_2){ std::cerr<<"ERROR: checkGrip: min angle must be at least 90 degrees (PI/2)"<<std::endl; return false; } std::vector<gazebo::math::Vector3>::const_iterator it1, it2; for (it1=forces.begin(); it1!=forces.end(); ++it1){ gazebo::math::Vector3 v1=*it1; for (it2=it1+1; it2!=forces.end(); ++it2){ gazebo::math::Vector3 v2=*it2; float l1=v1.GetLength(); float l2=v2.GetLength(); if ((l1<1e-04) || (l2<1e-04)) continue; /*gazebo::math::Vector3 _v1=v1; gazebo::math::Vector3 _v2=v2; _v1/=l1; _v2/=l2; float angle=acos(_v1.Dot(_v2));*/ float angle=angularDistance(v1, v2); // std::cout<<"Angular distance between v1.len="<<v1.GetLength()<<" and v2.len="<<v2.GetLength()<<": "<<angle*180/M_PI<<std::endl; if (angle > minAngleDiff) { float ratio; if (l1>l2) ratio=l2/l1; else ratio=l1/l2; // std::cout<<"Got angle "<<angle<<", ratio "<<ratio<<std::endl; if (ratio >= lengthRatio) { // std::cout<<"checkGrip() is true"<<std::endl; return true; } } } } return false; } void GazeboGraspFix::OnContact(const ConstContactsPtr &_msg) { //std::cout<<"CONTACT! "<<std::endl;//<<_contact<<std::endl; // for all contacts... for (int i = 0; i < _msg->contact_size(); ++i) { physics::CollisionPtr collision1 = boost::dynamic_pointer_cast<physics::Collision>( this->world->GetEntity(_msg->contact(i).collision1())); physics::CollisionPtr collision2 = boost::dynamic_pointer_cast<physics::Collision>( this->world->GetEntity(_msg->contact(i).collision2())); if ((collision1 && !collision1->IsStatic()) && (collision2 && !collision2->IsStatic())) { std::string name1 = collision1->GetScopedName(); std::string name2 = collision2->GetScopedName(); //std::cout<<"OBJ CONTACT! "<<name1<<" / "<<name2<<std::endl; int count = _msg->contact(i).position_size(); // Check to see if the contact arrays all have the same size. if ((count != _msg->contact(i).normal_size()) || (count != _msg->contact(i).wrench_size()) || (count != _msg->contact(i).depth_size())) { gzerr << "GazeboGraspFix: Contact message has invalid array sizes\n"<<std::endl; continue; } std::string collidingObjName, collidingLink, gripperOfCollidingLink; physics::CollisionPtr linkCollision; physics::CollisionPtr objCollision; physics::Contact contact; contact = _msg->contact(i); if (contact.count<1) { std::cerr<<"ERROR: GazeboGraspFix: Not enough forces given for contact of ."<<name1<<" / "<<name2<<std::endl; continue; } // all force vectors which are part of this contact std::vector<gazebo::math::Vector3> force; // find out which part of the colliding entities is the object, *not* the gripper, // and copy all the forces applied to it into the vector 'force'. std::map<std::string,std::string>::const_iterator gripperCollIt = this->collisions.find(name2); if (gripperCollIt != this->collisions.end()) { // collision 1 is the object collidingObjName=name1; collidingLink=name2; linkCollision=collision2; objCollision=collision1; gripperOfCollidingLink=gripperCollIt->second; for (int k=0; k<contact.count; ++k) force.push_back(contact.wrench[k].body1Force); } else if ((gripperCollIt=this->collisions.find(name1)) != this->collisions.end()) { // collision 2 is the object collidingObjName=name2; collidingLink=name1; linkCollision=collision1; objCollision=collision2; gripperOfCollidingLink=gripperCollIt->second; for (int k=0; k<contact.count; ++k) force.push_back(contact.wrench[k].body2Force); } gazebo::math::Vector3 avgForce; // compute average/sum of the forces applied on the object for (int k=0; k<force.size(); ++k){ avgForce+=force[k]; } avgForce/=force.size(); gazebo::math::Vector3 avgPos; // compute center point (average pose) of all the origin positions of the forces appied for (int k=0; k<contact.count; ++k) avgPos+=contact.positions[k]; avgPos/=contact.count; // now, get average pose relative to the colliding link gazebo::math::Pose linkWorldPose=linkCollision->GetLink()->GetWorldPose(); // To find out the collision point relative to the Link's local coordinate system, first get the Poses as 4x4 matrices gazebo::math::Matrix4 worldToLink=linkWorldPose.rot.GetAsMatrix4(); worldToLink.SetTranslate(linkWorldPose.pos); gazebo::math::Matrix4 worldToContact=gazebo::math::Matrix4::IDENTITY; //we can assume that the contact has identity rotation because we don't care about its orientation. //We could always set another rotation here too. worldToContact.SetTranslate(avgPos); // now, worldToLink * contactInLocal = worldToContact // hence, contactInLocal = worldToLink.Inv * worldToContact gazebo::math::Matrix4 worldToLinkInv = worldToLink.Inverse(); gazebo::math::Matrix4 contactInLocal = worldToLinkInv * worldToContact; gazebo::math::Vector3 contactPosInLocal = contactInLocal.GetTranslation(); //std::cout<<"---------"<<std::endl; //std::cout<<"CNT in loc: "<<contactPosInLocal.x<<","<<contactPosInLocal.y<<","<<contactPosInLocal.z<<std::endl; /*gazebo::math::Vector3 sDiff=avgPos-linkWorldPose.pos; std::cout<<"SIMPLE trans: "<<sDiff.x<<","<<sDiff.y<<","<<sDiff.z<<std::endl; std::cout<<"coll world pose: "<<linkWorldPose.pos.x<<", "<<linkWorldPose.pos.y<<", "<<linkWorldPose.pos.z<<std::endl; std::cout<<"contact avg pose: "<<avgPos.x<<", "<<avgPos.y<<", "<<avgPos.z<<std::endl; gazebo::math::Vector3 lX=linkWorldPose.rot.GetXAxis(); gazebo::math::Vector3 lY=linkWorldPose.rot.GetYAxis(); gazebo::math::Vector3 lZ=linkWorldPose.rot.GetZAxis(); std::cout<<"World ori: "<<linkWorldPose.rot.x<<","<<linkWorldPose.rot.y<<","<<linkWorldPose.rot.z<<","<<linkWorldPose.rot.w<<std::endl; std::cout<<"x axis: "<<lX.x<<","<<lX.y<<","<<lX.z<<std::endl; std::cout<<"y axis: "<<lY.x<<","<<lY.y<<","<<lY.z<<std::endl; std::cout<<"z axis: "<<lZ.x<<","<<lZ.y<<","<<lZ.z<<std::endl;*/ // now, get the pose of the object and compute it's relative position to the collision surface. gazebo::math::Pose objWorldPose = objCollision->GetLink()->GetWorldPose(); gazebo::math::Matrix4 worldToObj = objWorldPose.rot.GetAsMatrix4(); worldToObj.SetTranslate(objWorldPose.pos); gazebo::math::Matrix4 objInLocal = worldToLinkInv * worldToObj; gazebo::math::Vector3 objPosInLocal = objInLocal.GetTranslation(); { boost::mutex::scoped_lock lock(this->mutexContacts); CollidingPoint& p = this->contacts[collidingObjName][collidingLink]; // inserts new entry if doesn't exist p.gripperName=gripperOfCollidingLink; p.collLink=linkCollision; p.collObj=objCollision; p.force+=avgForce; p.pos+=contactPosInLocal; p.objPos+=objPosInLocal; p.sum++; } //std::cout<<"Average force of contact= "<<avgForce.x<<", "<<avgForce.y<<", "<<avgForce.z<<" out of "<<force.size()<<" vectors."<<std::endl; } } }
0
0.902251
1
0.902251
game-dev
MEDIA
0.619939
game-dev
0.83801
1
0.83801
can1357/ByePg
3,176
ByePgLib/HalCallbacks.h
#pragma once #include <intrin.h> #include "NT/HAL.h" #include "NT/Internals.h" #include "ExceptionHandler.h" namespace HalCallbacks { static FnHalNotifyProcessorFreeze* HalNotifyProcessorFreezeOrig = nullptr; static void __stdcall HkHalNotifyProcessorFreeze( BOOLEAN Flag1, BOOLEAN Flag2 ) { // Invoke callback if args match KiFreezeTargetExecution's if( Flag1 && !Flag2 ) ExceptionHandler::OnFreezeNotification(); // Call original routine HalNotifyProcessorFreezeOrig( Flag1, Flag2 ); } static FnHalPrepareForBugcheck* HalPrepareForBugcheckOrig = nullptr; static void __stdcall HkHalPrepareForBugcheck( BOOLEAN NmiFlag ) { // Invoke callback ExceptionHandler::OnBugCheckNotification(); // Call original routine HalPrepareForBugcheckOrig( NmiFlag ); } static FnHalTimerWatchdogStop* HalTimerWatchdogStopOrig = nullptr; static NTSTATUS __stdcall HkHalTimerWatchdogStop() { // Check if caller is KeBugCheck2, if so invoke callback if ( KeBugCheck2 < _ReturnAddress() && _ReturnAddress() < ( KeBugCheck2 + 0x1000 ) ) ExceptionHandler::OnBugCheckNotification(); // Pass to original routine return HalTimerWatchdogStopOrig(); } static FnHalRestoreHvEnlightenment* HalRestoreHvEnlightenmentOrig = nullptr; static void __stdcall HkHalRestoreHvEnlightenment() { // Check if caller is KeBugCheck2, if so invoke callback if ( KeBugCheck2 < _ReturnAddress() && _ReturnAddress() < ( KeBugCheck2 + 0x1000 ) ) ExceptionHandler::OnFreezeNotification(); // Pass to original routine HalRestoreHvEnlightenmentOrig(); } static bool Register() { // Check if already hooked if ( HalPrepareForBugcheckOrig || HalTimerWatchdogStopOrig || HalNotifyProcessorFreezeOrig ) return true; // Hook processor freeze notification if ( HalPrivateDispatchTable.Version >= HAL_PDT_NOTIFY_PROCESSOR_FREEZE_MIN_VERSION ) { HalNotifyProcessorFreezeOrig = HalPrivateDispatchTable.HalNotifyProcessorFreeze; HalPrivateDispatchTable.HalNotifyProcessorFreeze = &HkHalNotifyProcessorFreeze; } // OS must support HAL processor freeze notifications else { return false; } // Hook any function within KeBugCheck2 control flow if ( HalPrivateDispatchTable.Version >= HAL_PDT_TIMER_WATCHDOG_STOP_MIN_VERSION ) { // Hook HalTimerWatchdogStop HalTimerWatchdogStopOrig = HalPrivateDispatchTable.HalTimerWatchdogStop; HalPrivateDispatchTable.HalTimerWatchdogStop = &HkHalTimerWatchdogStop; } else if ( HalPrivateDispatchTable.Version >= HAL_PDT_PREPARE_FOR_BUGCHECK_MIN_VERSION ) { // Hook HalPrepareForBugcheck HalPrepareForBugcheckOrig = HalPrivateDispatchTable.HalPrepareForBugcheck; HalPrivateDispatchTable.HalPrepareForBugcheck = &HkHalPrepareForBugcheck; } else { // Fail return false; } // Hook a function called before returning to firmware if ( HalPrivateDispatchTable.Version <= HAL_PDT_RESTORE_HV_ENLIGHTENMENT_MIN_VERSION ) return false; // Hook HalRestoreHvEnlightenment HalRestoreHvEnlightenmentOrig = HalPrivateDispatchTable.HalRestoreHvEnlightenment; HalPrivateDispatchTable.HalRestoreHvEnlightenment = &HkHalRestoreHvEnlightenment; return true; } };
0
0.548564
1
0.548564
game-dev
MEDIA
0.833012
game-dev
0.855926
1
0.855926
magicskysword/Next
5,985
FairyGUIBundle/Assets/FairyGUI/Scripts/UI/Relations.cs
using System; using System.Collections.Generic; using FairyGUI.Utils; namespace FairyGUI { /// <summary> /// /// </summary> public class Relations { GObject _owner; List<RelationItem> _items; public GObject handling; public Relations(GObject owner) { _owner = owner; _items = new List<RelationItem>(); } /// <summary> /// /// </summary> /// <param name="target"></param> /// <param name="relationType"></param> public void Add(GObject target, RelationType relationType) { Add(target, relationType, false); } /// <summary> /// /// </summary> /// <param name="target"></param> /// <param name="relationType"></param> /// <param name="usePercent"></param> public void Add(GObject target, RelationType relationType, bool usePercent) { int cnt = _items.Count; for (int i = 0; i < cnt; i++) { RelationItem item = _items[i]; if (item.target == target) { item.Add(relationType, usePercent); return; } } RelationItem newItem = new RelationItem(_owner); newItem.target = target; newItem.Add(relationType, usePercent); _items.Add(newItem); } /// <summary> /// /// </summary> /// <param name="target"></param> /// <param name="relationType"></param> public void Remove(GObject target, RelationType relationType) { int cnt = _items.Count; int i = 0; while (i < cnt) { RelationItem item = _items[i]; if (item.target == target) { item.Remove(relationType); if (item.isEmpty) { item.Dispose(); _items.RemoveAt(i); cnt--; continue; } else i++; } i++; } } /// <summary> /// /// </summary> /// <param name="target"></param> /// <returns></returns> public bool Contains(GObject target) { int cnt = _items.Count; for (int i = 0; i < cnt; i++) { RelationItem item = _items[i]; if (item.target == target) return true; } return false; } /// <summary> /// /// </summary> /// <param name="target"></param> public void ClearFor(GObject target) { int cnt = _items.Count; int i = 0; while (i < cnt) { RelationItem item = _items[i]; if (item.target == target) { item.Dispose(); _items.RemoveAt(i); cnt--; } else i++; } } /// <summary> /// /// </summary> public void ClearAll() { int cnt = _items.Count; for (int i = 0; i < cnt; i++) { RelationItem item = _items[i]; item.Dispose(); } _items.Clear(); } /// <summary> /// /// </summary> /// <param name="source"></param> public void CopyFrom(Relations source) { ClearAll(); List<RelationItem> arr = source._items; foreach (RelationItem ri in arr) { RelationItem item = new RelationItem(_owner); item.CopyFrom(ri); _items.Add(item); } } /// <summary> /// /// </summary> public void Dispose() { ClearAll(); handling = null; } /// <summary> /// /// </summary> /// <param name="dWidth"></param> /// <param name="dHeight"></param> /// <param name="applyPivot"></param> public void OnOwnerSizeChanged(float dWidth, float dHeight, bool applyPivot) { int cnt = _items.Count; if (cnt == 0) return; for (int i = 0; i < cnt; i++) _items[i].ApplyOnSelfSizeChanged(dWidth, dHeight, applyPivot); } /// <summary> /// /// </summary> public bool isEmpty { get { return _items.Count == 0; } } public void Setup(ByteBuffer buffer, bool parentToChild) { int cnt = buffer.ReadByte(); GObject target; for (int i = 0; i < cnt; i++) { int targetIndex = buffer.ReadShort(); if (targetIndex == -1) target = _owner.parent; else if (parentToChild) target = ((GComponent)_owner).GetChildAt(targetIndex); else target = _owner.parent.GetChildAt(targetIndex); RelationItem newItem = new RelationItem(_owner); newItem.target = target; _items.Add(newItem); int cnt2 = buffer.ReadByte(); for (int j = 0; j < cnt2; j++) { RelationType rt = (RelationType)buffer.ReadByte(); bool usePercent = buffer.ReadBool(); newItem.InternalAdd(rt, usePercent); } } } } }
0
0.895538
1
0.895538
game-dev
MEDIA
0.378521
game-dev
0.867197
1
0.867197
sergev/LiteBSD
9,486
games/trek/phaser.c
/* * Copyright (c) 1980, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef lint static char sccsid[] = "@(#)phaser.c 8.1 (Berkeley) 5/31/93"; #endif /* not lint */ # include "trek.h" # include "getpar.h" /* factors for phaser hits; see description below */ # define ALPHA 3.0 /* spread */ # define BETA 3.0 /* franf() */ # define GAMMA 0.30 /* cos(angle) */ # define EPSILON 150.0 /* dist ** 2 */ # define OMEGA 10.596 /* overall scaling factor */ /* OMEGA ~= 100 * (ALPHA + 1) * (BETA + 1) / (EPSILON + 1) */ /* ** Phaser Control ** ** There are up to NBANKS phaser banks which may be fired ** simultaneously. There are two modes, "manual" and ** "automatic". In manual mode, you specify exactly which ** direction you want each bank to be aimed, the number ** of units to fire, and the spread angle. In automatic ** mode, you give only the total number of units to fire. ** ** The spread is specified as a number between zero and ** one, with zero being minimum spread and one being maximum ** spread. You will normally want zero spread, unless your ** short range scanners are out, in which case you probably ** don't know exactly where the Klingons are. In that case, ** you really don't have any choice except to specify a ** fairly large spread. ** ** Phasers spread slightly, even if you specify zero spread. ** ** Uses trace flag 30 */ struct cvntab Matab[] = { "m", "anual", (int (*)())1, 0, "a", "utomatic", 0, 0, 0 }; struct banks { int units; double angle; double spread; }; phaser() { register int i; int j; register struct kling *k; double dx, dy; double anglefactor, distfactor; register struct banks *b; int manual, flag, extra; int hit; double tot; int n; int hitreqd[NBANKS]; struct banks bank[NBANKS]; struct cvntab *ptr; if (Ship.cond == DOCKED) return(printf("Phasers cannot fire through starbase shields\n")); if (damaged(PHASER)) return (out(PHASER)); if (Ship.shldup) return (printf("Sulu: Captain, we cannot fire through shields.\n")); if (Ship.cloaked) { printf("Sulu: Captain, surely you must realize that we cannot fire\n"); printf(" phasers with the cloaking device up.\n"); return; } /* decide if we want manual or automatic mode */ manual = 0; if (testnl()) { if (damaged(COMPUTER)) { printf(Device[COMPUTER].name); manual++; } else if (damaged(SRSCAN)) { printf(Device[SRSCAN].name); manual++; } if (manual) printf(" damaged, manual mode selected\n"); } if (!manual) { ptr = getcodpar("Manual or automatic", Matab); manual = (int) ptr->value; } if (!manual && damaged(COMPUTER)) { printf("Computer damaged, manual selected\n"); skiptonl(0); manual++; } /* initialize the bank[] array */ flag = 1; for (i = 0; i < NBANKS; i++) bank[i].units = 0; if (manual) { /* collect manual mode statistics */ while (flag) { printf("%d units available\n", Ship.energy); extra = 0; flag = 0; for (i = 0; i < NBANKS; i++) { b = &bank[i]; printf("\nBank %d:\n", i); hit = getintpar("units"); if (hit < 0) return; if (hit == 0) break; extra += hit; if (extra > Ship.energy) { printf("available energy exceeded. "); skiptonl(0); flag++; break; } b->units = hit; hit = getintpar("course"); if (hit < 0 || hit > 360) return; b->angle = hit * 0.0174532925; b->spread = getfltpar("spread"); if (b->spread < 0 || b->spread > 1) return; } Ship.energy -= extra; } extra = 0; } else { /* automatic distribution of power */ if (Etc.nkling <= 0) return (printf("Sulu: But there are no Klingons in this quadrant\n")); printf("Phasers locked on target. "); while (flag) { printf("%d units available\n", Ship.energy); hit = getintpar("Units to fire"); if (hit <= 0) return; if (hit > Ship.energy) { printf("available energy exceeded. "); skiptonl(0); continue; } flag = 0; Ship.energy -= hit; extra = hit; n = Etc.nkling; if (n > NBANKS) n = NBANKS; tot = n * (n + 1) / 2; for (i = 0; i < n; i++) { k = &Etc.klingon[i]; b = &bank[i]; distfactor = k->dist; anglefactor = ALPHA * BETA * OMEGA / (distfactor * distfactor + EPSILON); anglefactor *= GAMMA; distfactor = k->power; distfactor /= anglefactor; hitreqd[i] = distfactor + 0.5; dx = Ship.sectx - k->x; dy = k->y - Ship.secty; b->angle = atan2(dy, dx); b->spread = 0.0; b->units = ((n - i) / tot) * extra; # ifdef xTRACE if (Trace) { printf("b%d hr%d u%d df%.2f af%.2f\n", i, hitreqd[i], b->units, distfactor, anglefactor); } # endif extra -= b->units; hit = b->units - hitreqd[i]; if (hit > 0) { extra += hit; b->units -= hit; } } /* give out any extra energy we might have around */ if (extra > 0) { for (i = 0; i < n; i++) { b = &bank[i]; hit = hitreqd[i] - b->units; if (hit <= 0) continue; if (hit >= extra) { b->units += extra; extra = 0; break; } b->units = hitreqd[i]; extra -= hit; } if (extra > 0) printf("%d units overkill\n", extra); } } } # ifdef xTRACE if (Trace) { for (i = 0; i < NBANKS; i++) { b = &bank[i]; printf("b%d u%d", i, b->units); if (b->units > 0) printf(" a%.2f s%.2f\n", b->angle, b->spread); else printf("\n"); } } # endif /* actually fire the shots */ Move.free = 0; for (i = 0; i < NBANKS; i++) { b = &bank[i]; if (b->units <= 0) { continue; } printf("\nPhaser bank %d fires:\n", i); n = Etc.nkling; k = Etc.klingon; for (j = 0; j < n; j++) { if (b->units <= 0) break; /* ** The formula for hit is as follows: ** ** zap = OMEGA * [(sigma + ALPHA) * (rho + BETA)] ** / (dist ** 2 + EPSILON)] ** * [cos(delta * sigma) + GAMMA] ** * hit ** ** where sigma is the spread factor, ** rho is a random number (0 -> 1), ** GAMMA is a crud factor for angle (essentially ** cruds up the spread factor), ** delta is the difference in radians between the ** angle you are shooting at and the actual ** angle of the klingon, ** ALPHA scales down the significance of sigma, ** BETA scales down the significance of rho, ** OMEGA is the magic number which makes everything ** up to "* hit" between zero and one, ** dist is the distance to the klingon ** hit is the number of units in the bank, and ** zap is the amount of the actual hit. ** ** Everything up through dist squared should maximize ** at 1.0, so that the distance factor is never ** greater than one. Conveniently, cos() is ** never greater than one, but the same restric- ** tion applies. */ distfactor = BETA + franf(); distfactor *= ALPHA + b->spread; distfactor *= OMEGA; anglefactor = k->dist; distfactor /= anglefactor * anglefactor + EPSILON; distfactor *= b->units; dx = Ship.sectx - k->x; dy = k->y - Ship.secty; anglefactor = atan2(dy, dx) - b->angle; anglefactor = cos((anglefactor * b->spread) + GAMMA); if (anglefactor < 0.0) { k++; continue; } hit = anglefactor * distfactor + 0.5; k->power -= hit; printf("%d unit hit on Klingon", hit); if (!damaged(SRSCAN)) printf(" at %d,%d", k->x, k->y); printf("\n"); b->units -= hit; if (k->power <= 0) { killk(k->x, k->y); continue; } k++; } } /* compute overkill */ for (i = 0; i < NBANKS; i++) extra += bank[i].units; if (extra > 0) printf("\n%d units expended on empty space\n", extra); }
0
0.663007
1
0.663007
game-dev
MEDIA
0.826604
game-dev
0.804255
1
0.804255
SpongePowered/Sponge
7,117
src/main/java/org/spongepowered/common/world/generation/structure/jigsaw/SpongeJigsawPoolTemplate.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.world.generation.structure.jigsaw; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.mojang.datafixers.util.Pair; import com.mojang.serialization.JsonOps; import net.minecraft.core.Holder; import net.minecraft.core.RegistryAccess; import net.minecraft.resources.RegistryOps; import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement; import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.persistence.DataContainer; import org.spongepowered.api.data.persistence.DataFormats; import org.spongepowered.api.data.persistence.DataView; import org.spongepowered.api.datapack.DataPack; import org.spongepowered.api.datapack.DataPacks; import org.spongepowered.api.registry.RegistryReference; import org.spongepowered.api.world.generation.structure.jigsaw.JigsawPool; import org.spongepowered.api.world.generation.structure.jigsaw.JigsawPoolElement; import org.spongepowered.api.world.generation.structure.jigsaw.JigsawPoolTemplate; import org.spongepowered.common.SpongeCommon; import org.spongepowered.common.accessor.world.level.levelgen.structure.pools.StructureTemplatePoolAccessor; import org.spongepowered.common.util.AbstractDataPackEntryBuilder; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.function.Function; public record SpongeJigsawPoolTemplate(ResourceKey key, StructureTemplatePool representedJigsawPool, DataPack<JigsawPoolTemplate> pack) implements JigsawPoolTemplate { @Override public JigsawPool jigsawPool() { return (JigsawPool) this.representedJigsawPool; } @Override public int contentVersion() { return 0; } @Override public DataContainer toContainer() { final JsonElement serialized = SpongeJigsawPoolTemplate.encode(this, SpongeCommon.server().registryAccess()); try { return DataFormats.JSON.get().read(serialized.toString()); } catch (IOException e) { throw new IllegalStateException("Could not read deserialized Structure:\n" + serialized, e); } } public static JsonElement encode(final JigsawPoolTemplate template, final RegistryAccess registryAccess) { final RegistryOps<JsonElement> ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); return StructureTemplatePool.DIRECT_CODEC.encodeStart(ops, (StructureTemplatePool) template.jigsawPool()).getOrThrow(); } public static StructureTemplatePool decode(final JsonElement json, final RegistryAccess registryAccess) { final RegistryOps<JsonElement> ops = RegistryOps.create(JsonOps.INSTANCE, registryAccess); return StructureTemplatePool.DIRECT_CODEC.parse(ops, json).getOrThrow(); } public static SpongeJigsawPoolTemplate decode(final DataPack<JigsawPoolTemplate> pack, final ResourceKey key, final JsonElement packEntry, final RegistryAccess registryAccess) { final StructureTemplatePool parsed = SpongeJigsawPoolTemplate.decode(packEntry, registryAccess); return new SpongeJigsawPoolTemplate(key, parsed, pack); } public static final class BuilderImpl extends AbstractDataPackEntryBuilder<JigsawPool, JigsawPoolTemplate, Builder> implements Builder { private Holder<StructureTemplatePool> fallback; private List<Pair<StructurePoolElement, Integer>> templates; public BuilderImpl() { this.reset(); } @Override public Function<JigsawPoolTemplate, JigsawPool> valueExtractor() { return JigsawPoolTemplate::jigsawPool; } @Override public Builder fromValue(final JigsawPool StructureTemplatePool) { var mcPool = (StructureTemplatePool) StructureTemplatePool; this.fallback = mcPool.getFallback(); this.templates = new ArrayList<>(((StructureTemplatePoolAccessor) mcPool).accessor$rawTemplates()); return this; } @Override public Builder fromDataPack(final DataView pack) throws IOException { final JsonElement json = JsonParser.parseString(DataFormats.JSON.get().write(pack)); final StructureTemplatePool decoded = SpongeJigsawPoolTemplate.decode(json, SpongeCommon.server().registryAccess()); return this.fromValue((JigsawPool) decoded); } @Override public Builder add(final JigsawPoolElement element, final int weight) { this.templates.add(Pair.of((StructurePoolElement) element, weight)); return this; } @Override public Builder name(final ResourceKey name) { // TODO this.name = (ResourceLocation) (Object) name; return this; } @Override public Builder fallback(final RegistryReference<JigsawPool> fallback) { // TODO this.fallback = (ResourceLocation) (Object) fallback.location(); return this; } @Override public Builder fallback(final JigsawPoolTemplate fallback) { // TODO this.fallback = (ResourceLocation) (Object) fallback.key(); return this; } @Override public Builder reset() { super.reset(); this.pack = DataPacks.JIGSAW_POOL; // TODO this.name = null; // TODO this.fallback = new ResourceLocation("empty"); this.templates = new ArrayList<>(); return this; } @Override protected SpongeJigsawPoolTemplate build0() { // TODO Objects.requireNonNull(this.name, "name"); return new SpongeJigsawPoolTemplate(this.key, new StructureTemplatePool(this.fallback, this.templates), this.pack); } } }
0
0.719783
1
0.719783
game-dev
MEDIA
0.895991
game-dev
0.869847
1
0.869847
robb/NES.swift
3,177
NES/CPU.swift
import Foundation /// The CPU of the NES. internal final class CPU { /// The number of cycles the CPU has run for. var cycles: Int = 0 /// The PC register. /// /// This register holds the program counter. var pc: UInt16 = 0 /// The SP register. /// /// This register holds the stack pointer. var sp: UInt8 = 0xFD /// The P register. /// /// This register holds the processor flags. var p: UInt8 { get { var result: UInt8 = 0 result[bit: 0] = c result[bit: 1] = z result[bit: 2] = i result[bit: 3] = d result[bit: 5] = b result[bit: 6] = v result[bit: 7] = n return result } set { c = newValue[bit: 0] z = newValue[bit: 1] i = newValue[bit: 2] d = newValue[bit: 3] b = newValue[bit: 5] v = newValue[bit: 6] n = newValue[bit: 7] } } /// Carry. /// /// If `true`, the last addition or shift resulted in a carry or the last /// subtraction resulted in no borrow. var c: Bool = false /// Zero. /// /// If `true`, the last operation resulted in `0`. var z: Bool = false /// Interrupt inhibit. /// /// If `true`, only non-maskable interrupts can be triggered. var i: Bool = true /// Decimal. /// /// If `true`, `ADC` and `SBC` _should_ use binary-coded decimals. However, /// this flag has no effect on the NES and is only present here for sake of /// completeness. var d: Bool = false /// Break. /// /// Set by `BRK`. var b: Bool = false /// Overflow. /// /// If `true`, the last `ADC` or `SBC` resulted in signed overflow, or the /// 6th bit of the last `BIT` was set. var v: Bool = true /// Negative. /// /// If `true`, the last operation resulted in a negative number. var n: Bool = false /// The A register. var a: UInt8 = 0 /// The X register. var x: UInt8 = 0 /// The Y register. var y: UInt8 = 0 /// The interrupt that will be evaluated on the next step. var interrupt: Interrupt = .none /// The number of cycles the CPU should be stalling. var stallCycles: Int = 0 /// The mapper the CPU reads from. let mapper: Mapper /// The PPU. var ppu: PPU! /// The RAM the CPU reads from. var ram: ContiguousArray<UInt8> var controller1: Controller = Controller() var controller2: Controller = Controller() init(mapper: Mapper, ram data: Data = Data(repeating: 0x00, count: 0x800)) { self.mapper = mapper self.ram = ContiguousArray(data) } } internal extension CPU { /// A convenience method for setting the A register as well as the Zero and /// Negative flags. func updateAZN(_ value: UInt8) { a = value z = value == 0 n = value & 0x80 != 0 } /// A convenience method for setting the Zero and Negative flags. func updateZN(_ value: UInt8) { z = value == 0 n = value & 0x80 != 0 } }
0
0.964527
1
0.964527
game-dev
MEDIA
0.243954
game-dev
0.858167
1
0.858167
google-ai-edge/LiteRT
3,940
litert/cc/options/litert_gpu_options.cc
// Copyright 2025 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "litert/cc/options/litert_gpu_options.h" #include "litert/c/litert_common.h" #include "litert/c/litert_opaque_options.h" #include "litert/c/options/litert_gpu_options.h" #include "litert/cc/litert_expected.h" #include "litert/cc/litert_handle.h" #include "litert/cc/litert_macros.h" namespace litert { const char* GpuOptions::GetPayloadIdentifier() { return LiteRtGetGpuOptionsPayloadIdentifier(); } Expected<GpuOptions> GpuOptions::Create() { LiteRtOpaqueOptions options; LITERT_RETURN_IF_ERROR(LiteRtCreateGpuOptions(&options)); return GpuOptions(options, OwnHandle::kYes); } LiteRtStatus GpuOptions::EnableConstantTensorSharing(bool enabled) { return LiteRtSetGpuOptionsConstantTensorSharing(Get(), enabled); } LiteRtStatus GpuOptions::EnableInfiniteFloatCapping(bool enabled) { return LiteRtSetGpuOptionsInfiniteFloatCapping(Get(), enabled); } LiteRtStatus GpuOptions::EnableBenchmarkMode(bool enabled) { return LiteRtSetGpuOptionsBenchmarkMode(Get(), enabled); } LiteRtStatus GpuOptions::SetGpuBackend(LiteRtGpuBackend backend) { return LiteRtSetGpuOptionsGpuBackend(Get(), backend); } LiteRtStatus GpuOptions::EnableAllowSrcQuantizedFcConvOps(bool enabled) { return LiteRtSetGpuAcceleratorCompilationOptionsAllowSrcQuantizedFcConvOps( Get(), enabled); } LiteRtStatus GpuOptions::SetDelegatePrecision( LiteRtDelegatePrecision precision) { return LiteRtSetGpuAcceleratorCompilationOptionsPrecision(Get(), precision); } LiteRtStatus GpuOptions::SetBufferStorageType( LiteRtDelegateBufferStorageType type) { return LiteRtSetGpuAcceleratorCompilationOptionsUseBufferStorageType(Get(), type); } LiteRtStatus GpuOptions::SetPreferTextureWeights(bool prefer_texture_weights) { return LiteRtSetGpuAcceleratorCompilationOptionsPreferTextureWeights( Get(), prefer_texture_weights); } LiteRtStatus GpuOptions::SetSerializationDir(const char* serialization_dir) { return LiteRtSetGpuAcceleratorCompilationOptionsSerializationDir( Get(), serialization_dir); } LiteRtStatus GpuOptions::SetModelCacheKey(const char* model_cache_key) { return LiteRtSetGpuAcceleratorCompilationOptionsModelCacheKey( Get(), model_cache_key); } LiteRtStatus GpuOptions::SetSerializeProgramCache( bool serialize_program_cache) { return LiteRtSetGpuAcceleratorCompilationOptionsSerializeProgramCache( Get(), serialize_program_cache); } LiteRtStatus GpuOptions::SetSerializeExternalTensors( bool serialize_external_tensors) { return LiteRtSetGpuAcceleratorCompilationOptionsSerializeExternalTensors( Get(), serialize_external_tensors); } LiteRtStatus GpuOptions::EnableExternalTensorsMode(bool enabled) { return LiteRtSetGpuOptionsExternalTensorsMode(Get(), enabled); } LiteRtStatus GpuOptions::AddExternalTensorPattern(const char* pattern) { return LiteRtAddGpuOptionsExternalTensorPattern(Get(), pattern); } LiteRtStatus GpuOptions::SetGpuPriority(LiteRtGpuPriority priority) { return LiteRtSetGpuOptionsGpuPriority(Get(), priority); } LiteRtStatus GpuOptions::SetMadviseOriginalSharedTensors( bool madvise_original_shared_tensors) { return LiteRtSetGpuAcceleratorCompilationOptionsMadviseOriginalSharedTensors( Get(), madvise_original_shared_tensors); } } // namespace litert
0
0.850204
1
0.850204
game-dev
MEDIA
0.243807
game-dev
0.505715
1
0.505715
allista/ThrottleControlledAvionics
12,765
Utils/AtmoSim.cs
// Author: // Allis Tauri <allista@gmail.com> // // Copyright (c) 2016 Allis Tauri // // This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License. // To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/ // or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. // using System; using System.Collections.Generic; using UnityEngine; using AT_Utils; namespace ThrottleControlledAvionics { public class AtmoSim : TCAComponent { public class Config : ComponentConfig<Config> { [Persistent] public float DeltaTime = 0.5f; [Persistent] public float DragCurveK = 0.8f; [Persistent] public float RotAccelPhase = 0.6f; } public static Config C => Config.INST; static double _Cd = -1; public static double Cd { get { if(_Cd < 0) //0.0005 converts dynamic pressure to kPa and divides area by 2: Drag = dP * Cd * S/2. _Cd = 0.0005 * PhysicsGlobals.DragCubeMultiplier * PhysicsGlobals.DragMultiplier; return _Cd; } } LambertSolver2D solver = new LambertSolver2D(); PIDf_Controller3 pitch = new PIDf_Controller3(); PIDf_Controller3 throttle = new PIDf_Controller3(); PIDf_Controller3 throttle_correction = new PIDf_Controller3(); Ratchet correction_started = new Ratchet(); EnginesStats eStats; CelestialBody Body { get { return VSL.Body; } } public AtmoSim(ModuleTCA tca) : base(tca) { } public void Init() { eStats = VSL.Engines.NoActiveEngines ? VSL.Engines.GetNearestEnginedStageStats() : VSL.Engines.GetEnginesStats(VSL.Engines.Active); pitch.setPID(TargetedToOrbitExecutor.C.TargetPitchPID); pitch.Min = -AttitudeControlBase.C.MaxAttitudeError; pitch.Reset(); throttle.setPID(ToOrbitExecutor.C.ThrottlePID); throttle.setClamp(0.5f); throttle.Reset(); throttle_correction.setPID(TargetedToOrbitExecutor.C.ThrottleCorrectionPID); throttle_correction.Reset(); correction_started.Reset(); } double drag(double s, double h, double v) { if(h > Body.atmosphereDepth) return 0; var atm = Body.AtmoParamsAtAltitude(h); var v2 = v * v; var dP = atm.Rho * v2 / 2; var mach = v / atm.Mach1; var d = Cd * PhysicsGlobals.DragCurveValue(PhysicsGlobals.SurfaceCurves, C.DragCurveK, (float)mach) * PhysicsGlobals.DragCurvePseudoReynolds.Evaluate((float)(atm.Rho * Math.Abs(v))); return dP * d * s; } double StG(double h) { var r = Body.Radius + h; return Body.gMagnitudeAtCenter / r / r; } Vector2d getApV(double m, double s, Vector2d r, Vector2d v, double dt, out double t) { t = 0; while(Vector2d.Dot(r, v) > 0) { r += v * dt; var R = r.magnitude; var V = v.magnitude; v -= (r * Body.gMagnitudeAtCenter / R / R / R + v / V * drag(s, R - Body.Radius, V) / m) * dt; t += dt; } return r; } float max_G_throttle(float T, double m, float maxG) => T > 0? maxG / Utils.ClampL(T / (float)m / VSL.Physics.StG - 1, maxG) : 1; public struct PV { public Vector3d pos, vel; public double time, alt; } public double FreeFallTime(Orbit orb, double startUT, Vector3d vel, Vector3d pos, double end_altitude, double dt, out Vector3d terminal_velocity, out Vector3d end_position) { var R = Body.Radius + end_altitude; var p = new PV { pos = pos.xzy, vel = vel.xzy, alt = pos.magnitude - R }; var m = (double)VSL.Physics.M; var s = (double)VSL.Geometry.BoundsSideAreas.MinComponentF(); var started = false; var UT = startUT; var endUT = startUT + orb.timeToPe; while(p.alt > 0 && UT < endUT) { var sv = p.vel - Vector3d.Cross(Body.angularVelocity, p.pos); var svm = sv.magnitude; var drag_dv = drag(s, p.alt, svm) / m * dt; started |= drag_dv > 0.1; UT = startUT + p.time; if(started) { var r = p.pos.magnitude; p.vel -= p.pos * Body.gMagnitudeAtCenter / r / r / r * dt + sv / svm * Math.Min(drag_dv, svm); p.pos += p.vel * dt; } else { p.vel = orb.getOrbitalVelocityAtUT(UT).xzy; p.pos = orb.getRelativePositionAtUT(UT).xzy; } p.alt = p.pos.magnitude - R; p.time += dt; if(dt > 0.01 && p.alt / svm < dt) dt = p.alt / svm * 0.9; // Utils.Log("h {}, t {}, dt {}, pos {}, vel {}", // p.alt, p.time, dt, p.pos, p.vel);//debug } terminal_velocity = p.vel.xzy; end_position = p.pos.xzy; return p.time; } public double FreeFallTime(double end_altitude, out double terminal_velocity) { var t = 0.0; var v = (double)VSL.VerticalSpeed.Absolute; var h = (double)VSL.Altitude.Relative; var th = (double)VSL.Altitude.TerrainAltitude; var m = (double)VSL.Physics.M; var s = VSL.Geometry.AreaInDirection(VSL.Physics.UpL); var dt = v < 0 ? Math.Abs(h / v / 10) : 1; if(dt > C.DeltaTime) dt = C.DeltaTime; while(h > end_altitude) { h += v * dt; var ah = h + th; v = Utils.ClampH(v - (StG(ah) - drag(s, ah, v) / m) * dt, -0.1); t += dt; dt = Math.Max(Math.Min(dt, (end_altitude - h) / v * 0.9), 0.01); // Utils.Log("h {}, v {}, t {}", h, v, t);//debug } terminal_velocity = Math.Abs(v); return t; } public double FreeFallTime(out double terminal_velocity) { return FreeFallTime(VSL.Geometry.H, out terminal_velocity); } public IEnumerable<double> FromSurfaceTTA(float ApA_offset, double ApA, double alpha, float maxG, float angularV) { //Log("FromSurfaceTTA: ApA_offset {}, ApA {}, alpha {}, maxG {}, angularV {}", //ApA_offset, ApA, alpha*Mathf.Rad2Deg, maxG, angularV*Mathf.Rad2Deg);//debug var t = 0.0; var BR = Body.Radius; var ApR = BR + ApA; var v = new Vector2d(1e-3, 1e-3); var r0n = new Vector2d(0, 1); var r = new Vector2d(0, VSL.orbit.radius); var r1n = new Vector2d(Math.Sin(alpha), Math.Cos(alpha)); var r1 = r1n * ApR; var T = new Vector2d(0, 1); var m = (double)VSL.Physics.M; var m0 = m; var mT = eStats.MaxThrust; var mTm = mT.magnitude; var mflow = eStats.MaxMassFlow; var AA = eStats.TorqueInfo.AA_rad; var s = VSL.Geometry.AreaInDirection(mT); var thrust = true; var R = r.magnitude; var prev_r = r; var maxR = ApR*2; double turn_start = VSL.Altitude.Absolute; bool turn_started = false; Orbit obt = null; while(R > BR && R < maxR && Utils.Angle2(r0n, r1n) > Utils.Angle2(r0n, r)) { yield return -1; prev_r = r; R = r.magnitude; var h = R - BR; double time2ApA; var ApV = getApV(m, s, r, v, C.DeltaTime * 4, out time2ApA); thrust &= Vector2d.Dot(ApV - r1, r1 - r) < 0; var srf_dir = -r.Rotate90().normalized; var thr = thrust ? max_G_throttle((float)Vector2d.Dot(T, r.normalized), m, maxG) : 0; var nV = v; if(thrust && Vector2d.Dot(r.normalized, v) / VSL.Physics.StG > ToOrbitExecutor.C.MinClimbTime) { var rr1 = r1 - r; solver.Init(Body, r, v, r1); var minT = solver.ParabolicTime; var maxT = solver.MinEnergyTime; nV = solver.dV4TransferME(); while(maxT - minT > 0.1) { var curT = (maxT + minT) / 2; nV = solver.dV4Transfer(curT); obt = TrajectoryCalculator.NewOrbit(Body, r, v + nV, VSL.Physics.UT, obt); if(obt.timeToAp > curT) minT = curT; else maxT = curT; } var neededAoA = Utils.ClampH(Utils.Angle2(rr1, r) / 2, 45); var angle2Hor = 90 - Utils.Angle2(nV, r); var AoA = Utils.Angle2(r, v); pitch.Max = AoA < neededAoA ? 0 : (float)AoA; pitch.Update((float)angle2Hor); correction_started.Update(angle2Hor >= 0); if(AoA < neededAoA && !correction_started) pitch.Action = (float)Utils.Clamp(AoA - neededAoA + angle2Hor, -AttitudeControlBase.C.MaxAttitudeError, AoA); if(!turn_started && h < Body.atmosphereDepth) { var atm = Body.AtmoParamsAtAltitude(h); if(atm.Rho > ToOrbitExecutor.C.AtmDensityOffset) turn_start = h; else turn_started = true; } var startF = Utils.Clamp((h - turn_start) / ApA/ToOrbitExecutor.C.GTurnOffset, 0, 1); var nT = v.Rotate(pitch.Action * startF); var atErr = Utils.Angle2Rad(r, T) - Utils.Angle2Rad(r, nT); T = T.RotateRad(atErr / Math.Max(C.DeltaTime, eStats.TorqueInfo.RotationTime3Phase((float)Math.Abs(atErr*Mathf.Rad2Deg), (float)(AA*m0/m), C.RotAccelPhase, 1)) * C.DeltaTime) .normalized; if(Vector2d.Dot(T, r) < 0) T = srf_dir; throttle_correction.Update((float)angle2Hor); throttle.Update(ApA_offset + throttle_correction.Action - (float)time2ApA); thr = Utils.ClampH(0.5f + throttle, thr); } if(thrust && thr > 0) { if(!CheatOptions.InfinitePropellant) { var dm = mflow * thr * C.DeltaTime; if(m < dm) thrust = false; else m -= dm; } if(thrust) v += T * mTm / m * thr * C.DeltaTime; } v -= r * Body.gMagnitudeAtCenter / R / R / R * C.DeltaTime; if(h < Body.atmosphereDepth) { var vm = v.magnitude; if(vm > 0) v -= v / vm * drag(s, h, vm) / m * C.DeltaTime; } r += v * C.DeltaTime; r1n = r1n.RotateRad(angularV*C.DeltaTime).normalized; r1 = r1n*ApR; t += C.DeltaTime; //DebugUtils.CSV("ToOrbitSim.csv", t, r);//debug //DebugUtils.CSV("ToOrbitSim.csv", t, r, v, rel_v, T*mTm/m*thr, h, m, thr, r1, nV);//debug } //Log("TimeToApA: {}", t);//debug yield return t; } } }
0
0.8908
1
0.8908
game-dev
MEDIA
0.920007
game-dev
0.99387
1
0.99387
EpicSentry/P2ASW
68,780
src/game/server/portal/portal_base2d.cpp
//===== Copyright 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: // // $NoKeywords: $ //===========================================================================// #include "cbase.h" #include "portal_base2d.h" #include "portal_player.h" #include "portal/weapon_physcannon.h" #include "physics_npc_solver.h" #include "envmicrophone.h" #include "env_speaker.h" #include "func_portal_detector.h" #include "model_types.h" #include "te_effect_dispatch.h" #include "collisionutils.h" #include "physobj.h" #include "world.h" #include "hierarchy.h" #include "physics_saverestore.h" #include "PhysicsCloneArea.h" #include "portal_gamestats.h" #include "portal_base2d_shared.h" #include "weapon_portalgun.h" #include "portal_placement.h" #include "physicsshadowclone.h" #include "particle_parse.h" #include "rumble_shared.h" #include "func_portal_orientation.h" #include "env_debughistory.h" #include "tier1/callqueue.h" #include "vphysics/player_controller.h" #include "saverestore_utlvector.h" #include "prop_weightedcube.h" // FIXME: //#include "baseprojector.h" //#include "tier0/stackstats.h" #include "portal2/portal_grabcontroller_shared.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern Vector Portal_FindUsefulVelocity( CBaseEntity *pOther ); ConVar sv_portal_debug_touch("sv_portal_debug_touch", "0", FCVAR_REPLICATED ); ConVar sv_portal_new_velocity_check("sv_portal_new_velocity_check", "1", FCVAR_CHEAT ); ConVar sv_portal_enable_microphone("sv_portal_enable_microphone", "0", FCVAR_DEVELOPMENTONLY ); ConVar sv_portal_microphone_sensitivity ( "sv_portal_microphone_sensitivity", "1.0f" ); ConVar sv_portal_microphone_max_range ( "sv_portal_microphone_max_range", "256.0f" ); ConVar sv_portal_high_speed_physics_early_untouch( "sv_portal_high_speed_physics_early_untouch", "1" ); extern ConVar sv_allow_mobile_portal_teleportation; const char *CPortal_Base2D::s_szTestRestingSurfaceThinkContext = "CPortal_Base2D::TestRestingSurfaceThink"; const char *CPortal_Base2D::s_szDeactivatePortalNowContext = "CPortal_Base2D::DeactivatePortalNow"; BEGIN_DATADESC( CPortal_Base2D ) //saving DEFINE_FIELD( m_hLinkedPortal, FIELD_EHANDLE ), DEFINE_FIELD( m_matrixThisToLinked, FIELD_VMATRIX ), DEFINE_KEYFIELD( m_bActivated, FIELD_BOOLEAN, "Activated" ), DEFINE_KEYFIELD( m_bOldActivatedState, FIELD_BOOLEAN, "OldActivated" ), DEFINE_KEYFIELD( m_bIsPortal2, FIELD_BOOLEAN, "PortalTwo" ), DEFINE_FIELD( m_vPrevForward, FIELD_VECTOR ), DEFINE_FIELD( m_hMicrophone, FIELD_EHANDLE ), DEFINE_FIELD( m_hSpeaker, FIELD_EHANDLE ), DEFINE_FIELD( m_bMicAndSpeakersLinkedToRemote, FIELD_BOOLEAN ), DEFINE_FIELD( m_vAudioOrigin, FIELD_VECTOR ), DEFINE_FIELD( m_vDelayedPosition, FIELD_VECTOR ), DEFINE_FIELD( m_qDelayedAngles, FIELD_VECTOR ), DEFINE_FIELD( m_iDelayedFailure, FIELD_INTEGER ), DEFINE_FIELD( m_vOldPosition, FIELD_VECTOR ), DEFINE_FIELD( m_qOldAngles, FIELD_VECTOR ), DEFINE_FIELD( m_hPlacedBy, FIELD_EHANDLE ), DEFINE_KEYFIELD( m_fNetworkHalfWidth, FIELD_FLOAT, "HalfWidth" ), DEFINE_KEYFIELD( m_fNetworkHalfHeight, FIELD_FLOAT, "HalfHeight" ), DEFINE_FIELD( m_bIsMobile, FIELD_BOOLEAN ), // DEFINE_FIELD( m_plane_Origin, cplane_t ), // DEFINE_FIELD( m_pAttachedCloningArea, CPhysicsCloneArea ), // DEFINE_FIELD( m_PortalSimulator, CPortalSimulator ), // DEFINE_FIELD( m_pCollisionShape, CPhysCollide ), DEFINE_FIELD( m_bSharedEnvironmentConfiguration, FIELD_BOOLEAN ), DEFINE_ARRAY( m_vPortalCorners, FIELD_POSITION_VECTOR, 4 ), DEFINE_UTLVECTOR( m_PortalEventListeners, FIELD_EHANDLE ), // Function Pointers DEFINE_THINKFUNC( TestRestingSurfaceThink ), DEFINE_THINKFUNC( DeactivatePortalNow ), DEFINE_OUTPUT( m_OnPlacedSuccessfully, "OnPlacedSuccessfully" ), DEFINE_OUTPUT( m_OnEntityTeleportFromMe, "OnEntityTeleportFromMe" ), DEFINE_OUTPUT( m_OnPlayerTeleportFromMe, "OnPlayerTeleportFromMe" ), DEFINE_OUTPUT( m_OnEntityTeleportToMe, "OnEntityTeleportToMe" ), DEFINE_OUTPUT( m_OnPlayerTeleportToMe, "OnPlayerTeleportToMe" ), DEFINE_FIELD( m_vPortalSpawnLocation, FIELD_VECTOR ), END_DATADESC() extern void SendProxy_Origin( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); extern void SendProxy_Angles( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ); IMPLEMENT_SERVERCLASS_ST( CPortal_Base2D, DT_Portal_Base2D ) //upgrade origin and angles to high precision to prevent prediction errors with projected walls. SendPropExclude( "DT_BaseEntity", "m_vecOrigin" ), SendPropExclude( "DT_BaseEntity", "m_angRotation" ), SendPropVector( SENDINFO(m_vecOrigin), -1, SPROP_NOSCALE, 0.0f, HIGH_DEFAULT, SendProxy_Origin ), SendPropVector( SENDINFO(m_angRotation), -1, SPROP_NOSCALE, 0.0f, HIGH_DEFAULT, SendProxy_Angles ), //if we're resting on another entity, we still need ultra-precise absolute coords. We should probably downgrade local origin/angles in favor of these SendPropVector( SENDINFO(m_ptOrigin), -1, SPROP_NOSCALE, 0.0f, HIGH_DEFAULT ), SendPropVector( SENDINFO(m_qAbsAngle), -1, SPROP_NOSCALE, 0.0f, HIGH_DEFAULT ), SendPropEHandle( SENDINFO(m_hLinkedPortal) ), SendPropBool( SENDINFO(m_bActivated) ), SendPropBool( SENDINFO(m_bOldActivatedState) ), SendPropBool( SENDINFO(m_bIsPortal2) ), SendPropFloat( SENDINFO( m_fNetworkHalfWidth ), -1, SPROP_NOSCALE, 0.0f, HIGH_DEFAULT ), SendPropFloat( SENDINFO( m_fNetworkHalfHeight ), -1, SPROP_NOSCALE, 0.0f, HIGH_DEFAULT ), SendPropBool( SENDINFO( m_bIsMobile ) ), SendPropDataTable( SENDINFO_DT( m_PortalSimulator ), &REFERENCE_SEND_TABLE( DT_PortalSimulator ) ) END_SEND_TABLE() LINK_ENTITY_TO_CLASS( portal_base2D, CPortal_Base2D ); CON_COMMAND_F( portal_place, "Places a portal. Indicate the group #, then the portal #, then pos + angle", FCVAR_CHEAT ) { if ( args.ArgC() != 9 ) { ConMsg( "Usage: portal_place <group #> <portal #> <pos.x pos.y pos.z> <angle.x angle.y angle.z>\n" ); return; } int iLinkageGroupID = atoi( args[1] ); // clamp to either 0, 1 or 2 iLinkageGroupID = MIN( iLinkageGroupID, 2 ); iLinkageGroupID = MAX( iLinkageGroupID, 0 ); bool bPortal2 = atoi( args[2] ) != 0; CProp_Portal *pPortal = CProp_Portal::FindPortal( iLinkageGroupID, bPortal2, true ); if ( !pPortal ) { ConMsg( "Error finding portal!\n" ); return; } Vector vNewOrigin; vNewOrigin.x = atof( args[3] ); vNewOrigin.y = atof( args[4] ); vNewOrigin.z = atof( args[5] ); // Next 3 entries are new angles QAngle vNewAngles; vNewAngles.x = atof( args[6] ); vNewAngles.y = atof( args[7] ); vNewAngles.z = atof( args[8] ); // Call main placement function (skipping placement rules) pPortal->NewLocation( vNewOrigin, vNewAngles ); } void PortalReportFunc( bool bOnlySpewIfPortalsChanged = false ) { struct PortalReportItem_t { Vector vOrigin; QAngle vAngles; int nIndex; int iLinkageGroupID; }; struct PortalReport_t { int nPortals; int nPlayers; PortalReportItem_t portals[4]; PortalReportItem_t players[2]; }; static PortalReport_t oldReport = { 0, 0 }; PortalReport_t newReport; memset( &newReport, 0, sizeof( PortalReport_t ) ); // Portal linkage groups are 0 in single-player or 1 & 2 for first and second player in co-op for ( int iLinkageGroupID = 0; iLinkageGroupID < 3; ++iLinkageGroupID ) { for ( int nPortal = 0; nPortal < 2; ++nPortal ) { CProp_Portal *pPortal = CProp_Portal::FindPortal( iLinkageGroupID, (nPortal != 0), false ); if ( !pPortal ) continue; PortalReportItem_t &item = newReport.portals[ newReport.nPortals++ ]; item.vOrigin = pPortal->m_ptOrigin; item.vAngles = pPortal->m_qAbsAngle; item.nIndex = nPortal; item.iLinkageGroupID = iLinkageGroupID; } } // Player indices are 1 or 2 (only 1 in single-player) for ( int i = 1; i <= 2; ++i ) { CBasePlayer *pPlayer = UTIL_PlayerByIndex( i ); if ( !pPlayer ) continue; PortalReportItem_t &item = newReport.players[ newReport.nPlayers++ ]; item.vOrigin = pPlayer->GetAbsOrigin(); item.vAngles = pPlayer->GetAbsAngles(); item.nIndex = i; } if ( !bOnlySpewIfPortalsChanged || memcmp( &oldReport.portals, &newReport.portals, sizeof( newReport.portals ) ) ) { for ( int i = 0; i < newReport.nPortals; i++ ) { PortalReportItem_t &item = newReport.portals[ i ]; ConMsg( "portal_place %d %d %.3f %.3f %.3f %.3f %.3f %.3f; ", item.iLinkageGroupID, item.nIndex, item.vOrigin.x, item.vOrigin.y, item.vOrigin.z, item.vAngles.x, item.vAngles.y, item.vAngles.z ); } for ( int i = 0; i < newReport.nPlayers; i++ ) { PortalReportItem_t &item = newReport.players[ i ]; ConMsg( "cmd%d setpos_exact %.3f %.3f %.3f; cmd%d setang_exact %.3f %.3f %.3f; ", item.nIndex, item.vOrigin.x, item.vOrigin.y, item.vOrigin.z, item.nIndex, item.vAngles.x, item.vAngles.y, item.vAngles.z ); } ConMsg( "\n" ); } memcpy( &oldReport, &newReport, sizeof( PortalReport_t ) ); } CON_COMMAND_F( portal_report, "Reports the location of all portals", FCVAR_CHEAT ) { PortalReportFunc(); } CPortal_Base2D::CPortal_Base2D( void ) { m_vPrevForward = Vector( 0.0f, 0.0f, 0.0f ); m_PortalSimulator.SetPortalSimulatorCallbacks( this ); // Init to something safe for ( int i = 0; i < 4; ++i ) { m_vPortalCorners[i] = Vector(0,0,0); } CPortal_Base2D_Shared::AllPortals.AddToTail( this ); // Make sure all listeners are clear m_PortalEventListeners.Purge(); m_vPortalSpawnLocation.Invalidate(); } CPortal_Base2D::~CPortal_Base2D( void ) { CPortal_Base2D_Shared::AllPortals.FindAndRemove( this ); if( m_pCollisionShape ) { physcollision->DestroyCollide( m_pCollisionShape ); m_pCollisionShape = NULL; } } void CPortal_Base2D::UpdateOnRemove( void ) { m_PortalSimulator.ClearEverything(); RemovePortalMicAndSpeaker(); CPortal_Base2D *pRemote = m_hLinkedPortal; if( pRemote != NULL ) { m_PortalSimulator.DetachFromLinked(); m_hLinkedPortal = NULL; SetActive( false ); m_bOldActivatedState = false; pRemote->UpdatePortalLinkage(); pRemote->UpdatePortalTeleportMatrix(); } if( m_pAttachedCloningArea ) { UTIL_Remove( m_pAttachedCloningArea ); m_pAttachedCloningArea = NULL; } m_PortalEventListeners.Purge(); BaseClass::UpdateOnRemove(); } void CPortal_Base2D::Spawn( void ) { Precache(); UpdateCollisionShape(); Assert( (m_fNetworkHalfHeight > 0.0f) && (m_fNetworkHalfWidth > 0.0f) ); m_matrixThisToLinked.Identity(); //don't accidentally teleport objects to zero space AddEffects( EF_NORECEIVESHADOW | EF_NOSHADOW ); SetSolid( SOLID_OBB ); SetSolidFlags( FSOLID_TRIGGER | FSOLID_NOT_SOLID | FSOLID_CUSTOMBOXTEST | FSOLID_CUSTOMRAYTEST ); SetMoveType( MOVETYPE_NONE ); SetCollisionGroup( COLLISION_GROUP_PLAYER ); SetSize( GetLocalMins(), GetLocalMaxs() ); UpdateCorners(); if( sv_portal_enable_microphone.GetInt() ) { CreateMicAndSpeaker(); } BaseClass::Spawn(); m_pAttachedCloningArea = CPhysicsCloneArea::CreatePhysicsCloneArea( this ); m_bMicAndSpeakersLinkedToRemote = false; // Because we're not solid AddEFlags( EFL_USE_PARTITION_WHEN_NOT_SOLID ); m_vPortalSpawnLocation = GetAbsOrigin(); } void CPortal_Base2D::OnRestore() { m_ptOrigin = GetAbsOrigin(); m_qAbsAngle = GetAbsAngles(); UpdatePortalTeleportMatrix(); UpdateCorners(); Assert( m_pAttachedCloningArea == NULL ); m_pAttachedCloningArea = CPhysicsCloneArea::CreatePhysicsCloneArea( this ); BaseClass::OnRestore(); } void DumpActiveCollision( const CPortalSimulator *pPortalSimulator, const char *szFileName ); void PortalSimulatorDumps_DumpCollideToGlView( CPhysCollide *pCollide, const Vector &origin, const QAngle &angles, float fColorScale, const char *pFilename ); bool CPortal_Base2D::TestCollision( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr ) { if ( !m_pCollisionShape ) { //HACK: This is a last-gasp type fix for a crash caused by m_pCollisionShape not yet being set up // during a restore. UpdateCollisionShape(); } physcollision->TraceBox( ray, MASK_ALL, NULL, m_pCollisionShape, GetAbsOrigin(), GetAbsAngles(), &tr ); return tr.DidHit(); } ConVar portal_test_resting_surface_for_paint( "portal_test_resting_surface_for_paint", "0", 0, "Test if a portal is on a white painted surface and fizzle if it goes away. Test it EVERY FRAME." ); //----------------------------------------------------------------------------- // Purpose: When placed on a surface that could potentially go away (anything but world geo), we test for that condition and fizzle //----------------------------------------------------------------------------- void CPortal_Base2D::TestRestingSurfaceThink( void ) { // Make sure there's still a surface behind the portal Vector vOrigin = GetAbsOrigin(); Vector vForward, vRight, vUp; GetVectors( &vForward, &vRight, &vUp ); trace_t tr; CTraceFilterSimpleClassnameList baseFilter( NULL, COLLISION_GROUP_NONE ); UTIL_Portal_Trace_Filter( &baseFilter ); baseFilter.AddClassnameToIgnore( "prop_portal" ); CTraceFilterTranslateClones traceFilterPortalShot( &baseFilter ); int iCornersOnVolatileSurface = 0; bool bAnyCornerOnPortalPaint = false; // Check corners for ( int iCorner = 0; iCorner < 4; ++iCorner ) { Vector vCorner = vOrigin; if ( iCorner % 2 == 0 ) vCorner += vRight * ( m_fNetworkHalfWidth - PORTAL_BUMP_FORGIVENESS * 1.1f ); else vCorner += -vRight * ( m_fNetworkHalfWidth - PORTAL_BUMP_FORGIVENESS * 1.1f ); if ( iCorner < 2 ) vCorner += vUp * ( m_fNetworkHalfHeight - PORTAL_BUMP_FORGIVENESS * 1.1f ); else vCorner += -vUp * ( m_fNetworkHalfHeight - PORTAL_BUMP_FORGIVENESS * 1.1f ); Ray_t ray; ray.Init( vCorner, vCorner - vForward ); enginetrace->TraceRay( ray, MASK_SOLID_BRUSHONLY, &traceFilterPortalShot, &tr ); // This corner isn't on a valid brush (skipping phys converts or physboxes because they frequently go through portals and can't be placed upon). if ( tr.fraction == 1.0f && !tr.startsolid && ( !tr.m_pEnt || ( tr.m_pEnt && !FClassnameIs( tr.m_pEnt, "func_physbox" ) && !FClassnameIs( tr.m_pEnt, "simple_physics_brush" ) ) ) ) { DevMsg( "Surface removed from behind portal.\n" ); DeactivatePortalOnThink(); SetContextThink( NULL, TICK_NEVER_THINK, s_szTestRestingSurfaceThinkContext ); break; } if ( portal_test_resting_surface_for_paint.GetBool() ) { PortalSurfaceType_t portalSurfType = PortalSurfaceType( tr ); // check if we still on portal paint if ( portalSurfType == PORTAL_SURFACE_PAINT ) { bAnyCornerOnPortalPaint = true; } // This corner is on no portal surf without portal paint if ( portalSurfType == PORTAL_SURFACE_INVALID ) { DevMsg( "Portal paint removed from behind portal.\n" ); DeactivatePortalOnThink(); SetContextThink( NULL, TICK_NEVER_THINK, s_szTestRestingSurfaceThinkContext ); break; } } if ( !tr.DidHitWorld() ) { iCornersOnVolatileSurface++; } } // Still on a movable or deletable surface or portal paint if ( iCornersOnVolatileSurface > 0 || bAnyCornerOnPortalPaint ) { SetContextThink ( &CPortal_Base2D::TestRestingSurfaceThink, gpGlobals->curtime + 0.1f, s_szTestRestingSurfaceThinkContext ); } else { // All corners on world, we don't need to test SetContextThink( NULL, TICK_NEVER_THINK, s_szTestRestingSurfaceThinkContext ); } } void CPortal_Base2D::DeactivatePortalOnThink( void ) { if( IsActive() && (GetNextThink( s_szDeactivatePortalNowContext ) == TICK_NEVER_THINK) ) { SetContextThink( &CPortal_Base2D::DeactivatePortalNow, gpGlobals->curtime, s_szDeactivatePortalNowContext ); } } void CPortal_Base2D::DeactivatePortalNow( void ) { // if held entity is on the opposite side of portal, make the player drops the entity when either portal gets deactivated for( int i = 1; i <= gpGlobals->maxClients; ++i ) { CPortal_Player *pPlayer = ToPortalPlayer( UTIL_PlayerByIndex( i ) ); //If the other player exists and is connected if( pPlayer && pPlayer->IsConnected() && pPlayer->IsUsingVMGrab() ) { if ( GetPlayerHeldEntity( pPlayer ) && pPlayer->IsHeldObjectOnOppositeSideOfPortal() ) { CPortal_Base2D *pHeldObjectPortal = pPlayer->GetHeldObjectPortal(); CPortal_Base2D *pPlayerPortal = pHeldObjectPortal->m_hLinkedPortal.Get(); if ( pPlayerPortal == this || pHeldObjectPortal == this ) { pPlayer->ClearUseEntity(); } } } } CPortal_Base2D *pRemotePortal = m_hLinkedPortal; StopParticleEffects( this ); SetActive( false ); m_bOldActivatedState = false; m_hLinkedPortal = NULL; m_PortalSimulator.DetachFromLinked(); m_PortalSimulator.ReleaseAllEntityOwnership(); if( pRemotePortal ) { pRemotePortal->UpdatePortalLinkage(); } UpdateClientCheckPVS(); SetMoveType( MOVETYPE_NONE ); SetMobileState( false ); SetContextThink( NULL, TICK_NEVER_THINK, s_szDeactivatePortalNowContext ); SetContextThink( NULL, TICK_NEVER_THINK, s_szTestRestingSurfaceThinkContext ); OnPortalDeactivated(); } //----------------------------------------------------------------------------- // Purpose: Removes the portal microphone and speakers. This is done in two places // (fizzle and UpdateOnRemove) so the code is consolidated here. // Input : - //----------------------------------------------------------------------------- void CPortal_Base2D::RemovePortalMicAndSpeaker() { // Shut down microphone/speaker if they exist if ( m_hMicrophone ) { CEnvMicrophone *pMicrophone = (CEnvMicrophone*)(m_hMicrophone.Get()); if ( pMicrophone ) { inputdata_t inMicDisable; pMicrophone->InputDisable( inMicDisable ); UTIL_Remove( pMicrophone ); } m_hMicrophone = 0; } if ( m_hSpeaker ) { CSpeaker *pSpeaker = (CSpeaker *)(m_hSpeaker.Get()); if ( pSpeaker ) { // Remove the remote portal's microphone, as it references the speaker we're about to remove. if ( m_hLinkedPortal.Get() ) { CPortal_Base2D* pRemotePortal = m_hLinkedPortal.Get(); if ( pRemotePortal->m_hMicrophone ) { inputdata_t inputdata; inputdata.pActivator = this; inputdata.pCaller = this; CEnvMicrophone* pRemotePortalMic = dynamic_cast<CEnvMicrophone*>(pRemotePortal->m_hMicrophone.Get()); if ( pRemotePortalMic ) { pRemotePortalMic->Remove(); } } } inputdata_t inTurnOff; pSpeaker->InputTurnOff( inTurnOff ); UTIL_Remove( pSpeaker ); } m_hSpeaker = 0; } m_bMicAndSpeakersLinkedToRemote = false; if ( m_hLinkedPortal.Get() ) { if ( m_hLinkedPortal->m_hMicrophone.Get() ) { CEnvMicrophone* pRemoteMic = dynamic_cast<CEnvMicrophone*>( m_hLinkedPortal->m_hMicrophone.Get() ); if ( pRemoteMic ) { pRemoteMic->SetSpeaker( NULL_STRING, NULL ); } } m_hLinkedPortal->m_bMicAndSpeakersLinkedToRemote = false; } } void CPortal_Base2D::PunchPenetratingPlayer( CBasePlayer *pPlayer ) { if ( m_PortalSimulator.IsReadyToSimulate() ) { ICollideable *pCollideable = pPlayer->GetCollideable(); if ( pCollideable ) { Vector vMin, vMax; pCollideable->WorldSpaceSurroundingBounds( &vMin, &vMax ); if ( UTIL_IsBoxIntersectingPortal( ( vMin + vMax ) / 2.0f, ( vMax - vMin ) / 2.0f, this ) ) { Ray_t playerRay; playerRay.Init( pPlayer->GetAbsOrigin(), pPlayer->GetAbsOrigin(), pPlayer->GetPlayerMins(), pPlayer->GetPlayerMaxs() ); trace_t WorldTrace; CTraceFilterSimple traceFilter( pPlayer, COLLISION_GROUP_PLAYER_MOVEMENT ); enginetrace->TraceRay( playerRay, MASK_PLAYERSOLID, &traceFilter, &WorldTrace ); if( WorldTrace.startsolid ) //player would be stuck unless moving using portal traces. Really good indicator that they're actually in the portal plane. { Vector vForward; GetVectors( &vForward, 0, 0 ); vForward *= 100.0f; pPlayer->VelocityPunch( vForward ); } } } } } void CPortal_Base2D::PunchAllPenetratingPlayers( void ) { for( int i = 1; i <= gpGlobals->maxClients; ++i ) { CBasePlayer *pPlayer = UTIL_PlayerByIndex( i ); if ( pPlayer ) { PunchPenetratingPlayer( pPlayer ); } } } void CPortal_Base2D::Activate( void ) { UpdateCollisionShape(); if( m_pAttachedCloningArea == NULL ) m_pAttachedCloningArea = CPhysicsCloneArea::CreatePhysicsCloneArea( this ); UpdatePortalTeleportMatrix(); UpdatePortalLinkage(); UpdateClientCheckPVS(); BaseClass::Activate(); AddEffects( EF_NOSHADOW | EF_NORECEIVESHADOW ); m_PortalSimulator.SetCarvedParent( GetParent() ); if( IsActive() && (m_hLinkedPortal.Get() != NULL) ) { Vector ptCenter = GetAbsOrigin(); QAngle qAngles = GetAbsAngles(); SetSize( GetLocalMins(), GetLocalMaxs() ); m_PortalSimulator.SetSize( GetHalfWidth(), GetHalfHeight() ); m_PortalSimulator.MoveTo( ptCenter, qAngles ); //resimulate everything we're touching touchlink_t *root = ( touchlink_t * )GetDataObject( TOUCHLINK ); if( root ) { for( touchlink_t *link = root->nextLink; link != root; link = link->nextLink ) { if( (link->flags & FTOUCHLINK_START_TOUCH) == 0 ) continue; //not actually touching this thing CBaseEntity *pOther = link->entityTouched; bool bTeleportable = CPortal_Base2D_Shared::IsEntityTeleportable( pOther ); bool bShouldCloneAcrossPortals = CPortal_Base2D_Shared::ShouldPhysicsCloneNonTeleportableEntityAcrossPortals( pOther ); if( bTeleportable || bShouldCloneAcrossPortals ) { CCollisionProperty *pOtherCollision = pOther->CollisionProp(); Vector vWorldMins, vWorldMaxs; pOtherCollision->WorldSpaceAABB( &vWorldMins, &vWorldMaxs ); Vector ptOtherCenter = (vWorldMins + vWorldMaxs) / 2.0f; if( m_plane_Origin.normal.Dot( ptOtherCenter ) > m_plane_Origin.dist ) { //we should be interacting with this object, add it to our environment if( bTeleportable ) { if( SharedEnvironmentCheck( pOther ) ) { Assert( ((m_PortalSimulator.GetLinkedPortalSimulator() == NULL) && (m_hLinkedPortal.Get() == NULL)) || (m_PortalSimulator.GetLinkedPortalSimulator() == &m_hLinkedPortal->m_PortalSimulator) ); //make sure this entity is linked to the same portal as our simulator CPortalSimulator *pOwningSimulator = CPortalSimulator::GetSimulatorThatOwnsEntity( pOther ); if( pOwningSimulator && (pOwningSimulator != &m_PortalSimulator) ) pOwningSimulator->ReleaseOwnershipOfEntity( pOther ); m_PortalSimulator.TakeOwnershipOfEntity( pOther ); } } else if( bShouldCloneAcrossPortals ) { m_PortalSimulator.StartCloningEntityAcrossPortals( pOther ); } } } } } } } void CPortal_Base2D::Touch( CBaseEntity *pOther ) { if( pOther->IsPlayer() || (pOther == GetMoveParent()) ) return; BaseClass::Touch( pOther ); pOther->Touch( this ); // Don't do anything on touch if it's not active if( !IsActive() || (m_hLinkedPortal.Get() == NULL) ) { Assert( !m_PortalSimulator.OwnsEntity( pOther ) ); Assert( !pOther->IsPlayer() || (((CPortal_Player *)pOther)->m_hPortalEnvironment.Get() != this) ); //I'd really like to fix the root cause, but this will keep the game going m_PortalSimulator.ReleaseOwnershipOfEntity( pOther ); m_PortalSimulator.StopCloningEntityAcrossPortals( pOther ); return; } Assert( IsMobile() || ((m_PortalSimulator.GetLinkedPortalSimulator() == NULL) && (m_hLinkedPortal.Get() == NULL)) || (m_hLinkedPortal->IsMobile()) || (m_PortalSimulator.GetLinkedPortalSimulator() == &m_hLinkedPortal->m_PortalSimulator) ); //make sure this entity is linked to the same portal as our simulator if( IsMobile() || ((m_hLinkedPortal.Get() != NULL) && m_hLinkedPortal->IsMobile()) ) { if( !sv_allow_mobile_portal_teleportation.GetBool() || !pOther->IsPlayer() ) return; } // Fizzle portal with any moving brush Vector vVelocityCheck; AngularImpulse vAngularImpulseCheck; pOther->GetVelocity( &vVelocityCheck, &vAngularImpulseCheck ); if( vVelocityCheck != vec3_origin || vAngularImpulseCheck != vec3_origin ) { if ( modelinfo->GetModelType( pOther->GetModel() ) == mod_brush ) { if ( !FClassnameIs( pOther, "func_physbox" ) && !FClassnameIs( pOther, "simple_physics_brush" ) ) // except CPhysBox { Vector vForward; GetVectors( &vForward, NULL, NULL ); Vector vMin, vMax; pOther->GetCollideable()->WorldSpaceSurroundingBounds( &vMin, &vMax ); if ( UTIL_IsBoxIntersectingPortal( ( vMin + vMax ) / 2.0f, ( vMax - vMin ) / 2.0f - Vector( 2.0f, 2.0f, 2.0f ), this, 0.0f ) && ((pOther->GetSolid() != SOLID_VPHYSICS) || !m_pCollisionShape || UTIL_IsCollideableIntersectingPhysCollide( pOther->GetCollideable(), m_pCollisionShape, m_ptOrigin, m_qAbsAngle )) ) { DevMsg( "Moving brush intersected portal plane.\n" ); DeactivatePortalOnThink(); return; } else { Vector vOrigin = GetAbsOrigin(); trace_t tr; UTIL_TraceLine( vOrigin, vOrigin - vForward * PORTAL_HALF_DEPTH, MASK_SOLID_BRUSHONLY, NULL, COLLISION_GROUP_NONE, &tr ); // Something went wrong if ( tr.fraction == 1.0f && !tr.startsolid ) { DevMsg( "Surface removed from behind portal.\n" ); DeactivatePortalOnThink(); return; } else if ( !sv_allow_mobile_portals.GetBool() && tr.m_pEnt && tr.m_pEnt->IsMoving() ) { DevMsg( "Surface behind portal is moving.\n" ); DeactivatePortalOnThink(); return; } } } } } if( m_hLinkedPortal == NULL ) return; if( sv_portal_high_speed_physics_early_untouch.GetBool() ) { IPhysicsObject *pOtherPhysObject = pOther->VPhysicsGetObject(); if( (pOther->GetMoveType() == MOVETYPE_VPHYSICS) && (pOtherPhysObject != NULL) ) { Vector vPhysVelocity; //physics velocity not necessarily equal to entity velocity pOtherPhysObject->GetVelocity( &vPhysVelocity, NULL ); float fExitSpeed = m_plane_Origin.normal.Dot( vPhysVelocity ); if( fExitSpeed > 200.0f ) //200.0f is a magic number indicating "leaving the portal and unlikely to turn back in a single tick" { const CPhysCollide *pCollide = pOtherPhysObject->GetCollide(); if( pCollide ) { //vphysics object leaving portal at a healthy velocity. //If it's moving fast enough, it will have left our bounds by a large margin before we receive an EndTouch(). It's possible that "large margin" lets the object pass outside // the area that we carved portal collision. See if we should remove it from the portal environment now instead so it always has valid collision Vector vPos; QAngle qAngle; pOtherPhysObject->GetPosition( &vPos, &qAngle ); float fRadius = physcollision->CollideGetRadius( pCollide ); if( (m_plane_Origin.normal.Dot( vPos ) - fRadius) > m_plane_Origin.dist ) { //has fully left portal hole, switching collision should be a safe operation const float fCollisionDataEndsDist = m_PortalSimulator.GetInternalData().Placement.vCollisionCloneExtents.x; //we don't have collision data for the world past this plane! float fDistToEndPlane = -((m_plane_Origin.normal.Dot( vPos ) - (m_plane_Origin.dist + fCollisionDataEndsDist)) + fRadius); float fTimeToExit = fDistToEndPlane / fExitSpeed; if( fTimeToExit < TICK_INTERVAL ) { //at our current velocity, we will pass outside our carved collision within a tick, need to switch now. #if 0 //debugging overlays //projection of where we believe we absolutely must be colliding with the real world as a white OBB NDebugOverlay::BoxAngles( vPos + vPhysVelocity * fTimeToExit, pOther->CollisionProp()->OBBMins(), pOther->CollisionProp()->OBBMaxs(), qAngle, 255, 255, 255, 64, 30.0f ); //where we are right now as a green OBB NDebugOverlay::BoxAngles( vPos, pOther->CollisionProp()->OBBMins(), pOther->CollisionProp()->OBBMaxs(), qAngle, 0, 255, 0, 64, 30.0f ); #endif m_PortalSimulator.ReleaseOwnershipOfEntity( pOther ); return; } } } } } } bool bTeleportable = CPortal_Base2D_Shared::IsEntityTeleportable( pOther ); //see if we should even be interacting with this object, this is a bugfix where some objects get added to physics environments through walls if( !IsMobile() && !m_hLinkedPortal->IsMobile() ) { bool bShouldCloneAcrossPortals = CPortal_Base2D_Shared::ShouldPhysicsCloneNonTeleportableEntityAcrossPortals( pOther ); if( bTeleportable || bShouldCloneAcrossPortals ) { CCollisionProperty *pOtherCollision = pOther->CollisionProp(); Vector vWorldMins, vWorldMaxs; pOtherCollision->WorldSpaceAABB( &vWorldMins, &vWorldMaxs ); Vector ptOtherCenter = (vWorldMins + vWorldMaxs) / 2.0f; //hmm, not in our environment, plane tests, sharing tests if( (m_plane_Origin.normal.Dot( ptOtherCenter ) >= m_plane_Origin.dist) ) { if( bTeleportable && !m_PortalSimulator.OwnsEntity( pOther ) ) { if( SharedEnvironmentCheck( pOther ) ) { CPortalSimulator *pOwningSimulator = CPortalSimulator::GetSimulatorThatOwnsEntity( pOther ); if( pOwningSimulator && (pOwningSimulator != &m_PortalSimulator) ) pOwningSimulator->ReleaseOwnershipOfEntity( pOther ); m_PortalSimulator.TakeOwnershipOfEntity( pOther ); } } else if( bShouldCloneAcrossPortals ) { m_PortalSimulator.StartCloningEntityAcrossPortals( pOther ); } } } } if( bTeleportable && ShouldTeleportTouchingEntity( pOther ) && (m_PortalSimulator.OwnsEntity( pOther ) || IsMobile() || m_hLinkedPortal->IsMobile()) ) { TeleportTouchingEntity( pOther ); } } void CPortal_Base2D::StartTouch( CBaseEntity *pOther ) { if( pOther->IsPlayer() || (pOther == GetMoveParent()) ) return; BaseClass::StartTouch( pOther ); // Since prop_portal is a trigger it doesn't send back start touch, so I'm forcing it pOther->StartTouch( this ); if( sv_portal_debug_touch.GetBool() ) { Vector vVelocity = Portal_FindUsefulVelocity( pOther ); DevMsg( "Portal %i StartTouch: %s : %f %f %f : %f\n", ((m_bIsPortal2)?(2):(1)), pOther->GetClassname(), vVelocity.x, vVelocity.y, vVelocity.z, gpGlobals->curtime ); } #if !defined ( DISABLE_DEBUG_HISTORY ) if ( !IsMarkedForDeletion() ) { ADD_DEBUG_HISTORY( HISTORY_PLAYER_DAMAGE, UTIL_VarArgs( "Portal %i StartTouch: %s : %f\n", ((m_bIsPortal2)?(2):(1)), pOther->GetClassname(), gpGlobals->curtime ) ); } #endif if( (m_hLinkedPortal == NULL) || (IsActive() == false) || IsMobile() || m_hLinkedPortal->IsMobile() ) return; bool bTeleportable = CPortal_Base2D_Shared::IsEntityTeleportable( pOther ); bool bShouldCloneAcrossPortals = CPortal_Base2D_Shared::ShouldPhysicsCloneNonTeleportableEntityAcrossPortals( pOther ); if( bTeleportable || bShouldCloneAcrossPortals ) { CCollisionProperty *pOtherCollision = pOther->CollisionProp(); Vector vWorldMins, vWorldMaxs; pOtherCollision->WorldSpaceAABB( &vWorldMins, &vWorldMaxs ); Vector ptOtherCenter = (vWorldMins + vWorldMaxs) / 2.0f; if( m_plane_Origin.normal.Dot( ptOtherCenter ) > m_plane_Origin.dist ) { //we should be interacting with this object, add it to our environment if( bTeleportable ) { if( SharedEnvironmentCheck( pOther ) ) { Assert( IsMobile() || m_hLinkedPortal->IsMobile() || ((m_PortalSimulator.GetLinkedPortalSimulator() == NULL) && (m_hLinkedPortal.Get() == NULL)) || (m_PortalSimulator.GetLinkedPortalSimulator() == &m_hLinkedPortal->m_PortalSimulator) ); //make sure this entity is linked to the same portal as our simulator CPortalSimulator *pOwningSimulator = CPortalSimulator::GetSimulatorThatOwnsEntity( pOther ); if( pOwningSimulator && (pOwningSimulator != &m_PortalSimulator) ) pOwningSimulator->ReleaseOwnershipOfEntity( pOther ); m_PortalSimulator.TakeOwnershipOfEntity( pOther ); } } else if( bShouldCloneAcrossPortals ) { m_PortalSimulator.StartCloningEntityAcrossPortals( pOther ); } } } } void CPortal_Base2D::EndTouch( CBaseEntity *pOther ) { if ( pOther->IsPlayer() || (pOther == GetMoveParent()) ) return; BaseClass::EndTouch( pOther ); // Since prop_portal is a trigger it doesn't send back end touch, so I'm forcing it pOther->EndTouch( this ); // Don't do anything on end touch if it's not active if ( !IsActive() || IsMobile() || ((m_hLinkedPortal.Get() != NULL) && m_hLinkedPortal->IsMobile()) ) { return; } if ( ShouldTeleportTouchingEntity( pOther ) ) //an object passed through the plane and all the way out of the touch box { TeleportTouchingEntity( pOther ); } else if ( pOther->IsPlayer() && //player IsCeilingPortal( -0.7071f ) && //most likely falling out of the portal (m_PortalSimulator.GetInternalData().Placement.PortalPlane.m_Normal.Dot( pOther->WorldSpaceCenter() ) < m_PortalSimulator.GetInternalData().Placement.PortalPlane.m_Dist) && //but behind the portal plane (((CPortal_Player *)pOther)->m_Local.m_bInDuckJump) ) //while ducking { //player has pulled their feet up (moving their center instantaneously) while falling downward out of the portal, send them back (probably only for a frame) DevMsg( "Player pulled feet above the portal they fell out of, postponing Releasing ownership\n" ); //TeleportTouchingEntity( pOther ); } else { //only 1 of these 2 calls should actually perform work depending on how the entity interacts with portals m_PortalSimulator.ReleaseOwnershipOfEntity( pOther ); m_PortalSimulator.StopCloningEntityAcrossPortals( pOther ); } if ( sv_portal_debug_touch.GetBool() ) { Vector vVelocity = Portal_FindUsefulVelocity( pOther ); DevMsg( "Portal %i EndTouch: %s : %f %f %f : %f\n", ((m_bIsPortal2)?(2):(1)), pOther->GetClassname(), vVelocity.x, vVelocity.y, vVelocity.z, gpGlobals->curtime ); } #if !defined( DISABLE_DEBUG_HISTORY ) if ( !IsMarkedForDeletion() ) { ADD_DEBUG_HISTORY( HISTORY_PLAYER_DAMAGE, UTIL_VarArgs( "Portal %i EndTouch: %s : %f\n", ((m_bIsPortal2)?(2):(1)), pOther->GetClassname(), gpGlobals->curtime ) ); } #endif } bool CPortal_Base2D::SharedEnvironmentCheck( CBaseEntity *pEntity ) { Assert( IsMobile() || ((m_PortalSimulator.GetLinkedPortalSimulator() == NULL) && (m_hLinkedPortal.Get() == NULL)) || (m_hLinkedPortal->IsMobile()) || (m_PortalSimulator.GetLinkedPortalSimulator() == &m_hLinkedPortal->m_PortalSimulator) ); //make sure this entity is linked to the same portal as our simulator CPortalSimulator *pOwningSimulator = CPortalSimulator::GetSimulatorThatOwnsEntity( pEntity ); if( (pOwningSimulator == NULL) || (pOwningSimulator == &m_PortalSimulator) ) { //nobody else is claiming ownership return true; } Vector ptCenter = pEntity->WorldSpaceCenter(); if( (ptCenter - m_PortalSimulator.GetInternalData().Placement.ptCenter).LengthSqr() < (ptCenter - pOwningSimulator->GetInternalData().Placement.ptCenter).LengthSqr() ) return true; /*if( !m_hLinkedPortal->m_PortalSimulator.EntityIsInPortalHole( pEntity ) ) { Vector vOtherVelocity; pEntity->GetVelocity( &vOtherVelocity ); if( vOtherVelocity.Dot( m_PortalSimulator.GetInternalData().Placement.vForward ) < vOtherVelocity.Dot( m_hLinkedPortal->m_PortalSimulator.GetInternalData().Placement.vForward ) ) return true; //entity is going towards this portal more than the other }*/ return false; //we're in the shared configuration, and the other portal already owns the object, see if we'd be a better caretaker (distance check /*CCollisionProperty *pEntityCollision = pEntity->CollisionProp(); Vector vWorldMins, vWorldMaxs; pEntityCollision->WorldSpaceAABB( &vWorldMins, &vWorldMaxs ); Vector ptEntityCenter = (vWorldMins + vWorldMaxs) / 2.0f; Vector vEntToThis = GetAbsOrigin() - ptEntityCenter; Vector vEntToRemote = m_hLinkedPortal->GetAbsOrigin() - ptEntityCenter; return ( vEntToThis.LengthSqr() < vEntToRemote.LengthSqr() );*/ } void CPortal_Base2D::WakeNearbyEntities( void ) { CBaseEntity* pList[ 1024 ]; Vector vForward, vUp, vRight; GetVectors( &vForward, &vRight, &vUp ); Vector ptOrigin = GetAbsOrigin(); QAngle qAngles = GetAbsAngles(); Vector vLocalMins = GetLocalMins(); Vector vLocalMaxs = GetLocalMaxs(); Vector ptOBBStart = ptOrigin; ptOBBStart += vForward * vLocalMins.x; ptOBBStart += vRight * vLocalMins.y; ptOBBStart += vUp * vLocalMins.z; vForward *= vLocalMaxs.x - vLocalMins.x; vRight *= vLocalMaxs.y - vLocalMins.y; vUp *= vLocalMaxs.z - vLocalMins.z; Vector vAABBMins, vAABBMaxs; vAABBMins = vAABBMaxs = ptOBBStart; for( int i = 1; i != 8; ++i ) { Vector ptTest = ptOBBStart; if( i & (1 << 0) ) ptTest += vForward; if( i & (1 << 1) ) ptTest += vRight; if( i & (1 << 2) ) ptTest += vUp; if( ptTest.x < vAABBMins.x ) vAABBMins.x = ptTest.x; if( ptTest.y < vAABBMins.y ) vAABBMins.y = ptTest.y; if( ptTest.z < vAABBMins.z ) vAABBMins.z = ptTest.z; if( ptTest.x > vAABBMaxs.x ) vAABBMaxs.x = ptTest.x; if( ptTest.y > vAABBMaxs.y ) vAABBMaxs.y = ptTest.y; if( ptTest.z > vAABBMaxs.z ) vAABBMaxs.z = ptTest.z; } int count = UTIL_EntitiesInBox( pList, 1024, vAABBMins, vAABBMaxs, 0 ); //Iterate over all the possible targets for ( int i = 0; i < count; i++ ) { CBaseEntity *pEntity = pList[i]; if ( pEntity && (pEntity != this) ) { CCollisionProperty *pEntCollision = pEntity->CollisionProp(); Vector ptEntityCenter = pEntCollision->GetCollisionOrigin(); //double check intersection at the OBB vs OBB level, we don't want to affect large piles of physics objects if we don't have to. It gets slow if( IsOBBIntersectingOBB( ptOrigin, qAngles, vLocalMins, vLocalMaxs, ptEntityCenter, pEntCollision->GetCollisionAngles(), pEntCollision->OBBMins(), pEntCollision->OBBMaxs() ) ) { pEntity->WakeRestingObjects(); //pEntity->SetGroundEntity( NULL ); if ( pEntity->GetMoveType() == MOVETYPE_VPHYSICS ) { IPhysicsObject *pPhysicsObject = pEntity->VPhysicsGetObject(); //Check if the reflective cube is in its disabled state and enable it if ( UTIL_IsReflectiveCube( pEntity ) || UTIL_IsSchrodinger( pEntity ) ) { CPropWeightedCube *pReflectiveCube = assert_cast<CPropWeightedCube*>( pEntity ); pReflectiveCube->ExitDisabledState(); } if ( pPhysicsObject && pPhysicsObject->IsMoveable() ) { pPhysicsObject->Wake(); // If the target is debris, convert it to non-debris if ( pEntity->GetCollisionGroup() == COLLISION_GROUP_DEBRIS ) { // Interactive debris converts back to debris when it comes to rest pEntity->SetCollisionGroup( COLLISION_GROUP_INTERACTIVE_DEBRIS ); } } } } } } } void CPortal_Base2D::ForceEntityToFitInPortalWall( CBaseEntity *pEntity ) { CCollisionProperty *pCollision = pEntity->CollisionProp(); Vector vWorldMins, vWorldMaxs; pCollision->WorldSpaceAABB( &vWorldMins, &vWorldMaxs ); Vector ptCenter = pEntity->WorldSpaceCenter(); //(vWorldMins + vWorldMaxs) / 2.0f; Vector ptOrigin = pEntity->GetAbsOrigin(); Vector vEntityCenterToOrigin = ptOrigin - ptCenter; Vector ptPortalCenter = GetAbsOrigin(); Vector vPortalCenterToEntityCenter = ptCenter - ptPortalCenter; Vector vPortalForward; GetVectors( &vPortalForward, NULL, NULL ); Vector ptProjectedEntityCenter = ptPortalCenter + ( vPortalForward * vPortalCenterToEntityCenter.Dot( vPortalForward ) ); Vector ptDest; if ( m_PortalSimulator.IsReadyToSimulate() ) { Ray_t ray; ray.Init( ptProjectedEntityCenter, ptCenter, vWorldMins - ptCenter, vWorldMaxs - ptCenter ); trace_t ShortestTrace; ShortestTrace.fraction = 2.0f; const PS_SD_Static_Wall_Local_Brushes_t &WallBrushes = m_PortalSimulator.GetInternalData().Simulation.Static.Wall.Local.Brushes; int iTestMask = MASK_SOLID; if( pEntity->IsPlayer() ) { iTestMask |= CONTENTS_PLAYERCLIP; } else if( pEntity->IsNPC() ) { iTestMask |= CONTENTS_MONSTERCLIP; } for( int i = 0; i != ARRAYSIZE( WallBrushes.BrushSets ); ++i ) { if( (WallBrushes.BrushSets[i].iSolidMask & iTestMask) != 0 ) { trace_t TempTrace; physcollision->TraceBox( ray, m_PortalSimulator.GetInternalData().Simulation.Static.Wall.Local.Brushes.BrushSets[i].pCollideable, vec3_origin, vec3_angle, &TempTrace ); if( TempTrace.fraction < ShortestTrace.fraction ) { ShortestTrace = TempTrace; } } } if( ShortestTrace.fraction < 2.0f ) { Vector ptNewPos = ShortestTrace.endpos + vEntityCenterToOrigin; pEntity->Teleport( &ptNewPos, NULL, NULL ); pEntity->AddEffects( EF_NOINTERP ); #if !defined ( DISABLE_DEBUG_HISTORY ) if ( !IsMarkedForDeletion() ) { ADD_DEBUG_HISTORY( HISTORY_PLAYER_DAMAGE, UTIL_VarArgs( "Teleporting %s inside 'ForceEntityToFitInPortalWall'\n", pEntity->GetDebugName() ) ); } #endif if( sv_portal_debug_touch.GetBool() ) { DevMsg( "Teleporting %s inside 'ForceEntityToFitInPortalWall'\n", pEntity->GetDebugName() ); } //pEntity->SetAbsOrigin( ShortestTrace.endpos + vEntityCenterToOrigin ); } } } void CPortal_Base2D::UpdatePortalTeleportMatrix( void ) { //copied from client to ensure the numbers match as closely as possible. { ALIGN16 matrix3x4_t finalMatrix; if( GetMoveParent() ) { // Construct the entity-to-world matrix // Start with making an entity-to-parent matrix ALIGN16 matrix3x4_t matEntityToParent; AngleMatrix( GetLocalAngles(), matEntityToParent ); MatrixSetColumn( GetLocalOrigin(), 3, matEntityToParent ); // concatenate with our parent's transform ALIGN16 matrix3x4_t scratchMatrix; ConcatTransforms( GetParentToWorldTransform( scratchMatrix ), matEntityToParent, finalMatrix ); MatrixGetColumn( finalMatrix, 0, m_vForward ); MatrixGetColumn( finalMatrix, 1, m_vRight ); MatrixGetColumn( finalMatrix, 2, m_vUp ); Vector vTempOrigin; MatrixGetColumn( finalMatrix, 3, vTempOrigin ); m_ptOrigin = vTempOrigin; m_vRight = -m_vRight; QAngle qTempAngle; MatrixAngles( finalMatrix, qTempAngle ); m_qAbsAngle = qTempAngle; } else { AngleMatrix( m_qAbsAngle, finalMatrix ); MatrixGetColumn( finalMatrix, 0, m_vForward ); MatrixGetColumn( finalMatrix, 1, m_vRight ); MatrixGetColumn( finalMatrix, 2, m_vUp ); m_vRight = -m_vRight; } } //setup our origin plane m_plane_Origin.normal = m_vForward; m_plane_Origin.dist = m_plane_Origin.normal.Dot( m_ptOrigin ); m_plane_Origin.signbits = SignbitsForPlane( &m_plane_Origin ); Vector vAbsNormal; vAbsNormal.x = fabs(m_plane_Origin.normal.x); vAbsNormal.y = fabs(m_plane_Origin.normal.y); vAbsNormal.z = fabs(m_plane_Origin.normal.z); if( vAbsNormal.x > vAbsNormal.y ) { if( vAbsNormal.x > vAbsNormal.z ) { if( vAbsNormal.x > 0.999f ) m_plane_Origin.type = PLANE_X; else m_plane_Origin.type = PLANE_ANYX; } else { if( vAbsNormal.z > 0.999f ) m_plane_Origin.type = PLANE_Z; else m_plane_Origin.type = PLANE_ANYZ; } } else { if( vAbsNormal.y > vAbsNormal.z ) { if( vAbsNormal.y > 0.999f ) m_plane_Origin.type = PLANE_Y; else m_plane_Origin.type = PLANE_ANYY; } else { if( vAbsNormal.z > 0.999f ) m_plane_Origin.type = PLANE_Z; else m_plane_Origin.type = PLANE_ANYZ; } } UTIL_Portal_ComputeMatrix( this, m_hLinkedPortal.Get() ); } void CPortal_Base2D::CreateMicAndSpeaker( void ) { RemovePortalMicAndSpeaker(); inputdata_t inputdata; m_hMicrophone = CreateEntityByName( "env_microphone" ); CEnvMicrophone *pMicrophone = static_cast<CEnvMicrophone*>( m_hMicrophone.Get() ); pMicrophone->AddSpawnFlags( SF_MICROPHONE_IGNORE_NONATTENUATED ); pMicrophone->AddSpawnFlags( SF_MICROPHONE_SOUND_COMBAT | SF_MICROPHONE_SOUND_WORLD | SF_MICROPHONE_SOUND_PLAYER | SF_MICROPHONE_SOUND_BULLET_IMPACT | SF_MICROPHONE_SOUND_EXPLOSION ); DispatchSpawn( pMicrophone ); m_hSpeaker = CreateEntityByName( "env_speaker" ); CSpeaker *pSpeaker = static_cast<CSpeaker*>( m_hSpeaker.Get() ); float flMicrophoneSensitivity = sv_portal_microphone_sensitivity.GetFloat(); flMicrophoneSensitivity = clamp( flMicrophoneSensitivity, 0.0f, 10.0f ); float flMicrophoneRange = sv_portal_microphone_max_range.GetFloat(); if ( flMicrophoneRange < 0.0f ) { flMicrophoneRange = 0.0f; } pSpeaker->SetName( MAKE_STRING( m_bIsPortal2 ? "PortalMicrophone_2" : "PortalMicrophone_1" ) ); pMicrophone->SetName( MAKE_STRING( m_bIsPortal2 ? "PortalSpeaker_2" : "PortalSpeaker_1" ) ); pMicrophone->Activate(); pMicrophone->SetSensitivity( flMicrophoneSensitivity ); pMicrophone->SetMaxRange( flMicrophoneRange ); // Set microphone/speaker positions pMicrophone->AddSpawnFlags( SF_MICROPHONE_IGNORE_NONATTENUATED ); pMicrophone->Teleport( &GetAbsOrigin(), &GetAbsAngles(), &vec3_origin ); pSpeaker->Teleport( &GetAbsOrigin(), &GetAbsAngles(), &vec3_origin ); } void CPortal_Base2D::UpdatePortalLinkage( void ) { if( IsActive() ) { CPortal_Base2D *pLink = m_hLinkedPortal.Get(); if( pLink != NULL ) { CHandle<CPortal_Base2D> hThis = this; CHandle<CPortal_Base2D> hRemote = pLink; this->m_hLinkedPortal = hRemote; pLink->m_hLinkedPortal = hThis; m_bIsPortal2 = !m_hLinkedPortal->m_bIsPortal2; // Link up mic and speakers to remote portal // NOTE: This does the work for both portals if( sv_portal_enable_microphone.GetInt() ) { if ( m_bMicAndSpeakersLinkedToRemote == false ) { // Initialize mics/speakers if( m_hMicrophone.Get() == NULL || m_hSpeaker.Get() == NULL ) { CreateMicAndSpeaker(); } if ( m_hLinkedPortal->m_hMicrophone.Get() == NULL || m_hSpeaker.Get() == NULL ) { m_hLinkedPortal->CreateMicAndSpeaker(); } // Cross link the mics and speakers CEnvMicrophone* pMyMic = dynamic_cast<CEnvMicrophone*>( m_hMicrophone.Get() ); CEnvMicrophone* pRemoteMic = dynamic_cast<CEnvMicrophone*>( m_hLinkedPortal->m_hMicrophone.Get() ); Assert( pMyMic && pRemoteMic && m_hSpeaker.Get() && m_hLinkedPortal->m_hSpeaker.Get() ); if ( pMyMic ) { pMyMic->SetSpeaker( m_hLinkedPortal->m_hSpeaker->GetEntityName(), m_hLinkedPortal->m_hSpeaker ); } if ( pRemoteMic ) { pRemoteMic->SetSpeaker( m_hSpeaker->GetEntityName(), m_hSpeaker ); } m_bMicAndSpeakersLinkedToRemote = true; m_hLinkedPortal->m_bMicAndSpeakersLinkedToRemote = true; } } UpdatePortalTeleportMatrix(); } else { m_PortalSimulator.DetachFromLinked(); m_PortalSimulator.ReleaseAllEntityOwnership(); if ( m_hMicrophone.Get() ) { CEnvMicrophone* pMyMic = dynamic_cast<CEnvMicrophone*>( m_hMicrophone.Get() ); if ( pMyMic ) { pMyMic->SetSpeaker( NULL_STRING, NULL ); } } m_bMicAndSpeakersLinkedToRemote = false; } m_PortalSimulator.SetSize( GetHalfWidth(), GetHalfHeight() ); m_PortalSimulator.MoveTo( m_ptOrigin, m_qAbsAngle ); if( pLink ) { m_PortalSimulator.AttachTo( &pLink->m_PortalSimulator ); if( IsMobile() || pLink->IsMobile() ) { SetSize( GetLocalMins(), Vector( 4.0f, m_fNetworkHalfWidth, m_fNetworkHalfHeight ) ); pLink->SetSize( GetLocalMins(), Vector( 4.0f, m_fNetworkHalfWidth, m_fNetworkHalfHeight ) ); } else { SetSize( GetLocalMins(), GetLocalMaxs() ); pLink->SetSize( GetLocalMins(), GetLocalMaxs() ); } } if( m_pAttachedCloningArea ) m_pAttachedCloningArea->UpdatePosition(); } else { CPortal_Base2D *pRemote = m_hLinkedPortal; //apparently we've been deactivated m_PortalSimulator.DetachFromLinked(); m_PortalSimulator.ReleaseAllEntityOwnership(); m_hLinkedPortal = NULL; if( pRemote ) { pRemote->UpdatePortalLinkage(); } } if( m_bIsPortal2 ) { m_PortalSimulator.EditDebuggingData().overlayColor.SetColor( 255, 0, 0, 255 ); } else { m_PortalSimulator.EditDebuggingData().overlayColor.SetColor( 0, 0, 255, 255 ); } // 79483: We have a handle on perf now and don't need to dump this every portal placement. #if 0 #if !defined( _CERT ) // Make sure we have the last state of all portals in the console log, in case of a crash PortalReportFunc( true ); #endif // !_CERT #endif } //#define STACK_ANALYZE_PORTALPLACEMENT #if defined( STACK_ANALYZE_PORTALPLACEMENT ) struct PortalPlacementInfo_t { DECLARE_CALLSTACKSTATSTRUCT(); DECLARE_CALLSTACKSTATSTRUCT_FIELDDESCRIPTION(); int iEntered; int iActuallyMoved; int iMaxTest; int iMinTest; }; BEGIN_STATSTRUCTDESCRIPTION( PortalPlacementInfo_t ) WRITE_STATSTRUCT_FIELDDESCRIPTION(); //WRITE_STATSTRUCT_FIELDMERGESCRIPT( SSMSL_Squirrel ); END_STATSTRUCTDESCRIPTION() BEGIN_STATSTRUCTFIELDDESCRIPTION( PortalPlacementInfo_t ) DEFINE_STATSTRUCTFIELD( iEntered, BasicStatStructFieldDesc, ( BSSFT_INT32, BSSFCM_ADD ) ) DEFINE_STATSTRUCTFIELD( iActuallyMoved, BasicStatStructFieldDesc, ( BSSFT_INT32, BSSFCM_ADD ) ) DEFINE_STATSTRUCTFIELD( iMaxTest, BasicStatStructFieldDesc, ( BSSFT_INT32, BSSFCM_MAX ) ) DEFINE_STATSTRUCTFIELD( iMinTest, BasicStatStructFieldDesc, ( BSSFT_INT32, BSSFCM_MIN ) ) END_STATSTRUCTFIELDDESCRIPTION() CCallStackStatsGatherer<PortalPlacementInfo_t, 32, GetCallStack_Fast> s_PortalPlacementStats; CCallStackStatsGatherer_Standardized_t g_PlacementStats = s_PortalPlacementStats; void DumpPlacementStats() { s_PortalPlacementStats.DumpToFile( "PlacementStats.vcsf" ); } static ConCommand dump_placement( "dump_placement", DumpPlacementStats, "", FCVAR_CHEAT ); #endif void CPortal_Base2D::NewLocation( const Vector &vOrigin, const QAngle &qAngles ) { #if defined( STACK_ANALYZE_PORTALPLACEMENT ) CCallStackStatsGatherer_StructAccessor_AutoLock<PortalPlacementInfo_t> entry = s_PortalPlacementStats.GetEntry(); ++entry->iEntered; entry->iMaxTest = RandomInt(0, 10000); entry->iMinTest = RandomInt(0, 10000); if( vOrigin != m_ptOrigin || qAngles != m_qAbsAngle ) { ++entry->iActuallyMoved; } #endif // Tell our physics environment to stop simulating it's entities. // Fast moving objects can pass through the hole this frame while it's in the old location. m_PortalSimulator.ReleaseAllEntityOwnership(); Vector vOldForward; GetVectors( &vOldForward, 0, 0 ); m_vPrevForward = vOldForward; SetParent( NULL ); SetAbsVelocity( vec3_origin ); WakeNearbyEntities(); SetMobileState( false ); Teleport( &vOrigin, &qAngles, 0 ); m_ptOrigin = vOrigin; m_qAbsAngle = qAngles; if ( m_hMicrophone ) { CEnvMicrophone *pMicrophone = static_cast<CEnvMicrophone*>( m_hMicrophone.Get() ); pMicrophone->Teleport( &vOrigin, &qAngles, 0 ); inputdata_t inMicEnable; pMicrophone->InputEnable( inMicEnable ); } if ( m_hSpeaker ) { CSpeaker *pSpeaker = static_cast<CSpeaker*>( m_hSpeaker.Get() ); pSpeaker->Teleport( &vOrigin, &qAngles, 0 ); inputdata_t inTurnOn; pSpeaker->InputTurnOn( inTurnOn ); } //if the other portal should be static, let's not punch stuff resting on it bool bOtherShouldBeStatic = false; if( !m_hLinkedPortal ) bOtherShouldBeStatic = true; if ( IsActive() ) { BroadcastPortalEvent( PORTALEVENT_MOVED ); } SetActive( true ); UpdatePortalLinkage(); UpdatePortalTeleportMatrix(); // Update the four corners of this portal for faster reference UpdateCorners(); WakeNearbyEntities(); // Make sure it's not a floor portal... allowing those to punch creates a floor to floor exploit if ( !IsFloorPortal() ) { if ( m_hLinkedPortal ) { m_hLinkedPortal->WakeNearbyEntities(); if ( !bOtherShouldBeStatic ) { m_hLinkedPortal->PunchAllPenetratingPlayers(); } } } UpdateClientCheckPVS(); CBaseEntity *pAttachedToMovingEntity; //check to see if we landed on an entity that could potentially move { trace_t tr; Vector vForward, vUp; AngleVectors( qAngles, &vForward, NULL, &vUp ); UTIL_TraceLine( vOrigin + vForward * 5.0f, vOrigin - vForward * 10.0f, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); if( tr.m_pEnt && ((tr.m_pEnt->GetMoveType() != MOVETYPE_NONE) || (tr.m_pEnt->GetParent() != NULL)) ) { pAttachedToMovingEntity = tr.m_pEnt; QAngle qNewAngles; //recompute the angles since they may have changed between when we fired and when we landed VectorAngles( vForward, vUp, qNewAngles ); SetAbsAngles( qNewAngles ); SetAbsOrigin( tr.endpos ); m_ptOrigin = tr.endpos; m_qAbsAngle = qNewAngles; } else { pAttachedToMovingEntity = NULL; } } if( pAttachedToMovingEntity ) { SetMoveType( MOVETYPE_NOCLIP ); //switch the movetype to something that gets CPortal_Base2D::PhysicsSimulate() called. SetParent( pAttachedToMovingEntity ); } else { SetMoveType( MOVETYPE_NONE ); } m_PortalSimulator.SetCarvedParent( pAttachedToMovingEntity ); SetMobileState( sv_allow_mobile_portals.GetBool() && (pAttachedToMovingEntity != NULL) && UTIL_IsEntityMovingOrRotating( pAttachedToMovingEntity ) ); m_vPortalSpawnLocation = m_ptOrigin; PhysicsTouchTriggers( NULL ); } void CPortal_Base2D::PhysicsSimulate( void ) { BaseClass::PhysicsSimulate(); //update as if placed in a new position if we're mobile bool bMoving = GetParent() && UTIL_IsEntityMovingOrRotating( GetParent() ); bool bPortalMoving = m_vPortalSpawnLocation.IsValid() && m_vPortalSpawnLocation.DistToSqr( GetAbsOrigin() ) > 0.1f; if( ( bMoving || bPortalMoving ) && !sv_allow_mobile_portals.GetBool() ) { DeactivatePortalOnThink(); SetMoveType( MOVETYPE_NONE ); SetParent( NULL ); return; } SetMobileState( bMoving ); if( bMoving ) { UpdatePortalLinkage(); //this needs to change names or something. It does so much more than just linkage UpdatePortalTeleportMatrix(); m_PortalSimulator.MoveTo( m_ptOrigin, m_qAbsAngle ); UpdateCorners(); #if 0 //mobile portal debugging code NDebugOverlay::EntityBounds( this, 0, 255, 0, 50, 10.0f ); CPortal_Base2D *pLinked = m_hLinkedPortal; if( m_hLinkedPortal ) { Vector vTransformedOrigin = pLinked->m_PortalSimulator.m_DataAccess.Placement.matThisToLinked * pLinked->m_PortalSimulator.m_DataAccess.Placement.ptCenter; Vector vTransformedForward = pLinked->m_PortalSimulator.m_DataAccess.Placement.matThisToLinked.ApplyRotation( pLinked->m_PortalSimulator.m_DataAccess.Placement.vForward ); NDebugOverlay::Line( vTransformedOrigin, vTransformedOrigin + vTransformedForward * (-50.0f), 100, 0, 0, true, 10.0f ); } #endif } } void CPortal_Base2D::SetMobileState( bool bSet ) { if( m_bIsMobile != bSet ) { m_bIsMobile = bSet; if( bSet ) { //disable physics if it's setup //m_PortalSimulator.DetachFromLinked(); m_PortalSimulator.SetCollisionGenerationEnabled( false ); m_PortalSimulator.ReleaseAllEntityOwnership(); if( m_hLinkedPortal.Get() != NULL ) { m_hLinkedPortal->m_PortalSimulator.ReleaseAllEntityOwnership(); } if( IsActive() && (GetNextThink( s_szTestRestingSurfaceThinkContext ) == TICK_NEVER_THINK) ) SetContextThink( &CPortal_Base2D::TestRestingSurfaceThink, gpGlobals->curtime + 0.1f, s_szTestRestingSurfaceThinkContext ); } else { //re-enable physics if we're supposed to have it working m_PortalSimulator.SetCollisionGenerationEnabled( true ); if( IsActive() ) { UpdatePortalTeleportMatrix(); m_PortalSimulator.MoveTo( m_ptOrigin, m_qAbsAngle ); m_PortalSimulator.SetSize( GetHalfWidth(), GetHalfHeight() ); CPortal_Base2D *pLink = m_hLinkedPortal.Get(); if( pLink && !pLink->m_bIsMobile ) m_PortalSimulator.AttachTo( &pLink->m_PortalSimulator ); } } bool bSmallSize = bSet; CPortal_Base2D *pLinked = m_hLinkedPortal; if( pLinked ) { bSmallSize |= pLinked->IsMobile(); pLinked->SetSize( pLinked->GetLocalMins(), bSmallSize ? Vector( 4.0f, pLinked->m_fNetworkHalfWidth, pLinked->m_fNetworkHalfHeight ) : pLinked->GetLocalMaxs() ); } SetSize( GetLocalMins(), bSmallSize ? Vector( 4.0f, m_fNetworkHalfWidth, m_fNetworkHalfHeight ) : GetLocalMaxs() ); } } void CPortal_Base2D::Resize( float fHalfWidth, float fHalfHeight ) { if( (fHalfWidth == m_fNetworkHalfWidth) && (fHalfHeight == m_fNetworkHalfHeight) ) return; m_fNetworkHalfWidth = fHalfWidth; m_fNetworkHalfHeight = fHalfHeight; CPortal_Base2D *pLinked = m_hLinkedPortal; if( pLinked ) { if( (m_fNetworkHalfWidth != pLinked->m_fNetworkHalfWidth) || (m_fNetworkHalfHeight != pLinked->m_fNetworkHalfHeight) ) { //different portal sizes, unsupported, unlink. Scaling is a whole different ball of wax. //if you're resizing both portals. They'll find eachother in UpdatePortalLinkage() once they're both resized. m_hLinkedPortal = NULL; m_PortalSimulator.DetachFromLinked(); pLinked->m_hLinkedPortal = NULL; pLinked->m_PortalSimulator.DetachFromLinked(); } } UpdateCollisionShape(); if( m_pAttachedCloningArea ) m_pAttachedCloningArea->Resize( fHalfWidth, fHalfHeight ); m_PortalSimulator.SetSize( fHalfWidth, fHalfHeight ); if( pLinked ) pLinked->UpdatePortalLinkage(); UpdatePortalLinkage(); CBaseProjector::TestAllForProjectionChanges(); } void CPortal_Base2D::UpdateClientCheckPVS( void ) { for ( int i = 1; i <= gpGlobals->maxClients; ++i ) { CPortal_Player *pPlayer = dynamic_cast<CPortal_Player*>(UTIL_PlayerByIndex( i )); if ( pPlayer == NULL ) continue; pPlayer->MarkClientCheckPVSDirty(); } } void CPortal_Base2D::UpdateCorners() { Vector vOrigin = m_ptOrigin; Vector vUp, vRight; GetVectors( NULL, &vRight, &vUp ); vRight *= m_fNetworkHalfWidth; vUp *= m_fNetworkHalfHeight; m_vPortalCorners[0] = (vOrigin + vRight) + vUp; m_vPortalCorners[1] = (vOrigin - vRight) + vUp; m_vPortalCorners[2] = (vOrigin - vRight) - vUp; m_vPortalCorners[3] = (vOrigin + vRight) - vUp; } //----------------------------------------------------------------------------- // Purpose: Tell all listeners about an event that just occurred //----------------------------------------------------------------------------- void CPortal_Base2D::OnPortalDeactivated( void ) { BroadcastPortalEvent( PORTALEVENT_FIZZLE ); CBaseProjector::TestAllForProjectionChanges(); } //----------------------------------------------------------------------------- // Purpose: Tell all listeners about an event that just occurred //----------------------------------------------------------------------------- void CPortal_Base2D::BroadcastPortalEvent( PortalEvent_t nEventType ) { /* switch( nEventType ) { case PORTALEVENT_MOVED: Msg("[ Portal moved ]\n"); break; case PORTALEVENT_FIZZLE: Msg("[ Portal fizzled ]\n"); break; case PORTALEVENT_LINKED: Msg("[ Portal linked ]\n"); break; } */ // We need to walk the list backwards because callers can remove themselves from our list as they're notified for ( int i = m_PortalEventListeners.Count()-1; i >= 0; i-- ) { if ( m_PortalEventListeners[i] == NULL ) continue; m_PortalEventListeners[i]->NotifyPortalEvent( nEventType, this ); } } //----------------------------------------------------------------------------- // Purpose: Add a listener to our collection //----------------------------------------------------------------------------- void CPortal_Base2D::AddPortalEventListener( EHANDLE hListener ) { // Don't multiply add if ( m_PortalEventListeners.Find( hListener ) != m_PortalEventListeners.InvalidIndex() ) return; m_PortalEventListeners.AddToTail( hListener ); } //----------------------------------------------------------------------------- // Purpose: Remove a listener to our collection //----------------------------------------------------------------------------- void CPortal_Base2D::RemovePortalEventListener( EHANDLE hListener ) { m_PortalEventListeners.FindAndFastRemove( hListener ); } // Adds the PVS of the cluster where the portal's partner is placed to the parameter PVS. // NOTE: adds the *LINKED* portal's cluster, not the parameter portal. void AddPortalVisibilityToPVS( CPortal_Base2D* pPortal, int outputpvslength, unsigned char *outputpvs ) { Assert( pPortal ); if ( pPortal && pPortal->IsActivedAndLinked() ) { CPortal_Base2D* pLinked = pPortal->m_hLinkedPortal.Get(); int iCluster = engine->GetClusterForOrigin( pLinked->GetAbsOrigin() ); // get the pvs for the linked portal's cluster byte pvs[MAX_MAP_LEAFS/8]; engine->GetPVSForCluster( iCluster, sizeof( pvs ), pvs ); // Do the bulk on blocks of 4 uint32 nDWords = outputpvslength / 4; uint32 *pInputDWords = (uint32*)pvs; uint32 *RESTRICT pOutputDWords = (uint32*)outputpvs; for ( int i=0; i<nDWords; ++i ) { pOutputDWords[ i ] |= pInputDWords[ i ]; } // Do the remaining (up to 3) in bytes for ( int i=nDWords * 4; i<outputpvslength; ++i ) { outputpvs[ i ] |= pvs[ i ]; } } } CServerNetworkProperty *CPortal_Base2D::GetExtenderNetworkProp( void ) { return NetworkProp(); } const edict_t *CPortal_Base2D::GetExtenderEdict( void ) const { return edict(); } Vector CPortal_Base2D::GetExtensionPVSOrigin( void ) { return GetAbsOrigin() + m_plane_Origin.normal; } bool CPortal_Base2D::IsExtenderValid( void ) { return IsActivedAndLinked(); } int CPortal_Base2D::GetPolyVertCount( void ) { return 4; } int CPortal_Base2D::ComputeFrustumThroughPolygon( const Vector &vVisOrigin, const VPlane *pInputFrustum, int iInputFrustumPlanes, VPlane *pOutputFrustum, int iOutputFrustumMaxPlanes ) { int iReturnedPlanes = UTIL_CalcFrustumThroughConvexPolygon( m_vPortalCorners, 4, vVisOrigin, pInputFrustum, iInputFrustumPlanes, pOutputFrustum, iOutputFrustumMaxPlanes, 0 ); if( (iReturnedPlanes < iOutputFrustumMaxPlanes) && (iReturnedPlanes != 0) ) { //add the portal plane as a near plane pOutputFrustum[iReturnedPlanes].Init( -m_plane_Origin.normal, -m_plane_Origin.dist ); ++iReturnedPlanes; } return iReturnedPlanes; } ////////////////////////////////////////////////////////////////////////// // AddPortalCornersToEnginePVS // Subroutine to wrap the adding of portal corners to the PVS which is called once for the setup of each portal. // input - pPortal: the portal we are viewing 'out of' which needs it's corners added to the PVS ////////////////////////////////////////////////////////////////////////// void AddPortalCornersToEnginePVS( CPortal_Base2D* pPortal ) { Assert ( pPortal ); if ( !pPortal ) return; Vector vForward, vRight, vUp; pPortal->GetVectors( &vForward, &vRight, &vUp ); // Center of the remote portal Vector ptOrigin = pPortal->GetAbsOrigin(); // Distance offsets to the different edges of the portal... Used in the placement checks Vector vToTopEdge = vUp * ( pPortal->GetHalfHeight() - PORTAL_BUMP_FORGIVENESS ); Vector vToBottomEdge = -vToTopEdge; Vector vToRightEdge = vRight * ( pPortal->GetHalfWidth() - PORTAL_BUMP_FORGIVENESS ); Vector vToLeftEdge = -vToRightEdge; // Distance to place PVS points away from portal, to avoid being in solid Vector vForwardBump = vForward * 1.0f; // Add center and edges to the engine PVS engine->AddOriginToPVS( ptOrigin + vForwardBump); engine->AddOriginToPVS( ptOrigin + vToTopEdge + vToLeftEdge + vForwardBump ); engine->AddOriginToPVS( ptOrigin + vToTopEdge + vToRightEdge + vForwardBump ); engine->AddOriginToPVS( ptOrigin + vToBottomEdge + vToLeftEdge + vForwardBump ); engine->AddOriginToPVS( ptOrigin + vToBottomEdge + vToRightEdge + vForwardBump ); } void CPortal_Base2D::ComputeSubVisibility( CPVS_Extender **pExtenders, int iExtenderCount, unsigned char *outputPVS, int pvssize, const Vector &vVisOrigin, const VPlane *pVisFrustum, int iVisFrustumPlanes, VisExtensionChain_t *pVisChain, int iAreasNetworked[MAX_MAP_AREAS], int iMaxRecursionsLeft ) { if( iAreasNetworked[MAX_MAP_AREAS - 1] != -1 ) //early out, can't add any more data if we wanted to return; if( m_plane_Origin.normal.Dot( vVisOrigin ) < m_plane_Origin.dist ) return; //vis origin is behind the portal plane //both test if the portal is within the view frustum, and calculate the new one at the same time int iFrustumPlanesMax = (iVisFrustumPlanes + GetPolyVertCount() + 1); VPlane *pNewFrustum = (VPlane *)stackalloc( sizeof( VPlane ) * iFrustumPlanesMax ); int iNewFrustumPlanes = ComputeFrustumThroughPolygon( vVisOrigin, pVisFrustum, iVisFrustumPlanes, pNewFrustum, iFrustumPlanesMax ); if( iNewFrustumPlanes == 0 ) { //NDebugOverlay::EntityBounds( this, 255, 0, 0, 100, 0.0f ); return; } //NDebugOverlay::EntityBounds( this, 0, 255, 0, 100, 0.0f ); CPortal_Base2D *pLinkedPortal = m_hLinkedPortal.Get(); int iLinkedArea = pLinkedPortal->NetworkProp()->AreaNum(); unsigned char *pLinkedPVS = pLinkedPortal->m_pExtenderData->iPVSBits; if( !pLinkedPortal->m_pExtenderData->bAddedToPVSAlready ) { bool bFound = false; for( int i = 0; i != MAX_MAP_AREAS; ++i ) { if( iAreasNetworked[i] == iLinkedArea ) { bFound = true; break; } if( iAreasNetworked[i] == -1 ) { bFound = true; //we found it by adding it iAreasNetworked[i] = iLinkedArea; int iOutputPVSIntSize = pvssize / sizeof( unsigned int ); for( int j = 0; j != iOutputPVSIntSize; ++j ) { ((unsigned int *)outputPVS)[j] |= ((unsigned int *)pLinkedPVS)[j]; } for( int j = iOutputPVSIntSize * sizeof( unsigned int ); j != pvssize; ++j ) { outputPVS[j] |= pLinkedPVS[j]; } break; } } AddPortalCornersToEnginePVS( pLinkedPortal ); pLinkedPortal->m_pExtenderData->bAddedToPVSAlready = true; } --iMaxRecursionsLeft; if( iMaxRecursionsLeft == 0 ) return; edict_t *linkedPortalEdict = pLinkedPortal->edict(); VisExtensionChain_t chainNode; chainNode.m_nArea = iLinkedArea; chainNode.pParentChain = pVisChain; //transform vis origin to linked space Vector vTransformedVisOrigin = m_matrixThisToLinked * vVisOrigin; Vector vTranslation = m_matrixThisToLinked.GetTranslation(); //transform the planes into the linked portal space for( int i = 0; i != iNewFrustumPlanes; ++i ) { pNewFrustum[i].m_Normal = m_matrixThisToLinked.ApplyRotation( pNewFrustum[i].m_Normal ); pNewFrustum[i].m_Dist += pNewFrustum[i].m_Normal.Dot( vTranslation ); } Assert( pLinkedPVS != NULL ); //extend the vis by what the linked portal can see for( int i = 0; i != iExtenderCount; ++i ) { CPVS_Extender *pExtender = pExtenders[i]; if ( pExtender->GetExtenderEdict() == linkedPortalEdict ) continue; if ( pExtender->GetExtenderNetworkProp()->IsInPVS( linkedPortalEdict, pLinkedPVS, (MAX_MAP_LEAFS/8) ) ) //test against linked portal PVS, not aggregate PVS { chainNode.pExtender = pExtender; pExtender->ComputeSubVisibility( pExtenders, iExtenderCount, outputPVS, pvssize, vTransformedVisOrigin, pNewFrustum, iNewFrustumPlanes, &chainNode, iAreasNetworked, iMaxRecursionsLeft ); } } } //----------------------------------------------------------------------------- // Purpose: Notify this the supplied entity has teleported to this portal //----------------------------------------------------------------------------- void CPortal_Base2D::OnEntityTeleportedToPortal( CBaseEntity *pEntity ) { m_OnEntityTeleportToMe.FireOutput( this, this ); BroadcastPortalEvent( PORTALEVENT_ENTITY_TELEPORTED_TO ); if ( pEntity->IsPlayer() ) { m_OnPlayerTeleportToMe.FireOutput( this, this ); BroadcastPortalEvent( PORTALEVENT_PLAYER_TELEPORTED_TO ); } } //----------------------------------------------------------------------------- // Purpose: Notify this the supplied entity has teleported from this portal //----------------------------------------------------------------------------- void CPortal_Base2D::OnEntityTeleportedFromPortal( CBaseEntity *pEntity ) { m_OnEntityTeleportFromMe.FireOutput( this, this ); BroadcastPortalEvent( PORTALEVENT_ENTITY_TELEPORTED_FROM ); if ( pEntity->IsPlayer() ) { m_OnPlayerTeleportFromMe.FireOutput( this, this ); BroadcastPortalEvent( PORTALEVENT_PLAYER_TELEPORTED_FROM ); } } void EntityPortalled( CPortal_Base2D *pPortal, CBaseEntity *pOther, const Vector &vNewOrigin, const QAngle &qNewAngles, bool bForcedDuck ) { /*if( pOther->IsPlayer() ) { Warning( "Server player portalled %f %f %f %f %f %f %f\n", gpGlobals->curtime, XYZ( vNewOrigin ), XYZ( ((CPortal_Player *)pOther)->pl.v_angle ) ); }*/ for( int i = 1; i <= gpGlobals->maxClients; ++i ) { CPortal_Player *pPlayer = (CPortal_Player *)UTIL_PlayerByIndex( i ); if( pPlayer ) { pPlayer->NetworkPortalTeleportation( pOther, pPortal, gpGlobals->curtime, bForcedDuck ); } } } void DebugPortalCollideables_f( const CCommand &command ) { for( int i = 0; i != CPortal_Base2D_Shared::AllPortals.Count(); ++i ) { CPortal_Base2D *pPortal = CPortal_Base2D_Shared::AllPortals[i]; pPortal->m_PortalSimulator.DebugCollisionOverlay( true, 30.0f ); } } static ConCommand debugportalcollideables("debugportalcollideables", DebugPortalCollideables_f, "Dump all CPhysCollides for all portals to the debug overlay" );
0
0.972481
1
0.972481
game-dev
MEDIA
0.863914
game-dev
0.790802
1
0.790802
lzk228/space-axolotl-14
2,104
Content.Client/Replay/Spectator/ReplaySpectatorSystem.Blockers.cs
using Content.Shared.Hands; using Content.Shared.Interaction.Events; using Content.Shared.Inventory.Events; using Content.Shared.Item; using Content.Shared.Movement.Events; using Content.Shared.Movement.Pulling.Events; using Content.Shared.Throwing; namespace Content.Client.Replay.Spectator; public sealed partial class ReplaySpectatorSystem { private void InitializeBlockers() { // Block most interactions to avoid mispredicts // This **shouldn't** be required, but just in case. SubscribeLocalEvent<ReplaySpectatorComponent, UseAttemptEvent>(OnAttempt); SubscribeLocalEvent<ReplaySpectatorComponent, PickupAttemptEvent>(OnAttempt); SubscribeLocalEvent<ReplaySpectatorComponent, ThrowAttemptEvent>(OnAttempt); SubscribeLocalEvent<ReplaySpectatorComponent, InteractionAttemptEvent>(OnInteractAttempt); SubscribeLocalEvent<ReplaySpectatorComponent, AttackAttemptEvent>(OnAttempt); SubscribeLocalEvent<ReplaySpectatorComponent, DropAttemptEvent>(OnAttempt); SubscribeLocalEvent<ReplaySpectatorComponent, IsEquippingAttemptEvent>(OnAttempt); SubscribeLocalEvent<ReplaySpectatorComponent, IsUnequippingAttemptEvent>(OnAttempt); SubscribeLocalEvent<ReplaySpectatorComponent, UpdateCanMoveEvent>(OnUpdateCanMove); SubscribeLocalEvent<ReplaySpectatorComponent, ChangeDirectionAttemptEvent>(OnUpdateCanMove); SubscribeLocalEvent<ReplaySpectatorComponent, PullAttemptEvent>(OnPullAttempt); } private void OnInteractAttempt(Entity<ReplaySpectatorComponent> ent, ref InteractionAttemptEvent args) { args.Cancelled = true; } private void OnAttempt(EntityUid uid, ReplaySpectatorComponent component, CancellableEntityEventArgs args) { args.Cancel(); } private void OnUpdateCanMove(EntityUid uid, ReplaySpectatorComponent component, CancellableEntityEventArgs args) { args.Cancel(); } private void OnPullAttempt(EntityUid uid, ReplaySpectatorComponent component, PullAttemptEvent args) { args.Cancelled = true; } }
0
0.835259
1
0.835259
game-dev
MEDIA
0.633729
game-dev
0.815406
1
0.815406
provencher/MRTK-Quest-Sample
1,547
Assets/Oculus/Platform/Scripts/RoomOptions.cs
// This file was @generated with LibOVRPlatform/codegen/main. Do not modify it! namespace Oculus.Platform { using System; using System.Collections; using Oculus.Platform.Models; using System.Collections.Generic; using UnityEngine; public class RoomOptions { public RoomOptions() { Handle = CAPI.ovr_RoomOptions_Create(); } public void SetDataStore(string key, string value) { CAPI.ovr_RoomOptions_SetDataStoreString(Handle, key, value); } public void ClearDataStore() { CAPI.ovr_RoomOptions_ClearDataStore(Handle); } public void SetExcludeRecentlyMet(bool value) { CAPI.ovr_RoomOptions_SetExcludeRecentlyMet(Handle, value); } public void SetMaxUserResults(uint value) { CAPI.ovr_RoomOptions_SetMaxUserResults(Handle, value); } public void SetOrdering(UserOrdering value) { CAPI.ovr_RoomOptions_SetOrdering(Handle, value); } public void SetRecentlyMetTimeWindow(TimeWindow value) { CAPI.ovr_RoomOptions_SetRecentlyMetTimeWindow(Handle, value); } public void SetRoomId(UInt64 value) { CAPI.ovr_RoomOptions_SetRoomId(Handle, value); } public void SetTurnOffUpdates(bool value) { CAPI.ovr_RoomOptions_SetTurnOffUpdates(Handle, value); } /// For passing to native C public static explicit operator IntPtr(RoomOptions options) { return options != null ? options.Handle : IntPtr.Zero; } ~RoomOptions() { CAPI.ovr_RoomOptions_Destroy(Handle); } IntPtr Handle; } }
0
0.628199
1
0.628199
game-dev
MEDIA
0.658033
game-dev
0.632978
1
0.632978
FreeFalcon/freefalcon-central
10,149
src/campaign/include/campwp.h
/************************************************************************** * * CampWP.h * * Campaign waypoint manipulation routines * **************************************************************************/ #ifndef CAMPWP_H #define CAMPWP_H #include "Cmpglobl.h" extern bool g_bPrecisionWaypoints; //Wombat778 11-5-2003 class CampBaseClass; typedef CampBaseClass* CampEntity; // Waypoint actions #define WP_NOTHING 0 #define WP_TAKEOFF 1 #define WP_ASSEMBLE 2 #define WP_POSTASSEMBLE 3 #define WP_REFUEL 4 #define WP_REARM 5 #define WP_PICKUP 6 // Pick up a unit #define WP_LAND 7 #define WP_TIMING 8 // Just cruise around wasting time #define WP_CASCP 9 // CAS contact point #define WP_ESCORT 10 // Engage engaging fighters #define WP_CA 11 // Engage all enemy aircraft #define WP_CAP 12 // Patrol area for enemy aircraft #define WP_INTERCEPT 13 // Engage specific enemy aircraft #define WP_GNDSTRIKE 14 // Engage enemy units at target #define WP_NAVSTRIKE 15 // Engage enemy shits at target #define WP_SAD 16 // Engage any enemy at target #define WP_STRIKE 17 // Destroy enemy installation at target #define WP_BOMB 18 // Strategic bomb enemy installation at target #define WP_SEAD 19 // Suppress enemy air defense at target #define WP_ELINT 20 // Electronic intellicence (AWACS, JSTAR, ECM) #define WP_RECON 21 // Photograph target location #define WP_RESCUE 22 // Rescue a pilot at location #define WP_ASW 23 #define WP_TANKER 24 // Respond to tanker requests #define WP_AIRDROP 25 #define WP_JAM 26 // M.N. fix for Airlift missions //#define WP_LAND2 27 // this is our 2nd landing waypoint for Airlift missions // supply will be given at WP_LAND MNLOOK -> Change in string.txt 377 #define WP_B5 #define WP_B6 #define WP_B7 #define WP_FAC 30 #define WP_MOVEOPPOSED 40 // These are movement wps #define WP_MOVEUNOPPOSED 41 #define WP_AIRBORNE 42 #define WP_AMPHIBIOUS 43 #define WP_DEFEND 44 // These are action wps #define WP_REPAIR 45 #define WP_RESERVE 46 #define WP_AIRDEFENSE 47 #define WP_FIRESUPPORT 48 #define WP_SECURE 49 #define WP_LAST 50 // WP flags #define WPF_TARGET 0x0001 // This is a target wp #define WPF_ASSEMBLE 0x0002 // Wait for other elements here #define WPF_BREAKPOINT 0x0004 // Break point #define WPF_IP 0x0008 // IP waypoint #define WPF_TURNPOINT 0x0010 // Turn point #define WPF_CP 0x0020 // Contact point #define WPF_REPEAT 0x0040 // Return to previous WP until time is exceeded #define WPF_TAKEOFF 0x0080 #define WPF_LAND 0x0100 // Suck aircraft back into squadron #define WPF_DIVERT 0x0200 // This is a divert WP (deleted upon completion of divert) #define WPF_ALTERNATE 0x0400 // Alternate landing site // Climb profile flags #define WPF_HOLDCURRENT 0x0800 // Stay at current altitude until last minute // Other stuff #define WPF_REPEAT_CONTINUOUS 0x1000 // Do this until the end of time #define WPF_IN_PACKAGE 0x2000 // This is a package-coordinated wp // Even better "Other Stuff" #define WPF_TIME_LOCKED 0x4000 // This waypoint will have an arrive time as given, and will not be changed #define WPF_SPEED_LOCKED 0x8000 // This waypoint will have a speed as given, and will not be changed. #define WPF_REFUEL_INFORMATION 0x10000 // This waypoint is only an informational waypoint, no mission waypoint #define WPF_REQHELP 0x20000 // This divert waypoint is one from a request help call #define WPF_CRITICAL_MASK 0x07FF // If it's one of these, we can't skip this waypoint // time recalculation flags #define WPTS_KEEP_DEPARTURE_TIMES 0x01 // Don't shift departure times when updating waypoint times #define WPTS_SET_ALTERNATE_TIMES 0x02 // Set wp times for alternate waypoints #define GRIDZ_SCALE_FACTOR 10 // How many feet per pt of Z. #define MINIMUM_ASL_ALTITUDE 5000 // Below this # of feet, the WP is considered AGL // ============================================ // WayPoint Class // ============================================ class WayPointClass; typedef WayPointClass* WayPoint; class WayPointClass { #ifdef USE_SH_POOLS public: // Overload new/delete to use a SmartHeap fixed size pool void *operator new(size_t size) { ShiAssert(size == sizeof(WayPointClass)); return MemAllocFS(pool); }; void operator delete(void *mem) { if (mem) MemFreeFS(mem); }; static void InitializeStorage() { pool = MemPoolInitFS(sizeof(WayPointClass), 200, 0); }; static void ReleaseStorage() { MemPoolFree(pool); }; static MEM_POOL pool; #endif private: GridIndex GridX; // Waypoint's X,Y and Z coordinates (in km from southwest corner) GridIndex GridY; short GridZ; // Z is in 10s of feet CampaignTime Arrive; CampaignTime Depart; // This is only used for loiter waypoints VU_ID TargetID; uchar Action; uchar RouteAction; uchar Formation; uchar TargetBuilding; ulong Flags; // Various wp flags short Tactic; // Tactic to use here protected: float Speed; WayPoint PrevWP; // Make this one public for kicks.. WayPoint NextWP; // Make this one public for kicks.. private: // These functions are intended for use by the Sim (They use sim coordinates and times) //Wombat778 11-05-2003 new variable to hold a Sim location rather than a grid location BIG_SCALAR SimX; BIG_SCALAR SimY; BIG_SCALAR SimZ; public: WayPointClass(); WayPointClass( GridIndex x, GridIndex y, int alt, int speed, CampaignTime arr, CampaignTime station, uchar action, int flags ); WayPointClass(VU_BYTE **stream, long *rem); WayPointClass(FILE* fp); int SaveSize(void); int Save(VU_BYTE **stream); int Save(FILE* fp); // These functions are intended for general use void SetWPTarget(VU_ID e) { TargetID = e; } void SetWPTargetBuilding(uchar t) { TargetBuilding = t; } void SetWPAction(int a) { Action = (uchar) a; } void SetWPRouteAction(int a) { RouteAction = (uchar) a; } void SetWPFormation(int f) { Formation = (uchar) f; } void SetWPFlags(ulong f) { Flags = (ulong) f; } void SetWPFlag(ulong f) { Flags or_eq (ulong) f; } void UnSetWPFlag(ulong f) { Flags and_eq compl ((ulong)(f)); } void SetWPTactic(int f) { Tactic = (short) f; } VU_ID GetWPTargetID(void) { return TargetID; } CampEntity GetWPTarget(void) { return (CampEntity)vuDatabase->Find(TargetID); } uchar GetWPTargetBuilding(void) { return TargetBuilding; } int GetWPAction(void) { return (int)Action; } int GetWPRouteAction(void) { return (int)RouteAction; } int GetWPFormation(void) { return (int)Formation; } ulong GetWPFlags(void) { return (ulong)Flags; } int GetWPTactic(void) { return (int)Tactic; } WayPoint GetNextWP(void) { return NextWP; } WayPoint GetPrevWP(void) { return PrevWP; } void SetNextWP(WayPointClass *next); void SetPrevWP(WayPointClass *prev); void UnlinkNextWP(void); void SplitWP(void); void InsertWP(WayPointClass *); void DeleteWP(void); void CloneWP(WayPoint w); void SetWPTimes(CampaignTime t); float DistanceTo(WayPoint w); // These functions are intended for use by the campaign (They use Campaign Coordinates and times) void SetWPAltitude(int alt);// { GridZ = (short)(alt/GRIDZ_SCALE_FACTOR); } void SetWPAltitudeLevel(int alt);// { GridZ = (short)alt; } void SetWPStationTime(CampaignTime t) { Depart = Arrive + t; } void SetWPDepartTime(CampaignTime t) { Depart = t; } void SetWPArrive(CampaignTime t) { Arrive = t; } void SetWPSpeed(float s) { Speed = s; } float GetWPSpeed(void) { return Speed; } void SetWPLocation(GridIndex x, GridIndex y);// { GridX = x; GridY = y; } int GetWPAltitude() { return (int)(GridZ * GRIDZ_SCALE_FACTOR); } int GetWPAltitudeLevel() { return GridZ; } CampaignTime GetWPStationTime() { return (int)(Depart - Arrive); } CampaignTime GetWPArrivalTime() { return Arrive; } CampaignTime GetWPDepartureTime() { return Depart; } void AddWPTimeDelta(CampaignTime dt) { Arrive += dt; Depart += dt; } void GetWPLocation(GridIndex* x, GridIndex* y) const { *x = GridX; *y = GridY; } // Wombat778 11-5-2003 Changed to a new calculation. // Takes the sim position and stores it in a var, and also updates the GridX/Y/Z. // This is to allow waypoints to be placed more narrowly than the 1KM grid. // Hopefully, the sim wont care about the new more precise // waypoint locations. void SetLocation(float x, float y, float z); void GetLocation(float* x, float* y, float* z) const; }; // =================================================== // Global functions // =================================================== extern void DeleteWPList(WayPoint w); // Sets a set of waypoint times to start at waypoint w at time start. Returns duration of mission extern CampaignTime SetWPTimes(WayPoint w, CampaignTime start, int speed, int flags); // Shifts a set of waypoints by time delta. Returns duration of mission extern CampaignTime SetWPTimes(WayPoint w, long delta, int flags); // Sets a set of waypoint times to start at waypoint w as soon as we can get there from x,y. extern CampaignTime SetWPTimes(WayPoint w, GridIndex x, GridIndex y, int speed, int flags); extern WayPoint CloneWPList(WayPoint w); extern WayPoint CloneWPToList(WayPoint w, WayPoint stop); extern WayPoint CloneWPList(WayPointClass wps[], int waypoints); // KCK: This function requires that the graphic's altitude map is loaded extern float AdjustAltitudeForMSL_AGL(float x, float y, float z); extern float SetWPSpeed(WayPoint wp); #endif
0
0.958639
1
0.958639
game-dev
MEDIA
0.899142
game-dev
0.651707
1
0.651707
SethRobinson/proton
21,122
shared/Bullet/LinearMath/btMatrix3x3.h
/* Copyright (c) 2003-2006 Gino van den Bergen / Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_MATRIX3x3_H #define BT_MATRIX3x3_H #include "btVector3.h" #include "btQuaternion.h" #ifdef BT_USE_DOUBLE_PRECISION #define btMatrix3x3Data btMatrix3x3DoubleData #else #define btMatrix3x3Data btMatrix3x3FloatData #endif //BT_USE_DOUBLE_PRECISION /**@brief The btMatrix3x3 class implements a 3x3 rotation matrix, to perform linear algebra in combination with btQuaternion, btTransform and btVector3. * Make sure to only include a pure orthogonal matrix without scaling. */ class btMatrix3x3 { ///Data storage for the matrix, each vector is a row of the matrix btVector3 m_el[3]; public: /** @brief No initializaion constructor */ btMatrix3x3 () {} // explicit btMatrix3x3(const btScalar *m) { setFromOpenGLSubMatrix(m); } /**@brief Constructor from Quaternion */ explicit btMatrix3x3(const btQuaternion& q) { setRotation(q); } /* template <typename btScalar> Matrix3x3(const btScalar& yaw, const btScalar& pitch, const btScalar& roll) { setEulerYPR(yaw, pitch, roll); } */ /** @brief Constructor with row major formatting */ btMatrix3x3(const btScalar& xx, const btScalar& xy, const btScalar& xz, const btScalar& yx, const btScalar& yy, const btScalar& yz, const btScalar& zx, const btScalar& zy, const btScalar& zz) { setValue(xx, xy, xz, yx, yy, yz, zx, zy, zz); } /** @brief Copy constructor */ SIMD_FORCE_INLINE btMatrix3x3 (const btMatrix3x3& other) { m_el[0] = other.m_el[0]; m_el[1] = other.m_el[1]; m_el[2] = other.m_el[2]; } /** @brief Assignment Operator */ SIMD_FORCE_INLINE btMatrix3x3& operator=(const btMatrix3x3& other) { m_el[0] = other.m_el[0]; m_el[1] = other.m_el[1]; m_el[2] = other.m_el[2]; return *this; } /** @brief Get a column of the matrix as a vector * @param i Column number 0 indexed */ SIMD_FORCE_INLINE btVector3 getColumn(int i) const { return btVector3(m_el[0][i],m_el[1][i],m_el[2][i]); } /** @brief Get a row of the matrix as a vector * @param i Row number 0 indexed */ SIMD_FORCE_INLINE const btVector3& getRow(int i) const { btFullAssert(0 <= i && i < 3); return m_el[i]; } /** @brief Get a mutable reference to a row of the matrix as a vector * @param i Row number 0 indexed */ SIMD_FORCE_INLINE btVector3& operator[](int i) { btFullAssert(0 <= i && i < 3); return m_el[i]; } /** @brief Get a const reference to a row of the matrix as a vector * @param i Row number 0 indexed */ SIMD_FORCE_INLINE const btVector3& operator[](int i) const { btFullAssert(0 <= i && i < 3); return m_el[i]; } /** @brief Multiply by the target matrix on the right * @param m Rotation matrix to be applied * Equivilant to this = this * m */ btMatrix3x3& operator*=(const btMatrix3x3& m); /** @brief Set from a carray of btScalars * @param m A pointer to the beginning of an array of 9 btScalars */ void setFromOpenGLSubMatrix(const btScalar *m) { m_el[0].setValue(m[0],m[4],m[8]); m_el[1].setValue(m[1],m[5],m[9]); m_el[2].setValue(m[2],m[6],m[10]); } /** @brief Set the values of the matrix explicitly (row major) * @param xx Top left * @param xy Top Middle * @param xz Top Right * @param yx Middle Left * @param yy Middle Middle * @param yz Middle Right * @param zx Bottom Left * @param zy Bottom Middle * @param zz Bottom Right*/ void setValue(const btScalar& xx, const btScalar& xy, const btScalar& xz, const btScalar& yx, const btScalar& yy, const btScalar& yz, const btScalar& zx, const btScalar& zy, const btScalar& zz) { m_el[0].setValue(xx,xy,xz); m_el[1].setValue(yx,yy,yz); m_el[2].setValue(zx,zy,zz); } /** @brief Set the matrix from a quaternion * @param q The Quaternion to match */ void setRotation(const btQuaternion& q) { btScalar d = q.length2(); btFullAssert(d != btScalar(0.0)); btScalar s = btScalar(2.0) / d; btScalar xs = q.x() * s, ys = q.y() * s, zs = q.z() * s; btScalar wx = q.w() * xs, wy = q.w() * ys, wz = q.w() * zs; btScalar xx = q.x() * xs, xy = q.x() * ys, xz = q.x() * zs; btScalar yy = q.y() * ys, yz = q.y() * zs, zz = q.z() * zs; setValue(btScalar(1.0) - (yy + zz), xy - wz, xz + wy, xy + wz, btScalar(1.0) - (xx + zz), yz - wx, xz - wy, yz + wx, btScalar(1.0) - (xx + yy)); } /** @brief Set the matrix from euler angles using YPR around YXZ respectively * @param yaw Yaw about Y axis * @param pitch Pitch about X axis * @param roll Roll about Z axis */ void setEulerYPR(const btScalar& yaw, const btScalar& pitch, const btScalar& roll) { setEulerZYX(roll, pitch, yaw); } /** @brief Set the matrix from euler angles YPR around ZYX axes * @param eulerX Roll about X axis * @param eulerY Pitch around Y axis * @param eulerZ Yaw aboud Z axis * * These angles are used to produce a rotation matrix. The euler * angles are applied in ZYX order. I.e a vector is first rotated * about X then Y and then Z **/ void setEulerZYX(btScalar eulerX,btScalar eulerY,btScalar eulerZ) { ///@todo proposed to reverse this since it's labeled zyx but takes arguments xyz and it will match all other parts of the code btScalar ci ( btCos(eulerX)); btScalar cj ( btCos(eulerY)); btScalar ch ( btCos(eulerZ)); btScalar si ( btSin(eulerX)); btScalar sj ( btSin(eulerY)); btScalar sh ( btSin(eulerZ)); btScalar cc = ci * ch; btScalar cs = ci * sh; btScalar sc = si * ch; btScalar ss = si * sh; setValue(cj * ch, sj * sc - cs, sj * cc + ss, cj * sh, sj * ss + cc, sj * cs - sc, -sj, cj * si, cj * ci); } /**@brief Set the matrix to the identity */ void setIdentity() { setValue(btScalar(1.0), btScalar(0.0), btScalar(0.0), btScalar(0.0), btScalar(1.0), btScalar(0.0), btScalar(0.0), btScalar(0.0), btScalar(1.0)); } static const btMatrix3x3& getIdentity() { static const btMatrix3x3 identityMatrix(btScalar(1.0), btScalar(0.0), btScalar(0.0), btScalar(0.0), btScalar(1.0), btScalar(0.0), btScalar(0.0), btScalar(0.0), btScalar(1.0)); return identityMatrix; } /**@brief Fill the values of the matrix into a 9 element array * @param m The array to be filled */ void getOpenGLSubMatrix(btScalar *m) const { m[0] = btScalar(m_el[0].x()); m[1] = btScalar(m_el[1].x()); m[2] = btScalar(m_el[2].x()); m[3] = btScalar(0.0); m[4] = btScalar(m_el[0].y()); m[5] = btScalar(m_el[1].y()); m[6] = btScalar(m_el[2].y()); m[7] = btScalar(0.0); m[8] = btScalar(m_el[0].z()); m[9] = btScalar(m_el[1].z()); m[10] = btScalar(m_el[2].z()); m[11] = btScalar(0.0); } /**@brief Get the matrix represented as a quaternion * @param q The quaternion which will be set */ void getRotation(btQuaternion& q) const { btScalar trace = m_el[0].x() + m_el[1].y() + m_el[2].z(); btScalar temp[4]; if (trace > btScalar(0.0)) { btScalar s = btSqrt(trace + btScalar(1.0)); temp[3]=(s * btScalar(0.5)); s = btScalar(0.5) / s; temp[0]=((m_el[2].y() - m_el[1].z()) * s); temp[1]=((m_el[0].z() - m_el[2].x()) * s); temp[2]=((m_el[1].x() - m_el[0].y()) * s); } else { int i = m_el[0].x() < m_el[1].y() ? (m_el[1].y() < m_el[2].z() ? 2 : 1) : (m_el[0].x() < m_el[2].z() ? 2 : 0); int j = (i + 1) % 3; int k = (i + 2) % 3; btScalar s = btSqrt(m_el[i][i] - m_el[j][j] - m_el[k][k] + btScalar(1.0)); temp[i] = s * btScalar(0.5); s = btScalar(0.5) / s; temp[3] = (m_el[k][j] - m_el[j][k]) * s; temp[j] = (m_el[j][i] + m_el[i][j]) * s; temp[k] = (m_el[k][i] + m_el[i][k]) * s; } q.setValue(temp[0],temp[1],temp[2],temp[3]); } /**@brief Get the matrix represented as euler angles around YXZ, roundtrip with setEulerYPR * @param yaw Yaw around Y axis * @param pitch Pitch around X axis * @param roll around Z axis */ void getEulerYPR(btScalar& yaw, btScalar& pitch, btScalar& roll) const { // first use the normal calculus yaw = btScalar(btAtan2(m_el[1].x(), m_el[0].x())); pitch = btScalar(btAsin(-m_el[2].x())); roll = btScalar(btAtan2(m_el[2].y(), m_el[2].z())); // on pitch = +/-HalfPI if (btFabs(pitch)==SIMD_HALF_PI) { if (yaw>0) yaw-=SIMD_PI; else yaw+=SIMD_PI; if (roll>0) roll-=SIMD_PI; else roll+=SIMD_PI; } }; /**@brief Get the matrix represented as euler angles around ZYX * @param yaw Yaw around X axis * @param pitch Pitch around Y axis * @param roll around X axis * @param solution_number Which solution of two possible solutions ( 1 or 2) are possible values*/ void getEulerZYX(btScalar& yaw, btScalar& pitch, btScalar& roll, unsigned int solution_number = 1) const { struct Euler { btScalar yaw; btScalar pitch; btScalar roll; }; Euler euler_out; Euler euler_out2; //second solution //get the pointer to the raw data // Check that pitch is not at a singularity if (btFabs(m_el[2].x()) >= 1) { euler_out.yaw = 0; euler_out2.yaw = 0; // From difference of angles formula btScalar delta = btAtan2(m_el[0].x(),m_el[0].z()); if (m_el[2].x() > 0) //gimbal locked up { euler_out.pitch = SIMD_PI / btScalar(2.0); euler_out2.pitch = SIMD_PI / btScalar(2.0); euler_out.roll = euler_out.pitch + delta; euler_out2.roll = euler_out.pitch + delta; } else // gimbal locked down { euler_out.pitch = -SIMD_PI / btScalar(2.0); euler_out2.pitch = -SIMD_PI / btScalar(2.0); euler_out.roll = -euler_out.pitch + delta; euler_out2.roll = -euler_out.pitch + delta; } } else { euler_out.pitch = - btAsin(m_el[2].x()); euler_out2.pitch = SIMD_PI - euler_out.pitch; euler_out.roll = btAtan2(m_el[2].y()/btCos(euler_out.pitch), m_el[2].z()/btCos(euler_out.pitch)); euler_out2.roll = btAtan2(m_el[2].y()/btCos(euler_out2.pitch), m_el[2].z()/btCos(euler_out2.pitch)); euler_out.yaw = btAtan2(m_el[1].x()/btCos(euler_out.pitch), m_el[0].x()/btCos(euler_out.pitch)); euler_out2.yaw = btAtan2(m_el[1].x()/btCos(euler_out2.pitch), m_el[0].x()/btCos(euler_out2.pitch)); } if (solution_number == 1) { yaw = euler_out.yaw; pitch = euler_out.pitch; roll = euler_out.roll; } else { yaw = euler_out2.yaw; pitch = euler_out2.pitch; roll = euler_out2.roll; } } /**@brief Create a scaled copy of the matrix * @param s Scaling vector The elements of the vector will scale each column */ btMatrix3x3 scaled(const btVector3& s) const { return btMatrix3x3(m_el[0].x() * s.x(), m_el[0].y() * s.y(), m_el[0].z() * s.z(), m_el[1].x() * s.x(), m_el[1].y() * s.y(), m_el[1].z() * s.z(), m_el[2].x() * s.x(), m_el[2].y() * s.y(), m_el[2].z() * s.z()); } /**@brief Return the determinant of the matrix */ btScalar determinant() const; /**@brief Return the adjoint of the matrix */ btMatrix3x3 adjoint() const; /**@brief Return the matrix with all values non negative */ btMatrix3x3 absolute() const; /**@brief Return the transpose of the matrix */ btMatrix3x3 transpose() const; /**@brief Return the inverse of the matrix */ btMatrix3x3 inverse() const; btMatrix3x3 transposeTimes(const btMatrix3x3& m) const; btMatrix3x3 timesTranspose(const btMatrix3x3& m) const; SIMD_FORCE_INLINE btScalar tdotx(const btVector3& v) const { return m_el[0].x() * v.x() + m_el[1].x() * v.y() + m_el[2].x() * v.z(); } SIMD_FORCE_INLINE btScalar tdoty(const btVector3& v) const { return m_el[0].y() * v.x() + m_el[1].y() * v.y() + m_el[2].y() * v.z(); } SIMD_FORCE_INLINE btScalar tdotz(const btVector3& v) const { return m_el[0].z() * v.x() + m_el[1].z() * v.y() + m_el[2].z() * v.z(); } /**@brief diagonalizes this matrix by the Jacobi method. * @param rot stores the rotation from the coordinate system in which the matrix is diagonal to the original * coordinate system, i.e., old_this = rot * new_this * rot^T. * @param threshold See iteration * @param iteration The iteration stops when all off-diagonal elements are less than the threshold multiplied * by the sum of the absolute values of the diagonal, or when maxSteps have been executed. * * Note that this matrix is assumed to be symmetric. */ void diagonalize(btMatrix3x3& rot, btScalar threshold, int maxSteps) { rot.setIdentity(); for (int step = maxSteps; step > 0; step--) { // find off-diagonal element [p][q] with largest magnitude int p = 0; int q = 1; int r = 2; btScalar max = btFabs(m_el[0][1]); btScalar v = btFabs(m_el[0][2]); if (v > max) { q = 2; r = 1; max = v; } v = btFabs(m_el[1][2]); if (v > max) { p = 1; q = 2; r = 0; max = v; } btScalar t = threshold * (btFabs(m_el[0][0]) + btFabs(m_el[1][1]) + btFabs(m_el[2][2])); if (max <= t) { if (max <= SIMD_EPSILON * t) { return; } step = 1; } // compute Jacobi rotation J which leads to a zero for element [p][q] btScalar mpq = m_el[p][q]; btScalar theta = (m_el[q][q] - m_el[p][p]) / (2 * mpq); btScalar theta2 = theta * theta; btScalar cos; btScalar sin; if (theta2 * theta2 < btScalar(10 / SIMD_EPSILON)) { t = (theta >= 0) ? 1 / (theta + btSqrt(1 + theta2)) : 1 / (theta - btSqrt(1 + theta2)); cos = 1 / btSqrt(1 + t * t); sin = cos * t; } else { // approximation for large theta-value, i.e., a nearly diagonal matrix t = 1 / (theta * (2 + btScalar(0.5) / theta2)); cos = 1 - btScalar(0.5) * t * t; sin = cos * t; } // apply rotation to matrix (this = J^T * this * J) m_el[p][q] = m_el[q][p] = 0; m_el[p][p] -= t * mpq; m_el[q][q] += t * mpq; btScalar mrp = m_el[r][p]; btScalar mrq = m_el[r][q]; m_el[r][p] = m_el[p][r] = cos * mrp - sin * mrq; m_el[r][q] = m_el[q][r] = cos * mrq + sin * mrp; // apply rotation to rot (rot = rot * J) for (int i = 0; i < 3; i++) { btVector3& row = rot[i]; mrp = row[p]; mrq = row[q]; row[p] = cos * mrp - sin * mrq; row[q] = cos * mrq + sin * mrp; } } } /**@brief Calculate the matrix cofactor * @param r1 The first row to use for calculating the cofactor * @param c1 The first column to use for calculating the cofactor * @param r1 The second row to use for calculating the cofactor * @param c1 The second column to use for calculating the cofactor * See http://en.wikipedia.org/wiki/Cofactor_(linear_algebra) for more details */ btScalar cofac(int r1, int c1, int r2, int c2) const { return m_el[r1][c1] * m_el[r2][c2] - m_el[r1][c2] * m_el[r2][c1]; } void serialize(struct btMatrix3x3Data& dataOut) const; void serializeFloat(struct btMatrix3x3FloatData& dataOut) const; void deSerialize(const struct btMatrix3x3Data& dataIn); void deSerializeFloat(const struct btMatrix3x3FloatData& dataIn); void deSerializeDouble(const struct btMatrix3x3DoubleData& dataIn); }; SIMD_FORCE_INLINE btMatrix3x3& btMatrix3x3::operator*=(const btMatrix3x3& m) { setValue(m.tdotx(m_el[0]), m.tdoty(m_el[0]), m.tdotz(m_el[0]), m.tdotx(m_el[1]), m.tdoty(m_el[1]), m.tdotz(m_el[1]), m.tdotx(m_el[2]), m.tdoty(m_el[2]), m.tdotz(m_el[2])); return *this; } SIMD_FORCE_INLINE btScalar btMatrix3x3::determinant() const { return btTriple((*this)[0], (*this)[1], (*this)[2]); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::absolute() const { return btMatrix3x3( btFabs(m_el[0].x()), btFabs(m_el[0].y()), btFabs(m_el[0].z()), btFabs(m_el[1].x()), btFabs(m_el[1].y()), btFabs(m_el[1].z()), btFabs(m_el[2].x()), btFabs(m_el[2].y()), btFabs(m_el[2].z())); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::transpose() const { return btMatrix3x3(m_el[0].x(), m_el[1].x(), m_el[2].x(), m_el[0].y(), m_el[1].y(), m_el[2].y(), m_el[0].z(), m_el[1].z(), m_el[2].z()); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::adjoint() const { return btMatrix3x3(cofac(1, 1, 2, 2), cofac(0, 2, 2, 1), cofac(0, 1, 1, 2), cofac(1, 2, 2, 0), cofac(0, 0, 2, 2), cofac(0, 2, 1, 0), cofac(1, 0, 2, 1), cofac(0, 1, 2, 0), cofac(0, 0, 1, 1)); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::inverse() const { btVector3 co(cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1)); btScalar det = (*this)[0].dot(co); btFullAssert(det != btScalar(0.0)); btScalar s = btScalar(1.0) / det; return btMatrix3x3(co.x() * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s, co.y() * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s, co.z() * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::transposeTimes(const btMatrix3x3& m) const { return btMatrix3x3( m_el[0].x() * m[0].x() + m_el[1].x() * m[1].x() + m_el[2].x() * m[2].x(), m_el[0].x() * m[0].y() + m_el[1].x() * m[1].y() + m_el[2].x() * m[2].y(), m_el[0].x() * m[0].z() + m_el[1].x() * m[1].z() + m_el[2].x() * m[2].z(), m_el[0].y() * m[0].x() + m_el[1].y() * m[1].x() + m_el[2].y() * m[2].x(), m_el[0].y() * m[0].y() + m_el[1].y() * m[1].y() + m_el[2].y() * m[2].y(), m_el[0].y() * m[0].z() + m_el[1].y() * m[1].z() + m_el[2].y() * m[2].z(), m_el[0].z() * m[0].x() + m_el[1].z() * m[1].x() + m_el[2].z() * m[2].x(), m_el[0].z() * m[0].y() + m_el[1].z() * m[1].y() + m_el[2].z() * m[2].y(), m_el[0].z() * m[0].z() + m_el[1].z() * m[1].z() + m_el[2].z() * m[2].z()); } SIMD_FORCE_INLINE btMatrix3x3 btMatrix3x3::timesTranspose(const btMatrix3x3& m) const { return btMatrix3x3( m_el[0].dot(m[0]), m_el[0].dot(m[1]), m_el[0].dot(m[2]), m_el[1].dot(m[0]), m_el[1].dot(m[1]), m_el[1].dot(m[2]), m_el[2].dot(m[0]), m_el[2].dot(m[1]), m_el[2].dot(m[2])); } SIMD_FORCE_INLINE btVector3 operator*(const btMatrix3x3& m, const btVector3& v) { return btVector3(m[0].dot(v), m[1].dot(v), m[2].dot(v)); } SIMD_FORCE_INLINE btVector3 operator*(const btVector3& v, const btMatrix3x3& m) { return btVector3(m.tdotx(v), m.tdoty(v), m.tdotz(v)); } SIMD_FORCE_INLINE btMatrix3x3 operator*(const btMatrix3x3& m1, const btMatrix3x3& m2) { return btMatrix3x3( m2.tdotx( m1[0]), m2.tdoty( m1[0]), m2.tdotz( m1[0]), m2.tdotx( m1[1]), m2.tdoty( m1[1]), m2.tdotz( m1[1]), m2.tdotx( m1[2]), m2.tdoty( m1[2]), m2.tdotz( m1[2])); } /* SIMD_FORCE_INLINE btMatrix3x3 btMultTransposeLeft(const btMatrix3x3& m1, const btMatrix3x3& m2) { return btMatrix3x3( m1[0][0] * m2[0][0] + m1[1][0] * m2[1][0] + m1[2][0] * m2[2][0], m1[0][0] * m2[0][1] + m1[1][0] * m2[1][1] + m1[2][0] * m2[2][1], m1[0][0] * m2[0][2] + m1[1][0] * m2[1][2] + m1[2][0] * m2[2][2], m1[0][1] * m2[0][0] + m1[1][1] * m2[1][0] + m1[2][1] * m2[2][0], m1[0][1] * m2[0][1] + m1[1][1] * m2[1][1] + m1[2][1] * m2[2][1], m1[0][1] * m2[0][2] + m1[1][1] * m2[1][2] + m1[2][1] * m2[2][2], m1[0][2] * m2[0][0] + m1[1][2] * m2[1][0] + m1[2][2] * m2[2][0], m1[0][2] * m2[0][1] + m1[1][2] * m2[1][1] + m1[2][2] * m2[2][1], m1[0][2] * m2[0][2] + m1[1][2] * m2[1][2] + m1[2][2] * m2[2][2]); } */ /**@brief Equality operator between two matrices * It will test all elements are equal. */ SIMD_FORCE_INLINE bool operator==(const btMatrix3x3& m1, const btMatrix3x3& m2) { return ( m1[0][0] == m2[0][0] && m1[1][0] == m2[1][0] && m1[2][0] == m2[2][0] && m1[0][1] == m2[0][1] && m1[1][1] == m2[1][1] && m1[2][1] == m2[2][1] && m1[0][2] == m2[0][2] && m1[1][2] == m2[1][2] && m1[2][2] == m2[2][2] ); } ///for serialization struct btMatrix3x3FloatData { btVector3FloatData m_el[3]; }; ///for serialization struct btMatrix3x3DoubleData { btVector3DoubleData m_el[3]; }; SIMD_FORCE_INLINE void btMatrix3x3::serialize(struct btMatrix3x3Data& dataOut) const { for (int i=0;i<3;i++) m_el[i].serialize(dataOut.m_el[i]); } SIMD_FORCE_INLINE void btMatrix3x3::serializeFloat(struct btMatrix3x3FloatData& dataOut) const { for (int i=0;i<3;i++) m_el[i].serializeFloat(dataOut.m_el[i]); } SIMD_FORCE_INLINE void btMatrix3x3::deSerialize(const struct btMatrix3x3Data& dataIn) { for (int i=0;i<3;i++) m_el[i].deSerialize(dataIn.m_el[i]); } SIMD_FORCE_INLINE void btMatrix3x3::deSerializeFloat(const struct btMatrix3x3FloatData& dataIn) { for (int i=0;i<3;i++) m_el[i].deSerializeFloat(dataIn.m_el[i]); } SIMD_FORCE_INLINE void btMatrix3x3::deSerializeDouble(const struct btMatrix3x3DoubleData& dataIn) { for (int i=0;i<3;i++) m_el[i].deSerializeDouble(dataIn.m_el[i]); } #endif //BT_MATRIX3x3_H
0
0.927945
1
0.927945
game-dev
MEDIA
0.817041
game-dev
0.979299
1
0.979299
Fluorohydride/ygopro-scripts
1,342
c87819421.lua
--マスク・チャージ function c87819421.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetTarget(c87819421.target) e1:SetOperation(c87819421.activate) c:RegisterEffect(e1) end function c87819421.filter1(c) return c:IsSetCard(0x8) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c87819421.filter2(c) return c:IsSetCard(0xa5) and c:IsType(TYPE_QUICKPLAY) and c:IsAbleToHand() end function c87819421.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return false end if chk==0 then return Duel.IsExistingTarget(c87819421.filter1,tp,LOCATION_GRAVE,0,1,nil) and Duel.IsExistingTarget(c87819421.filter2,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g1=Duel.SelectTarget(tp,c87819421.filter1,tp,LOCATION_GRAVE,0,1,1,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g2=Duel.SelectTarget(tp,c87819421.filter2,tp,LOCATION_GRAVE,0,1,1,nil) g1:Merge(g2) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g1,2,0,0) end function c87819421.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local sg=g:Filter(Card.IsRelateToEffect,nil,e) if sg:GetCount()>0 then Duel.SendtoHand(sg,nil,REASON_EFFECT) end end
0
0.887144
1
0.887144
game-dev
MEDIA
0.963443
game-dev
0.964095
1
0.964095
Fluorohydride/ygopro-scripts
3,002
c94395649.lua
--超重禽属コカトリウム function c94395649.initial_effect(c) --Special Summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(94395649,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_HAND+LOCATION_GRAVE) e1:SetCountLimit(1,94395649) e1:SetCost(c94395649.spcost) e1:SetTarget(c94395649.sptg) e1:SetOperation(c94395649.spop) c:RegisterEffect(e1) --copy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(94395649,1)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetCountLimit(1,94395650) e2:SetRange(LOCATION_MZONE) e2:SetCost(c94395649.cost) e2:SetOperation(c94395649.operation) c:RegisterEffect(e2) end function c94395649.cfilter(c,tp) return c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and Duel.GetMZoneCount(tp,c)>0 and (c:IsFaceup() or c:IsControler(tp)) end function c94395649.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,c94395649.cfilter,1,nil,tp) end local g=Duel.SelectReleaseGroup(tp,c94395649.cfilter,1,1,nil,tp) Duel.Release(g,REASON_COST) end function c94395649.sptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0) end function c94395649.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)>0 then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT+RESETS_REDIRECT) e1:SetValue(LOCATION_REMOVED) c:RegisterEffect(e1,true) end end function c94395649.filter(c) return c:IsLevelBelow(4) and c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsAbleToRemoveAsCost() end function c94395649.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c94395649.filter,tp,LOCATION_DECK,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c94395649.filter,tp,LOCATION_DECK,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) e:SetLabelObject(g:GetFirst()) end function c94395649.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=e:GetLabelObject() if c:IsRelateToEffect(e) and c:IsFaceup() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) e1:SetCode(EFFECT_CHANGE_CODE) e1:SetValue(tc:GetOriginalCode()) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_CHANGE_RACE) e2:SetValue(tc:GetOriginalRace()) c:RegisterEffect(e2) local e3=e1:Clone() e3:SetCode(EFFECT_CHANGE_ATTRIBUTE) e3:SetValue(tc:GetOriginalAttribute()) c:RegisterEffect(e3) local e4=e1:Clone() e4:SetCode(EFFECT_CHANGE_LEVEL) e4:SetValue(tc:GetOriginalLevel()) c:RegisterEffect(e4) end end
0
0.920339
1
0.920339
game-dev
MEDIA
0.986496
game-dev
0.871769
1
0.871769
SkidderMC/FDPClient
1,505
src/main/java/net/ccbluex/liquidbounce/injection/forge/MixinLoader.java
/* * FDPClient Hacked Client * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge. * https://github.com/SkidderMC/FDPClient/ */ package net.ccbluex.liquidbounce.injection.forge; import net.ccbluex.liquidbounce.injection.transformers.ForgeNetworkTransformer; import net.ccbluex.liquidbounce.script.remapper.injection.transformers.AbstractJavaLinkerTransformer; import net.minecraftforge.fml.relauncher.IFMLLoadingPlugin; import org.spongepowered.asm.launch.MixinBootstrap; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.Mixins; import java.util.Map; public class MixinLoader implements IFMLLoadingPlugin { public MixinLoader() { System.out.println("[FDPCLIENT] Injecting with IFMLLoadingPlugin."); MixinBootstrap.init(); Mixins.addConfiguration("fdpclient.forge.mixins.json"); MixinEnvironment.getDefaultEnvironment().setSide(MixinEnvironment.Side.CLIENT); } @Override public String[] getASMTransformerClass() { return new String[] {ForgeNetworkTransformer.class.getName(), AbstractJavaLinkerTransformer.class.getName()}; } @Override public String getModContainerClass() { return null; } @Override public String getSetupClass() { return null; } @Override public void injectData(Map<String, Object> data) { } @Override public String getAccessTransformerClass() { return null; } }
0
0.874344
1
0.874344
game-dev
MEDIA
0.952582
game-dev
0.687117
1
0.687117
DRE2N/DungeonsXL
5,276
core/src/main/java/de/erethon/dungeonsxl/player/DPermission.java
/* * Copyright (C) 2012-2023 Frank Baumann * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.erethon.dungeonsxl.player; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import static org.bukkit.permissions.PermissionDefault.*; /** * @author Daniel Saukel */ public enum DPermission { // Main nodes ANNOUNCE("announce", OP), BED("bed", OP), BREAK("break", OP), BYPASS("bypass", OP), CHAT("chat", TRUE), CHAT_SPY("chatspy", OP), CMD_EDIT("cmdedit", OP), CREATE("create", OP), DELETE("delete", OP), DUNGEON_ITEM("dungeonitem", OP), EDIT("edit", OP), ENDER_CHEST("enderchest", OP), DISPENSER("dispenser", OP), ENTER("enter", OP), ESCAPE("escape", TRUE), GAME("game", TRUE), GROUP("group", OP), GROUP_ADMIN("group.admin", OP, GROUP), HELP("help", TRUE), IGNORE_REQUIREMENTS("ignorerequirements", OP), IMPORT("IMPORT", OP), INVITE("invite", OP), INSECURE("insecure", OP), JOIN("join", TRUE), KICK("kick", OP), LEAVE("leave", TRUE), LIST("list", OP), LIVES("lives", TRUE), MAIN("main", TRUE), MESSAGE("msg", OP), PLAY("play", OP), PORTAL("portal", OP), RELOAD("reload", OP), RENAME("rename", OP), RESOURCE_PACK("resourcepack", OP), REWARDS("rewards", TRUE), SAVE("save", OP), STATUS("status", OP), /** * Allows to open the settings menu. */ SETTINGS("settings", TRUE), /** * Allows to modify dungeon settings unless they have an own node. */ SETTINGS_EDIT("settings.edit", OP), /** * Allows to modify global settings. */ SETTINGS_GLOBAL("settings.global", OP), /** * Allows to modify player settings unless they have an own node. */ SETTINGS_PLAYER("settings.player", TRUE), SIGN("sign", OP), TEST("test", OP), UNINVITE("uninvite", OP), // Kits ADMINISTRATOR("*", OP), HALF_EDITOR("halfeditor", OP, ESCAPE, LIST, MESSAGE, SAVE), FULL_EDITOR("fulleditor", OP, HALF_EDITOR, DELETE, EDIT, PLAY, RENAME, SIGN, TEST), HALF_PLAYER("halfplayer", TRUE, CHAT, ESCAPE, GAME, HELP, JOIN, LEAVE, LIVES, MAIN, SETTINGS, SETTINGS_PLAYER), FULL_PLAYER("fullplayer", OP, HALF_PLAYER, GROUP); public static final String PREFIX = "dxl."; private Permission node; private List<DPermission> children = new ArrayList<>(); DPermission(String node, PermissionDefault isDefault) { this.node = new Permission(PREFIX + node, isDefault); } DPermission(String node, PermissionDefault isDefault, DPermission... children) { this(node, isDefault); this.children = Arrays.asList(children); for (DPermission child : children) { child.node.addParent(node, true); } } /** * @return the permission node String */ public String getNode() { return node.getName(); } /** * @return if a player has the node by default */ public PermissionDefault isDefault() { return node.getDefault(); } /** * @return if the node has children */ public boolean hasChildren() { return !children.isEmpty(); } /** * @return the child permissions */ public List<DPermission> getChildren() { return children; } /** * @param node the node String, with or without "dxl." * @return the DPermission value */ public static DPermission getByNode(String node) { for (DPermission permission : values()) { if (permission.getNode().equals(node) || permission.node.equals(node)) { return permission; } } return null; } /** * @param sender the CommandSender * @param permission the permission to check * @return if the player has the permission */ public static boolean hasPermission(CommandSender sender, DPermission permission) { return sender.hasPermission(permission.getNode()); } /** * Registers the permissions. */ public static void register() { for (DPermission permission : values()) { Bukkit.getPluginManager().addPermission(permission.node); } } /** * Unregisters the permissions. */ public static void unregister() { for (DPermission permission : values()) { Bukkit.getPluginManager().removePermission(permission.node); } } }
0
0.924181
1
0.924181
game-dev
MEDIA
0.933094
game-dev
0.8435
1
0.8435
chronosacaria/MCDungeonsWeapons
1,753
common/src/main/java/dev/timefall/mcdw/enchantment/enchantments/PhantomsMarkEnchantment.java
/* * Timefall Development License 1.2 * Copyright (c) 2020-2024. Chronosacaria, Kluzzio, Timefall Development. All Rights Reserved. * * This software's content is licensed under the Timefall Development License 1.2. You can find this license information here: https://github.com/Timefall-Development/Timefall-Development-Licence/blob/main/TimefallDevelopmentLicense1.2.txt */ package dev.timefall.mcdw.enchantment.enchantments; import net.minecraft.enchantment.Enchantment; import net.minecraft.item.BowItem; import net.minecraft.item.CrossbowItem; import net.minecraft.item.ItemStack; /* * Effects Needed: */ /* * Effects Present: * POST_HIT * ApplyMobEffectEnchantmentEffectType -> for glowing application itself */ public class PhantomsMarkEnchantment extends Enchantment { public PhantomsMarkEnchantment(Properties properties) { super(properties); } //public PhantomsMarkEnchantment(Rarity rarity, EnchantmentTarget enchantmentTarget, EquipmentSlot[] equipmentSlots) { // super(rarity, enchantmentTarget, equipmentSlots); // if (McdwCommon.CONFIG.mcdwEnchantmentsConfig.ENCHANTMENT_CONFIG.get(EnchantmentsID.PHANTOMS_MARK).mcdw$getIsEnabled()) { // ItemGroupEvents.modifyEntriesEvent(ItemGroupRegistry.ENCHANTMENTS).register(entries -> { // // For loop creates first 3 levels of enchanted books // for (int i = 1; i <= getMaxLevel(); i++) // entries.add(EnchantedBookItem.forEnchantment(new EnchantmentLevelEntry(this, i))); // }); // } //} @Override public boolean isAcceptableItem(ItemStack stack) { return stack.getItem() instanceof CrossbowItem || stack.getItem() instanceof BowItem; } }
0
0.801385
1
0.801385
game-dev
MEDIA
0.947533
game-dev
0.644483
1
0.644483
bergerhealer/TrainCarts
9,063
src/main/java/com/bergerkiller/bukkit/tc/attachments/control/light/LightAPIControllerForkImpl.java
package com.bergerkiller.bukkit.tc.attachments.control.light; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.bukkit.World; import com.bergerkiller.bukkit.common.bases.IntVector3; import ru.beykerykt.lightapi.LightAPI; import ru.beykerykt.lightapi.LightType; import ru.beykerykt.lightapi.chunks.ChunkInfo; /** * Implementation of the LightAPIController. Contains LightAPI * types. This is for LightAPI-Fork. */ class LightAPIControllerForkImpl extends LightAPIController { private final World world; private final LightType lightType; private final Map<IntVector3, LevelList> levels; private final Map<IntVector3, LevelList> dirty; public static LightAPIController forSkyLight(World world) { return new LightAPIControllerForkImpl(world, LightType.SKY); } public static LightAPIController forBlockLight(World world) { return new LightAPIControllerForkImpl(world, LightType.BLOCK); } private LightAPIControllerForkImpl(World world, LightType lightType) { this.world = world; this.lightType = lightType; this.levels = new HashMap<>(); this.dirty = new HashMap<>(); } public void add(IntVector3 position, int level) { if (level >= 1 && level <= 15) { LevelList list = levels.computeIfAbsent(position, p -> new LevelList()); if (list.add(level)) { dirty.put(position, list); schedule(); } } } public void remove(IntVector3 position, int level) { LevelList list = levels.get(position); if (list != null && list.remove(level)) { dirty.put(position, list); schedule(); } } public void move(IntVector3 old_position, IntVector3 new_position, int level) { remove(old_position, level); add(new_position, level); } @Override public void update(IntVector3 position, int old_level, int new_level) { LevelList list = levels.get(position); if (list != null && (list.remove(old_level) | list.add(new_level))) { dirty.put(position, list); schedule(); } } public boolean onSync() { if (dirty.isEmpty()) { return false; } final boolean async = true; Set<ChunkInfo> chunks = new HashSet<>(); // First process all dirty entries that need light removed for (Map.Entry<IntVector3, LevelList> dirty_entry : dirty.entrySet()) { if (dirty_entry.getValue().needsRemoving()) { IntVector3 pos = dirty_entry.getKey(); LightAPI.deleteLight(world, pos.x, pos.y, pos.z, lightType, async); chunks.addAll(LightAPI.collectChunks(world, pos.x, pos.y, pos.z, lightType, 15)); } } // Then process the dirty entries that create new light for (Map.Entry<IntVector3, LevelList> dirty_entry : dirty.entrySet()) { LevelList list = dirty_entry.getValue(); if (list.isEmpty()) { // Cleanup from states map levels.remove(dirty_entry.getKey()); } else { // Sync it up IntVector3 pos = dirty_entry.getKey(); int level = list.sync(); LightAPI.createLight(world, pos.x, pos.y, pos.z, lightType, level, async); chunks.addAll(LightAPI.collectChunks(world, pos.x, pos.y, pos.z, lightType, level)); } } // Refresh chunks and done dirty.clear(); for (ChunkInfo chunk : chunks) { LightAPI.updateChunk(chunk, lightType); } return true; } /** * List of light levels configured for a given block */ private static final class LevelList { private static final int[] NO_LEVELS = new int[0]; private static final int[][] SINGLE_LEVEL = new int[16][1]; static { for (int level = 0; level <= 15; level++) { SINGLE_LEVEL[level][0] = level; } } // Light level that was last synchronized private int sync = 0; // Sorted list of light levels, highest value first private int[] levels = NO_LEVELS; /** * Gets whether the original light source needs to be removed * to properly update the light * * @return True if the previous light needs to be removed */ public boolean needsRemoving() { return (levels == NO_LEVELS) ? (sync > 0) : (sync > levels[0]); } /** * Gets whether the list of levels is empty. * An empty list results in no light sources being created. * * @return True if empty */ public boolean isEmpty() { return levels == NO_LEVELS; } /** * Synchronizes the light level, returning the new maximum light level * applied. Should not be called when empty. * * @return light level */ public int sync() { return sync = levels[0]; } /** * Adds a new light level to this list. Returns true * if the maximum light level stored has increased as a * result. * * @param level Light level to add * @return True if the maximum light level has increased as a result */ public boolean add(int level) { if (levels == NO_LEVELS) { levels = SINGLE_LEVEL[level]; return true; } else if (level > levels[0]) { int[] new_levels = new int[levels.length + 1]; new_levels[0] = level; System.arraycopy(levels, 0, new_levels, 1, levels.length); levels = new_levels; return true; } else { int[] new_levels = new int[levels.length + 1]; for (int i = 0; i < levels.length; i++) { int other_level = levels[i]; if (level <= other_level) { new_levels[i] = other_level; continue; } // Level must be put here, in place of a previous level // Copy all remaining values after new_levels[i] = level; System.arraycopy(levels, i, new_levels, i+1, levels.length - i); levels = new_levels; return false; } // Add level at the end of the list new_levels[levels.length] = level; levels = new_levels; return false; } } /** * Removes a single light level from this list. Returns true if the maximum * light level has gone down as a result of removing it. * * @param level Light level to remove * @return True if the maximum light level dropped */ public boolean remove(int level) { int len = levels.length; if (len == 1) { // Optimized for if only one level is stored if (levels[0] == level) { levels = NO_LEVELS; return true; } else { return false; } } else if (len == 2) { // Switch to a single by-level, when two values are stored if (levels[1] == level) { levels = SINGLE_LEVEL[levels[0]]; return false; } else if (levels[0] == level) { levels = SINGLE_LEVEL[levels[1]]; return true; } else { return false; } } else if (levels[0] == level) { // List of levels, and the highest light level was removed // If the level following it is lower, then the light level changed int[] new_levels = new int[len - 1]; System.arraycopy(levels, 1, new_levels, 0, len - 1); levels = new_levels; return new_levels[0] != level; } else { // 3 or more requires list remove logic in the middle of the list // The maximum light level doesn't change for (int i = 1; i < len; len++) { if (levels[i] == level) { int[] new_levels = new int[len - 1]; System.arraycopy(levels, 0, new_levels, 0, i); System.arraycopy(levels, i+1, new_levels, i, len - i - 1); levels = new_levels; return false; } } // Not found return false; } } } }
0
0.794022
1
0.794022
game-dev
MEDIA
0.800972
game-dev
0.914267
1
0.914267
the-metalworks/cosmere-rpg
21,209
src/system/utils/handlebars/index.ts
import './application'; import { ArmorTraitId, WeaponTraitId, Skill, Attribute, ItemConsumeType, ActionCostType, DamageType, HoldType, AttackType, TurnSpeed, } from '@src/system/types/cosmere'; import { CosmereActor } from '@system/documents/actor'; import { CosmereItem } from '@system/documents/item'; import { AttributeData } from '@system/data/actor'; import { Derived } from '@system/data/fields'; import { AnyObject, NumberRange } from '@src/system/types/utils'; import { ItemContext, ItemContextOptions } from './types'; import { TEMPLATES } from '../templates'; import { SYSTEM_ID } from '@src/system/constants'; import { CosmereTurn } from '@src/system/applications/combat'; import { ItemConsumeData } from '@src/system/data/item/mixins/activatable'; Handlebars.registerHelper('add', (a: number, b: number) => a + b); Handlebars.registerHelper('sub', (a: number, b: number) => a - b); Handlebars.registerHelper('multi', (a: number, b: number) => a * b); Handlebars.registerHelper('divide', (a: number, b: number) => a / b); Handlebars.registerHelper('mod', (a: number, b: number) => a % b); Handlebars.registerHelper('default', (v: unknown, defaultVal: unknown) => { return v ? v : defaultVal; }); Handlebars.registerHelper('hasKey', (obj: AnyObject, path: string) => { // Split the path const keys = path.split('.'); // Reduce the object return ( keys.reduce( (obj, key, i) => { if (typeof obj === 'boolean') return obj; const isLast = i === keys.length - 1; return obj && key in obj ? isLast ? true : obj[key] ? (obj[key] as AnyObject) : null : null; }, obj as AnyObject | boolean | null, ) !== null ); }); Handlebars.registerHelper( 'replace', (from: string, searchValue: string, replaceValue: string) => { return from.replaceAll(searchValue, replaceValue); }, ); Handlebars.registerHelper('lower', (str: string) => str.toLowerCase()); Handlebars.registerHelper('upper', (str: string) => str.toUpperCase()); Handlebars.registerHelper('typeof', (value: unknown) => { if (value === null) return 'null'; if (value === undefined) return 'undefined'; if (Array.isArray(value)) return 'array'; return typeof value; }); Handlebars.registerHelper( 'perc', (value: number, max: number, floor = true) => { const perc = (value / max) * 100; const str = floor ? Math.floor(perc).toFixed() : perc.toFixed(3); return `${str}%`; }, ); Handlebars.registerHelper( 'times', (count: unknown, options: Handlebars.HelperOptions): string => [...Array(Number(count) || 0).keys()] .map((i) => options.fn(i, { data: options.data as unknown, blockParams: [i], }), ) .join(''), ); Handlebars.registerHelper( 'numberRange', (count: number, min?: number): number[] => Array.fromRange(count, min), ); Handlebars.registerHelper( 'isNumMax', (value: number) => value === Number.MAX_VALUE, ); Handlebars.registerHelper('cosmereDingbat', (type: ActionCostType) => { switch (type) { case ActionCostType.FreeAction: return '0'; case ActionCostType.Reaction: return 'r'; case ActionCostType.Special: return '*'; default: return ''; } }); Handlebars.registerHelper( 'derived', (derived?: Derived<string | number>, includeBonus = true) => { if (!derived) return; return includeBonus ? derived.value : derived.base; }, ); Handlebars.registerHelper('bonus', (obj?: AttributeData) => { if (!obj) return; return obj.value + (obj.bonus ?? 0); }); Handlebars.registerHelper( 'skillMod', (actor: CosmereActor, skill: Skill, attribute?: Attribute) => { return actor.getSkillMod(skill, attribute); }, ); Handlebars.registerHelper( 'formulaReplaceData', (formula: string, data: Record<string, unknown>) => { return Roll.replaceFormulaData(formula, data, { missing: '0' }); }, ); Handlebars.registerHelper('effect-duration', (effect: ActiveEffect) => { if (!effect.isTemporary) return '—'; const seconds = effect.duration.seconds; const turns = effect.duration.turns; const rounds = effect.duration.rounds; if (seconds) return `${seconds}s`; else { return [ rounds ? `${rounds} ${game.i18n!.localize('GENERIC.Rounds')}` : null, turns ? `${turns} ${game.i18n!.localize('GENERIC.Turns')}` : null, ] .filter((v) => !!v) .join(', '); } }); Handlebars.registerHelper( 'inline-partial', (partialName: string, options?: { hash?: AnyObject }) => { return new Handlebars.SafeString( (Handlebars.partials[partialName] as (data?: AnyObject) => string)( options?.hash, ).replace(/"/g, '&quot;'), ); }, ); Handlebars.registerHelper( 'itemContext', (item: CosmereItem, options?: { hash?: ItemContextOptions }) => { try { const context = {} as Partial<ItemContext>; const subtitle = [] as { text: string; classes?: string[] }[]; const isWeapon = item.isWeapon(); if (isWeapon) { context.isWeapon = true; const attack = item.system.attack; subtitle.push({ text: game.i18n!.localize( CONFIG.COSMERE.attack.types[attack.type].label, ), }); if (attack.range?.value) { if ( attack.type === AttackType.Melee && item.system.traits.reach?.active ) { subtitle[0].text += ` + ${attack.range.value}`; } else if (attack.type === AttackType.Ranged) { subtitle[0].text += ` (${attack.range.value}${attack.range.unit}${ attack.range.long ? `/${attack.range.long}${attack.range.unit}` : '' })`; } } } if (item.isArmor() && item.system.deflect) { subtitle.push({ text: `${game.i18n!.localize( 'COSMERE.Item.Armor.Deflect', )} [${item.system.deflect}]`, }); } if (item.isPhysical()) { context.isPhysical = true; context.hasQuantity = item.system.quantity !== null; context.hasWeight = item.system.weight.value !== null; context.quantity = item.system.quantity; context.weight = { value: item.system.weight.value, unit: item.system.weight.unit, total: parseFloat( ( item.system.quantity * item.system.weight.value ).toFixed(2), ), }; context.price = { value: item.system.price.value, unit: item.system.price.unit, }; } if (item.isEquippable() && !item.system.alwaysEquipped) { context.isEquippable = true; context.equipped = item.system.equipped; const type = item.system.equip.type; const hold = item.system.equip.hold; const hand = item.system.equip.hand; context.equip = { type, typeLabel: CONFIG.COSMERE.items.equip.types[type].label, hold, ...(hold ? { holdLabel: CONFIG.COSMERE.items.equip.hold[hold].label, } : {}), hand, ...(hand ? { handLabel: CONFIG.COSMERE.items.equip.hand[hand].label, } : {}), }; if (options?.hash?.showEquippedHand !== false) { if (hold && hold !== HoldType.TwoHanded) { subtitle.push({ text: game.i18n!.localize( CONFIG.COSMERE.items.equip.hold[hold].label, ), }); } } } if (item.hasTraits()) { subtitle.push( ...item.system.traitsArray .filter((trait) => trait.active) .map((trait) => { // Get the config const config = isWeapon ? CONFIG.COSMERE.traits.weaponTraits[ trait.id as WeaponTraitId ] : CONFIG.COSMERE.traits.armorTraits[ trait.id as ArmorTraitId ]; const modifiedByExpertise = trait.active !== trait.defaultActive || trait.value !== trait.defaultValue; return { text: `${game.i18n!.localize(config.label)} ${config.hasValue ? `[${trait.value}]` : ''}`.trim(), classes: modifiedByExpertise ? ['highlight'] : [], }; }) .sort((a, b) => a.classes.length - b.classes.length), ); } if (item.hasActivation()) { context.hasActivation = true; context.activation = {}; if (item.system.activation.cost?.type) { context.activation.hasCost = true; context.activation.cost = { type: item.system.activation.cost.type, typeLabel: CONFIG.COSMERE.action.costs[ item.system.activation.cost.type ].label, value: item.system.activation.cost.value, }; } // Check if a skill test is configured if (item.system.activation.resolvedSkill) { const skill = item.system.activation.resolvedSkill; const attribute = item.system.activation.resolvedAttribute; context.hasSkillTest = true; context.skillTest = { skill, skillLabel: CONFIG.COSMERE.skills[skill].label, usesDefaultAttribute: !attribute || attribute === CONFIG.COSMERE.skills[skill].attribute, ...(attribute ? { attribute, attributeLabel: CONFIG.COSMERE.attributes[attribute] .label, attributeLabelShort: CONFIG.COSMERE.attributes[attribute] .labelShort, } : {}), }; } // Check if the activation consumes some resource if (item.system.activation.consume) { context.consume = []; for (const consumable of item.system.activation.consume) { const consumesResource = consumable.type === ItemConsumeType.Resource; const consumesItem = consumable.type === ItemConsumeType.Item; // Get resource const resource = consumable.resource; context.hasConsume = true; context.consume.push({ type: consumable.type, value: consumable.value, consumesResource, consumesItem, ...(resource ? { resource: consumable.resource, resourceLabel: CONFIG.COSMERE.resources[resource] .label, } : {}), }); } } if (item.system.activation.uses) { const type = item.system.activation.uses.type; const value = item.system.activation.uses.value; const max = item.system.activation.uses.max; const recharge = item.system.activation.uses.recharge; const hasRecharge = recharge != null; // Get config const config = CONFIG.COSMERE.items.activation.uses.types[type]; context.hasUses = true; context.uses = { type, value, label: (max ?? value) > 1 ? config.labelPlural : config.label, max, hasRecharge, recharge, rechargeLabel: hasRecharge ? CONFIG.COSMERE.items.activation.uses.recharge[ recharge ].label : '', }; } } if (item.hasDamage() && item.system.damage.formula) { const skill = item.system.damage.skill; const attribute = item.system.damage.attribute; const hasSkill = !!skill; const hasAttribute = !!attribute; context.hasDamage = true; context.damage = { formula: item.system.damage.formula, formulaData: { ...item.actor?.getRollData(), }, hasSkill, hasAttribute, ...(hasSkill ? { skill, skillLabel: CONFIG.COSMERE.skills[skill].label, usesDefaultAttribute: !hasAttribute || attribute === CONFIG.COSMERE.skills[skill].attribute, } : {}), ...(hasAttribute ? { attribute, attributeLabel: CONFIG.COSMERE.attributes[attribute].label, attributeLabelShort: CONFIG.COSMERE.attributes[attribute] .labelShort, } : {}), ...(item.system.damage.type ? { type: item.system.damage.type, typeLabel: CONFIG.COSMERE.damageTypes[ item.system.damage.type ].label, } : {}), }; } if (item.isAction()) { subtitle.push({ text: game.i18n!.localize( CONFIG.COSMERE.action.types[item.system.type].label, ), }); } return { ...context, subtitle: subtitle .map( ({ text, classes }) => `<span class=${(classes ?? []).join(' ')}>${text}</span>`, ) .join('<span>, </span>'), }; } catch (err) { console.error(err); throw err; } }, ); Handlebars.registerHelper('damageTypeConfig', (type: DamageType) => { return CONFIG.COSMERE.damageTypes[type]; }); Handlebars.registerHelper('getCombatActedState', (turn: CosmereTurn) => { // use default activated for boss slow turns, and all other combatants' turns if (!turn.isBoss || turn.turnSpeed === TurnSpeed.Slow) { return turn.activated; } // track a boss's additional fast turn separately return turn.bossFastActivated; }); /** * Get the resource cost label of an item in an actor's action list */ Handlebars.registerHelper('resourceCostLabel', (consume: ItemConsumeData) => { const { value } = consume; const resource = game.i18n!.localize( consume.resource ? CONFIG.COSMERE.resources[consume.resource].label : 'GENERIC.Unknown', ); let label = ''; // Get adjusted minimum value, to account for optional formatting const adjustedMin = Math.max(value.min, 1); // Static range if (adjustedMin === value.max) { label = game.i18n!.format( 'COSMERE.Actor.Sheet.Actions.Consume.Static', { amount: adjustedMin, resource, }, ); } // Uncapped range else if (value.max === -1) { label = game.i18n!.format( 'COSMERE.Actor.Sheet.Actions.Consume.RangeUncapped', { amount: adjustedMin, resource, }, ); } // Capped range else { label = game.i18n!.format( 'COSMERE.Actor.Sheet.Actions.Consume.RangeCapped', { min: adjustedMin, max: value.max, resource, }, ); } // Treat actual minimum value of 0 as an "optional" cost if (value.min === 0) { label = game.i18n!.format( 'COSMERE.Actor.Sheet.Actions.Consume.Optional', { label, }, ); } return label; }); /** * Format the resource cost input field of an item's activation config */ Handlebars.registerHelper('resourceCostInput', (value: NumberRange) => { if (value.min === value.max) { return value.min.toString(); } else if (value.max === -1) { return `${value.min}+`; } else { return `${value.min}-${value.max}`; } }); Handlebars.registerHelper('entries', (obj: AnyObject) => { return Object.entries(obj).map(([key, value]) => ({ key, value })); }); Handlebars.registerHelper('filterSelectOptions', (( selectOptions: Record<string, string> | (() => Record<string, string>), ...args: [...string[], Handlebars.HelperOptions] ) => { if (typeof selectOptions === 'function') selectOptions = selectOptions(); const filters = args.slice(0, -1); const options = args[args.length - 1]; const filterSet = new Set(filters as unknown as string[]); return Object.entries(selectOptions) .filter(([key]) => !filterSet.has(key)) .reduce( (acc, [key, value]) => { acc[key] = value; return acc; }, {} as Record<string, string>, ); }) as unknown as Handlebars.HelperDelegate); export async function preloadHandlebarsTemplates() { const templates = Object.values(TEMPLATES).reduce( (partials, path) => { partials[path.split('/').pop()!.replace('.hbs', '')] = `systems/${SYSTEM_ID}/templates/${path}`; return partials; }, {} as Record<string, string>, ); return await loadTemplates(templates); }
0
0.856945
1
0.856945
game-dev
MEDIA
0.668871
game-dev,web-frontend
0.968201
1
0.968201
SourceEngine-CommunityEdition/source
2,210
game/client/c_func_dust.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #ifndef C_FUNC_DUST_H #define C_FUNC_DUST_H #ifdef _WIN32 #pragma once #endif #include "c_baseentity.h" #include "particles_simple.h" #include "particle_util.h" #include "bspflags.h" // ------------------------------------------------------------------------------------ // // CDustEffect particle renderer. // ------------------------------------------------------------------------------------ // class C_Func_Dust; class CFuncDustParticle : public Particle { public: Vector m_vVelocity; float m_flLifetime; float m_flDieTime; float m_flSize; color32 m_Color; }; class CDustEffect : public CParticleEffect { public: CDustEffect( const char *pDebugName ) : CParticleEffect( pDebugName ) {} virtual void RenderParticles( CParticleRenderIterator *pIterator ); virtual void SimulateParticles( CParticleSimulateIterator *pIterator ); C_Func_Dust *m_pDust; private: CDustEffect( const CDustEffect & ); // not defined, not accessible }; // ------------------------------------------------------------------------------------ // // C_Func_Dust class. // ------------------------------------------------------------------------------------ // class C_Func_Dust : public C_BaseEntity { public: DECLARE_CLASS( C_Func_Dust, C_BaseEntity ); DECLARE_CLIENTCLASS(); C_Func_Dust(); virtual ~C_Func_Dust(); virtual void OnDataChanged( DataUpdateType_t updateType ); virtual void ClientThink(); virtual bool ShouldDraw(); private: void AttemptSpawnNewParticle(); // Vars from server. public: color32 m_Color; int m_SpawnRate; float m_flSizeMin; float m_flSizeMax; int m_SpeedMax; int m_LifetimeMin; int m_LifetimeMax; int m_DistMax; float m_FallSpeed; // extra 'gravity' public: int m_DustFlags; // Combination of DUSTFLAGS_ public: CDustEffect m_Effect; PMaterialHandle m_hMaterial; TimedEvent m_Spawner; private: C_Func_Dust( const C_Func_Dust & ); // not defined, not accessible }; #endif // C_FUNC_DUST_H
0
0.884318
1
0.884318
game-dev
MEDIA
0.638744
game-dev,graphics-rendering
0.543091
1
0.543091
ImLegiitXD/Dream-Advanced
2,399
dll/back/1.8.9/net/minecraft/entity/ai/EntityMinecartMobSpawner.java
package net.minecraft.entity.ai; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityMinecart; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.MobSpawnerBaseLogic; import net.minecraft.util.BlockPos; import net.minecraft.world.World; public class EntityMinecartMobSpawner extends EntityMinecart { /** Mob spawner logic for this spawner minecart. */ private final MobSpawnerBaseLogic mobSpawnerLogic = new MobSpawnerBaseLogic() { public void func_98267_a(int id) { EntityMinecartMobSpawner.this.worldObj.setEntityState(EntityMinecartMobSpawner.this, (byte)id); } public World getSpawnerWorld() { return EntityMinecartMobSpawner.this.worldObj; } public BlockPos getSpawnerPosition() { return new BlockPos(EntityMinecartMobSpawner.this); } }; public EntityMinecartMobSpawner(World worldIn) { super(worldIn); } public EntityMinecartMobSpawner(World worldIn, double p_i1726_2_, double p_i1726_4_, double p_i1726_6_) { super(worldIn, p_i1726_2_, p_i1726_4_, p_i1726_6_); } public EntityMinecart.EnumMinecartType getMinecartType() { return EntityMinecart.EnumMinecartType.SPAWNER; } public IBlockState getDefaultDisplayTile() { return Blocks.mob_spawner.getDefaultState(); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound tagCompund) { super.readEntityFromNBT(tagCompund); this.mobSpawnerLogic.readFromNBT(tagCompund); } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ protected void writeEntityToNBT(NBTTagCompound tagCompound) { super.writeEntityToNBT(tagCompound); this.mobSpawnerLogic.writeToNBT(tagCompound); } public void handleStatusUpdate(byte id) { this.mobSpawnerLogic.setDelayToMin(id); } /** * Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); this.mobSpawnerLogic.updateSpawner(); } public MobSpawnerBaseLogic func_98039_d() { return this.mobSpawnerLogic; } }
0
0.878071
1
0.878071
game-dev
MEDIA
0.9894
game-dev
0.847935
1
0.847935
Ravaelles/Atlantis
2,450
src/atlantis/combat/micro/avoid/special/AvoidTanksSieged.java
package atlantis.combat.micro.avoid.special; import atlantis.architecture.Manager; import atlantis.information.enemy.EnemyUnits; import atlantis.units.AUnit; import atlantis.units.actions.Actions; import atlantis.game.player.Enemy; import atlantis.util.We; import bwapi.Color; public class AvoidTanksSieged extends Manager { private AUnit tankSieged; private double distToTank; public AvoidTanksSieged(AUnit unit) { super(unit); } @Override public boolean applies() { if (unit.isMissionDefendOrSparta()) return false; // AUnit tank = unit.enemiesNear().tanksSieged().first(); // System.out.println( // "unit = " + unit + " / ev:" + unit.eval() + " / sieged: " + // unit.enemiesNear().tanksSieged().size() + " / enemyEval:" // + (tank != null ? tank.eval() : "-") // ); return Enemy.terran() && unit.isGroundUnit() && !unit.isSieged() && (tankSieged = tank()) != null && (distToTank = unit.distTo(tankSieged)) <= 16 && notStrongerLocally() && tankSieged.distToBase() >= 25; } private boolean notStrongerLocally() { return unit.eval() <= 2.5 && (moreEnemyTanksThanOurUnits() || almostDeadAndFarFromFight()); } private boolean almostDeadAndFarFromFight() { if (!We.protoss()) return false; return unit.hp() <= 75 && distToTank >= 5; } private boolean moreEnemyTanksThanOurUnits() { return (tankSieged.friendsNear().combatUnits().countInRadius(7, unit) + 2) >= unit.friendsNear().combatUnits().countInRadius(9, unit); } private AUnit tank() { return EnemyUnits.discovered() .tanksSieged() .inRadius(13.5 + unit.woundPercent() / 30.0, unit) .nearestTo(unit); } @Override protected Manager handle() { if (tankSieged == null) return null; tankSieged.paintRectangle(1.1, 0.8, Color.Orange); tankSieged.paintRectangle(1.06, 0.76, Color.Orange); if (!unit.isAttacking() && unit.cooldown() <= 7 && unit.distTo(tankSieged) <= 0.7) { unit.holdPosition(Actions.HOLD_POSITION, "TANK!"); return usedManager(this); } unit.setTooltip("TANK!"); unit.runningManager().runFrom(tankSieged, 2, Actions.MOVE_AVOID, false); return usedManager(this); } }
0
0.864104
1
0.864104
game-dev
MEDIA
0.972133
game-dev
0.85541
1
0.85541
Tareq-Khalil/hawkthorne-Center
2,056
src/nodes/mailbox.lua
--special mailbox node for a Save Greendale quest with Frankie local Dialog = require 'dialog' local anim8 = require 'vendor/anim8' local utils = require 'utils' local prompt = require 'prompt' local player = require 'player' local Quest = require 'quest' local quests = require 'npcs/quests/frankiequest' local Mailbox = {} Mailbox.__index = Mailbox function Mailbox.new(node, collider) local mailbox = {} setmetatable(mailbox, Mailbox) mailbox.bb = collider:addRectangle(node.x, node.y, node.width, node.height) mailbox.bb.node = mailbox Mailbox.node = node collider:setPassive(mailbox.bb) return mailbox end function Mailbox:keypressed( button, player ) if button == 'INTERACT' and self.dialog == nil and not player.freeze then if player.quest == 'Save Greendale - Mail Diane' and player.inventory:hasKey('document') then self.prompt = prompt.new("Deposit document into mailbox?", function(result) if result == 'Yes' then player.freeze = true player.inventory:removeManyItems(1, {name='document',type='key'}) Dialog.new("Document successfuly deposited into the mailbox! Cue montage and return to Frankie.", function() Quest.removeQuestItem(player) Quest.addQuestItem(quests.dianereturn, player) player.quest = 'Save Greendale - Return to Frankie' Quest:save(quests.dianereturn) end) end player.freeze = false self.prompt = nil end) elseif player.quest == 'Save Greendale - Mail Diane' and not player.inventory:hasKey('document') then player.freeze = true Dialog.new("The document seems to be missing from your inventory. Cue montage of trying to find it!", function() player.freeze = false Dialog.currentDialog = nil end) else player.freeze = true Dialog.new("You don't have anything to mail right now.", function() player.freeze = false Dialog.currentDialog = nil end) end return true end end return Mailbox
0
0.878822
1
0.878822
game-dev
MEDIA
0.819633
game-dev
0.933565
1
0.933565
xiaoyaocz/dart_simple_live
16,519
simple_live_app/lib/app/controller/app_settings_controller.dart
import 'dart:io'; import 'package:simple_live_app/app/constant.dart'; import 'package:simple_live_app/app/log.dart'; import 'package:simple_live_app/app/sites.dart'; import 'package:simple_live_app/services/local_storage_service.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class AppSettingsController extends GetxController { static AppSettingsController get instance => Get.find<AppSettingsController>(); /// 缩放模式 var scaleMode = 0.obs; var themeMode = 0.obs; var firstRun = false; @override void onInit() { themeMode.value = LocalStorageService.instance .getValue(LocalStorageService.kThemeMode, 0); firstRun = LocalStorageService.instance .getValue(LocalStorageService.kFirstRun, true); danmuSize.value = LocalStorageService.instance .getValue(LocalStorageService.kDanmuSize, 16.0); danmuOpacity.value = LocalStorageService.instance .getValue(LocalStorageService.kDanmuOpacity, 1.0); danmuArea.value = LocalStorageService.instance .getValue(LocalStorageService.kDanmuArea, 0.8); danmuSpeed.value = LocalStorageService.instance .getValue(LocalStorageService.kDanmuSpeed, 10.0); danmuEnable.value = LocalStorageService.instance .getValue(LocalStorageService.kDanmuEnable, true); danmuStrokeWidth.value = LocalStorageService.instance .getValue(LocalStorageService.kDanmuStrokeWidth, 2.0); danmuTopMargin.value = LocalStorageService.instance .getValue(LocalStorageService.kDanmuTopMargin, 0.0); danmuBottomMargin.value = LocalStorageService.instance .getValue(LocalStorageService.kDanmuBottomMargin, 0.0); danmuFontWeight.value = LocalStorageService.instance.getValue( LocalStorageService.kDanmuFontWeight, FontWeight.normal.index); hardwareDecode.value = LocalStorageService.instance .getValue(LocalStorageService.kHardwareDecode, true); chatTextSize.value = LocalStorageService.instance .getValue(LocalStorageService.kChatTextSize, 14.0); chatTextGap.value = LocalStorageService.instance .getValue(LocalStorageService.kChatTextGap, 4.0); chatBubbleStyle.value = LocalStorageService.instance.getValue( LocalStorageService.kChatBubbleStyle, false, ); qualityLevel.value = LocalStorageService.instance .getValue(LocalStorageService.kQualityLevel, 1); qualityLevelCellular.value = LocalStorageService.instance .getValue(LocalStorageService.kQualityLevelCellular, 1); autoExitEnable.value = LocalStorageService.instance .getValue(LocalStorageService.kAutoExitEnable, false); autoExitDuration.value = LocalStorageService.instance .getValue(LocalStorageService.kAutoExitDuration, 60); roomAutoExitDuration.value = LocalStorageService.instance .getValue(LocalStorageService.kRoomAutoExitDuration, 60); playerCompatMode.value = LocalStorageService.instance .getValue(LocalStorageService.kPlayerCompatMode, false); playerAutoPause.value = LocalStorageService.instance .getValue(LocalStorageService.kPlayerAutoPause, false); playerForceHttps.value = LocalStorageService.instance .getValue(LocalStorageService.kPlayerForceHttps, false); autoFullScreen.value = LocalStorageService.instance .getValue(LocalStorageService.kAutoFullScreen, false); // ignore: invalid_use_of_protected_member shieldList.value = LocalStorageService.instance.shieldBox.values.toSet(); scaleMode.value = LocalStorageService.instance.getValue( LocalStorageService.kPlayerScaleMode, 0, ); playerVolume.value = LocalStorageService.instance.getValue( LocalStorageService.kPlayerVolume, 100.0, ); pipHideDanmu.value = LocalStorageService.instance .getValue(LocalStorageService.kPIPHideDanmu, true); styleColor.value = LocalStorageService.instance .getValue(LocalStorageService.kStyleColor, 0xff3498db); isDynamic.value = LocalStorageService.instance .getValue(LocalStorageService.kIsDynamic, false); bilibiliLoginTip.value = LocalStorageService.instance .getValue(LocalStorageService.kBilibiliLoginTip, true); playerBufferSize.value = LocalStorageService.instance .getValue(LocalStorageService.kPlayerBufferSize, 32); logEnable.value = LocalStorageService.instance .getValue(LocalStorageService.kLogEnable, false); if (logEnable.value) { Log.initWriter(); } customPlayerOutput.value = LocalStorageService.instance .getValue(LocalStorageService.kCustomPlayerOutput, false); videoOutputDriver.value = LocalStorageService.instance.getValue( LocalStorageService.kVideoOutputDriver, Platform.isAndroid ? "gpu" : "libmpv", ); audioOutputDriver.value = LocalStorageService.instance.getValue( LocalStorageService.kAudioOutputDriver, Platform.isAndroid ? "audiotrack" : Platform.isLinux ? "pulse" : Platform.isWindows ? "wasapi" : Platform.isIOS ? "audiounit" : Platform.isMacOS ? "coreaudio" : "sdl", ); videoHardwareDecoder.value = LocalStorageService.instance.getValue( LocalStorageService.kVideoHardwareDecoder, Platform.isAndroid ? "auto-safe" : "auto", ); autoUpdateFollowEnable.value = LocalStorageService.instance .getValue(LocalStorageService.kAutoUpdateFollowEnable, true); autoUpdateFollowDuration.value = LocalStorageService.instance .getValue(LocalStorageService.kUpdateFollowDuration, 10); updateFollowThreadCount.value = LocalStorageService.instance .getValue(LocalStorageService.kUpdateFollowThreadCount, 4); initSiteSort(); initHomeSort(); super.onInit(); } void initSiteSort() { var sort = LocalStorageService.instance .getValue( LocalStorageService.kSiteSort, Sites.allSites.keys.join(","), ) .split(","); //如果数量与allSites的数量不一致,将缺失的添加上 if (sort.length != Sites.allSites.length) { var keys = Sites.allSites.keys.toList(); for (var i = 0; i < keys.length; i++) { if (!sort.contains(keys[i])) { sort.add(keys[i]); } } } siteSort.value = sort; } void initHomeSort() { var sort = LocalStorageService.instance .getValue( LocalStorageService.kHomeSort, Constant.allHomePages.keys.join(","), ) .split(","); //如果数量与allSites的数量不一致,将缺失的添加上 if (sort.length != Constant.allHomePages.length) { var keys = Constant.allHomePages.keys.toList(); for (var i = 0; i < keys.length; i++) { if (!sort.contains(keys[i])) { sort.add(keys[i]); } } } homeSort.value = sort; } void setNoFirstRun() { LocalStorageService.instance.setValue(LocalStorageService.kFirstRun, false); } void changeTheme() { Get.dialog( SimpleDialog( title: const Text("设置主题"), children: [ RadioListTile<int>( title: const Text("跟随系统"), value: 0, groupValue: themeMode.value, onChanged: (e) { Get.back(); setTheme(e ?? 0); }, ), RadioListTile<int>( title: const Text("浅色模式"), value: 1, groupValue: themeMode.value, onChanged: (e) { Get.back(); setTheme(e ?? 1); }, ), RadioListTile<int>( title: const Text("深色模式"), value: 2, groupValue: themeMode.value, onChanged: (e) { Get.back(); setTheme(e ?? 2); }, ), ], ), ); } void setTheme(int i) { themeMode.value = i; var mode = ThemeMode.values[i]; LocalStorageService.instance.setValue(LocalStorageService.kThemeMode, i); Get.changeThemeMode(mode); } var hardwareDecode = true.obs; void setHardwareDecode(bool e) { hardwareDecode.value = e; LocalStorageService.instance .setValue(LocalStorageService.kHardwareDecode, e); } var chatTextSize = 14.0.obs; void setChatTextSize(double e) { chatTextSize.value = e; LocalStorageService.instance.setValue(LocalStorageService.kChatTextSize, e); } var chatTextGap = 4.0.obs; void setChatTextGap(double e) { chatTextGap.value = e; LocalStorageService.instance.setValue(LocalStorageService.kChatTextGap, e); } var chatBubbleStyle = false.obs; void setChatBubbleStyle(bool e) { chatBubbleStyle.value = e; LocalStorageService.instance .setValue(LocalStorageService.kChatBubbleStyle, e); } var danmuSize = 16.0.obs; void setDanmuSize(double e) { danmuSize.value = e; LocalStorageService.instance.setValue(LocalStorageService.kDanmuSize, e); } var danmuSpeed = 10.0.obs; void setDanmuSpeed(double e) { danmuSpeed.value = e; LocalStorageService.instance.setValue(LocalStorageService.kDanmuSpeed, e); } var danmuArea = 0.8.obs; void setDanmuArea(double e) { danmuArea.value = e; LocalStorageService.instance.setValue(LocalStorageService.kDanmuArea, e); } var danmuOpacity = 1.0.obs; void setDanmuOpacity(double e) { danmuOpacity.value = e; LocalStorageService.instance.setValue(LocalStorageService.kDanmuOpacity, e); } var danmuEnable = true.obs; void setDanmuEnable(bool e) { danmuEnable.value = e; LocalStorageService.instance.setValue(LocalStorageService.kDanmuEnable, e); } var danmuStrokeWidth = 2.0.obs; void setDanmuStrokeWidth(double e) { danmuStrokeWidth.value = e; LocalStorageService.instance .setValue(LocalStorageService.kDanmuStrokeWidth, e); } var danmuFontWeight = FontWeight.normal.index.obs; void setDanmuFontWeight(int e) { danmuFontWeight.value = e; LocalStorageService.instance .setValue(LocalStorageService.kDanmuFontWeight, e); } var qualityLevel = 1.obs; void setQualityLevel(int level) { qualityLevel.value = level; LocalStorageService.instance .setValue(LocalStorageService.kQualityLevel, level); } var qualityLevelCellular = 1.obs; void setQualityLevelCellular(int level) { qualityLevelCellular.value = level; LocalStorageService.instance .setValue(LocalStorageService.kQualityLevelCellular, level); } var autoExitEnable = false.obs; void setAutoExitEnable(bool e) { autoExitEnable.value = e; LocalStorageService.instance .setValue(LocalStorageService.kAutoExitEnable, e); } var autoExitDuration = 60.obs; void setAutoExitDuration(int e) { autoExitDuration.value = e; LocalStorageService.instance .setValue(LocalStorageService.kAutoExitDuration, e); } var roomAutoExitDuration = 60.obs; void setRoomAutoExitDuration(int e) { roomAutoExitDuration.value = e; LocalStorageService.instance .setValue(LocalStorageService.kRoomAutoExitDuration, e); } var playerCompatMode = false.obs; void setPlayerCompatMode(bool e) { playerCompatMode.value = e; LocalStorageService.instance .setValue(LocalStorageService.kPlayerCompatMode, e); } var playerBufferSize = 32.obs; void setPlayerBufferSize(int e) { playerBufferSize.value = e; LocalStorageService.instance .setValue(LocalStorageService.kPlayerBufferSize, e); } var playerAutoPause = false.obs; void setPlayerAutoPause(bool e) { playerAutoPause.value = e; LocalStorageService.instance .setValue(LocalStorageService.kPlayerAutoPause, e); } var autoFullScreen = false.obs; void setAutoFullScreen(bool e) { autoFullScreen.value = e; LocalStorageService.instance .setValue(LocalStorageService.kAutoFullScreen, e); } var playershowSuperChat = true.obs; void setPlayerShowSuperChat(bool e) { playershowSuperChat.value = e; LocalStorageService.instance .setValue(LocalStorageService.kPlayerShowSuperChat, e); } RxSet<String> shieldList = <String>{}.obs; void addShieldList(String e) { shieldList.add(e); LocalStorageService.instance.shieldBox.put(e, e); } void removeShieldList(String e) { shieldList.remove(e); LocalStorageService.instance.shieldBox.delete(e); } Future clearShieldList() async { shieldList.clear(); await LocalStorageService.instance.shieldBox.clear(); } void setScaleMode(int value) { scaleMode.value = value; LocalStorageService.instance.setValue( LocalStorageService.kPlayerScaleMode, value, ); } RxList<String> siteSort = RxList<String>(); void setSiteSort(List<String> e) { siteSort.value = e; LocalStorageService.instance.setValue( LocalStorageService.kSiteSort, siteSort.join(","), ); } RxList<String> homeSort = RxList<String>(); void setHomeSort(List<String> e) { homeSort.value = e; LocalStorageService.instance.setValue( LocalStorageService.kHomeSort, homeSort.join(","), ); } Rx<double> playerVolume = 100.0.obs; void setPlayerVolume(double value) { playerVolume.value = value; LocalStorageService.instance.setValue( LocalStorageService.kPlayerVolume, value, ); } var pipHideDanmu = true.obs; void setPIPHideDanmu(bool e) { pipHideDanmu.value = e; LocalStorageService.instance.setValue(LocalStorageService.kPIPHideDanmu, e); } var styleColor = 0xff3498db.obs; void setStyleColor(int e) { styleColor.value = e; LocalStorageService.instance.setValue(LocalStorageService.kStyleColor, e); } var isDynamic = false.obs; void setIsDynamic(bool e) { isDynamic.value = e; LocalStorageService.instance.setValue(LocalStorageService.kIsDynamic, e); } var danmuTopMargin = 0.0.obs; void setDanmuTopMargin(double e) { danmuTopMargin.value = e; LocalStorageService.instance .setValue(LocalStorageService.kDanmuTopMargin, e); } var danmuBottomMargin = 0.0.obs; void setDanmuBottomMargin(double e) { danmuBottomMargin.value = e; LocalStorageService.instance .setValue(LocalStorageService.kDanmuBottomMargin, e); } var bilibiliLoginTip = true.obs; void setBiliBiliLoginTip(bool e) { bilibiliLoginTip.value = e; LocalStorageService.instance .setValue(LocalStorageService.kBilibiliLoginTip, e); } var logEnable = false.obs; void setLogEnable(bool e) { logEnable.value = e; LocalStorageService.instance.setValue(LocalStorageService.kLogEnable, e); } var customPlayerOutput = false.obs; void setCustomPlayerOutput(bool e) { customPlayerOutput.value = e; LocalStorageService.instance .setValue(LocalStorageService.kCustomPlayerOutput, e); } var videoOutputDriver = "".obs; void setVideoOutputDriver(String e) { videoOutputDriver.value = e; LocalStorageService.instance .setValue(LocalStorageService.kVideoOutputDriver, e); } var audioOutputDriver = "".obs; void setAudioOutputDriver(String e) { audioOutputDriver.value = e; LocalStorageService.instance .setValue(LocalStorageService.kAudioOutputDriver, e); } var videoHardwareDecoder = "".obs; void setVideoHardwareDecoder(String e) { videoHardwareDecoder.value = e; LocalStorageService.instance .setValue(LocalStorageService.kVideoHardwareDecoder, e); } var autoUpdateFollowEnable = false.obs; void setAutoUpdateFollowEnable(bool e) { autoUpdateFollowEnable.value = e; LocalStorageService.instance .setValue(LocalStorageService.kAutoUpdateFollowEnable, e); } var autoUpdateFollowDuration = 10.obs; void setAutoUpdateFollowDuration(int e) { autoUpdateFollowDuration.value = e; LocalStorageService.instance .setValue(LocalStorageService.kUpdateFollowDuration, e); } var updateFollowThreadCount = 4.obs; void setUpdateFollowThreadCount(int e) { updateFollowThreadCount.value = e; LocalStorageService.instance .setValue(LocalStorageService.kUpdateFollowThreadCount, e); } var playerForceHttps = false.obs; void setPlayerForceHttps(bool e) { playerForceHttps.value = e; LocalStorageService.instance .setValue(LocalStorageService.kPlayerForceHttps, e); } }
0
0.812287
1
0.812287
game-dev
MEDIA
0.528193
game-dev
0.868658
1
0.868658
Debian/apt
7,542
methods/cdrom.cc
// -*- mode: cpp; mode: fold -*- // Description /*{{{*/ /* ###################################################################### CDROM URI method for APT ##################################################################### */ /*}}}*/ // Include Files /*{{{*/ #include <config.h> #include <apt-pkg/cdrom.h> #include <apt-pkg/cdromutl.h> #include <apt-pkg/configuration.h> #include <apt-pkg/error.h> #include <apt-pkg/fileutl.h> #include <apt-pkg/hashes.h> #include <apt-pkg/strutl.h> #include "aptmethod.h" #include <string> #include <vector> #include <sys/stat.h> #include <iostream> #include <apti18n.h> /*}}}*/ using namespace std; class CDROMMethod : public aptMethod { bool DatabaseLoaded; bool Debug; ::Configuration Database; string CurrentID; string CDROM; bool MountedByApt; pkgUdevCdromDevices UdevCdroms; bool IsCorrectCD(URI want, string MountPath, string& NewID); bool AutoDetectAndMount(const URI, string &NewID); bool Fetch(FetchItem *Itm) override; std::string GetID(std::string const &Name); void Exit() override; bool Configuration(std::string Message) override; public: CDROMMethod(); }; // CDROMMethod::CDROMethod - Constructor /*{{{*/ // --------------------------------------------------------------------- /* */ CDROMMethod::CDROMMethod() : aptMethod("cdrom", "1.0",SingleInstance | LocalOnly | SendConfig | NeedsCleanup | Removable | SendURIEncoded), DatabaseLoaded(false), Debug(false), MountedByApt(false) { } /*}}}*/ // CDROMMethod::Exit - Unmount the disc if necessary /*{{{*/ // --------------------------------------------------------------------- /* */ void CDROMMethod::Exit() { if (MountedByApt == true) UnmountCdrom(CDROM); } /*}}}*/ // CDROMMethod::GetID - Search the database for a matching string /*{{{*/ // --------------------------------------------------------------------- /* */ std::string CDROMMethod::GetID(std::string const &Name) { // Search for an ID const Configuration::Item *Top = Database.Tree("CD"); if (Top != 0) Top = Top->Child; for (; Top != 0;) { if (Top->Value == Name) return Top->Tag; Top = Top->Next; } return string(); } /*}}}*/ // CDROMMethod::AutoDetectAndMount /*{{{*/ // --------------------------------------------------------------------- /* Modifies class variable CDROM to the mountpoint */ bool CDROMMethod::AutoDetectAndMount(const URI Get, string &NewID) { vector<struct CdromDevice> v = UdevCdroms.Scan(); // first check if its mounted somewhere already for (unsigned int i=0; i < v.size(); i++) { if (v[i].Mounted) { if (Debug) clog << "Checking mounted cdrom device " << v[i].DeviceName << endl; if (IsCorrectCD(Get, v[i].MountPath, NewID)) { CDROM = v[i].MountPath; return true; } } } // we are not supposed to mount, exit if (_config->FindB("APT::CDROM::NoMount",false) == true) return false; // check if we have the mount point string AptMountPoint = _config->FindDir("Dir::Media::MountPath"); if (!FileExists(AptMountPoint)) mkdir(AptMountPoint.c_str(), 0750); // now try mounting for (unsigned int i=0; i < v.size(); i++) { if (!v[i].Mounted) { if(MountCdrom(AptMountPoint, v[i].DeviceName)) { if (IsCorrectCD(Get, AptMountPoint, NewID)) { MountedByApt = true; CDROM = AptMountPoint; return true; } else { UnmountCdrom(AptMountPoint); } } } } return false; } /*}}}*/ // CDROMMethod::IsCorrectCD /*{{{*/ // --------------------------------------------------------------------- /* */ bool CDROMMethod::IsCorrectCD(URI want, string MountPath, string& NewID) { for (unsigned int Version = 2; Version != 0; Version--) { if (IdentCdrom(MountPath,NewID,Version) == false) return false; if (Debug) clog << "ID " << Version << " " << NewID << endl; // A hit if (Database.Find("CD::" + NewID) == want.Host) return true; } return false; } /*}}}*/ // CDROMMethod::Fetch - Fetch a file /*{{{*/ // --------------------------------------------------------------------- /* */ bool CDROMMethod::Fetch(FetchItem *Itm) { FetchResult Res; URI Get(Itm->Uri); std::string const File = DecodeSendURI(Get.Path); Debug = DebugEnabled(); if (Debug) clog << "CDROMMethod::Fetch " << Itm->Uri << endl; /* All IMS queries are returned as a hit, CDROMs are readonly so time stamps never change */ if (Itm->LastModified != 0) { Res.LastModified = Itm->LastModified; Res.IMSHit = true; Res.Filename = Itm->DestFile; URIDone(Res); return true; } // Load the database if (DatabaseLoaded == false) { // Read the database string DFile = _config->FindFile("Dir::State::cdroms"); if (FileExists(DFile) == true) { if (ReadConfigFile(Database,DFile) == false) return _error->Error(_("Unable to read the cdrom database %s"), DFile.c_str()); } DatabaseLoaded = true; } // All non IMS queries for package files fail. if (Itm->IndexFile == true || GetID(Get.Host).empty() == true) { Fail(_("Please use apt-cdrom to make this CD-ROM recognized by APT." " apt-get update cannot be used to add new CD-ROMs")); return true; } // We already have a CD inserted, but it is the wrong one if (CurrentID.empty() == false && CurrentID != "FAIL" && Database.Find("CD::" + CurrentID) != Get.Host) { Fail(_("Wrong CD-ROM"),true); return true; } bool const AutoDetect = ConfigFindB("AutoDetect", true); CDROM = _config->FindDir("Acquire::cdrom::mount"); if (Debug) clog << "Looking for CDROM at " << CDROM << endl; if (CDROM[0] == '.') CDROM= SafeGetCWD() + '/' + CDROM; string NewID; while (CurrentID.empty() == true) { if (AutoDetect) AutoDetectAndMount(Get, NewID); if(!IsMounted(CDROM)) MountedByApt = MountCdrom(CDROM); if (IsCorrectCD(Get, CDROM, NewID)) break; // I suppose this should prompt somehow? if (_config->FindB("APT::CDROM::NoMount",false) == false && UnmountCdrom(CDROM) == false) return _error->Error(_("Unable to unmount the CD-ROM in %s, it may still be in use."), CDROM.c_str()); if (MediaFail(Get.Host,CDROM) == false) { CurrentID = "FAIL"; return _error->Error(_("Disk not found.")); } } // Found a CD Res.Filename = CDROM + File; struct stat Buf; if (stat(Res.Filename.c_str(),&Buf) != 0) return _error->Error(_("File not found")); URIStart(Res); if (NewID.empty() == false) CurrentID = NewID; Res.LastModified = Buf.st_mtime; Res.Size = Buf.st_size; Hashes Hash(Itm->ExpectedHashes); FileFd Fd(Res.Filename, FileFd::ReadOnly); Hash.AddFD(Fd); Res.TakeHashes(Hash); URIDone(Res); return true; } /*}}}*/ bool CDROMMethod::Configuration(std::string Message) /*{{{*/ { _config->CndSet("Binary::cdrom::Debug::NoDropPrivs", true); return aptMethod::Configuration(Message); } /*}}}*/ int main() { return CDROMMethod().Run(); }
0
0.911159
1
0.911159
game-dev
MEDIA
0.231391
game-dev
0.940147
1
0.940147
pharo-project/pharo
28,780
src/Ring-Core/RGBehavior.class.st
" An RGBehavior is an abstract definition for class-alike entities (e.g. classes, traits) Instance Variables methods: <Collection> protocols: <Collection> superclass: <Object> " Class { #name : 'RGBehavior', #superclass : 'RGBehaviorStrategyUser', #instVars : [ 'superclass', 'localMethods', 'traitComposition', 'metaclass', 'tagsForMethods', 'tags' ], #category : 'Ring-Core-Kernel', #package : 'Ring-Core', #tag : 'Kernel' } { #category : 'private - accessing' } RGBehavior class >> badInstantiationError [ RGBadInstantiationError signal: 'I cannot be instantiated this way because every RGBehavior must know its proper behavior strategy. Please use a subclass of RGBehaviorFactory or my methods like #newClass' ] { #category : 'accessing' } RGBehavior class >> named: aString [ ^ self badInstantiationError ] { #category : 'accessing' } RGBehavior class >> named: aName behaviorStrategy: anRGBehaviorStrategy [ | aBehavior | aBehavior := self basicNew behaviorStrategy: anRGBehaviorStrategy; initialize. anRGBehaviorStrategy initialize. ^ aBehavior pvtName: aName asSymbol; yourself ] { #category : 'accessing' } RGBehavior class >> named: aString parent: anRGObject [ ^ self badInstantiationError ] { #category : 'accessing' } RGBehavior class >> named: aName parent: anRGObject behaviorStrategy: anRGBehaviorStrategy [ | aBehavior | aBehavior := self basicNew behaviorStrategy: anRGBehaviorStrategy; parent: anRGObject; initialize. anRGBehaviorStrategy initialize. ^ aBehavior pvtName: aName asSymbol; yourself ] { #category : 'instance creation' } RGBehavior class >> newClass [ ^ self unnamedWithBehaviorStrategy: RGClassStrategy basicNew ] { #category : 'instance creation' } RGBehavior class >> newMetaclass [ ^ self unnamedWithBehaviorStrategy: RGMetaclassStrategy basicNew ] { #category : 'instance creation' } RGBehavior class >> newMetaclassTrait [ ^ self unnamedWithBehaviorStrategy: RGMetaclassTrait newStrategy ] { #category : 'instance creation' } RGBehavior class >> newTrait [ ^ self unnamedWithBehaviorStrategy: RGTrait newStrategy ] { #category : 'accessing' } RGBehavior class >> parent: anRGObject behaviorStrategy: anRGBehaviorStrategy [ | aBehavior | aBehavior := self basicNew behaviorStrategy: anRGBehaviorStrategy; parent: anRGObject; initialize. anRGBehaviorStrategy initialize. ^ aBehavior ] { #category : 'accessing' } RGBehavior class >> unnamedWithBehaviorStrategy: anRGBehaviorStrategy [ | aBehavior | aBehavior := self basicNew behaviorStrategy: anRGBehaviorStrategy; initialize. anRGBehaviorStrategy initialize. ^ aBehavior ] { #category : 'accessing' } RGBehavior class >> unresolvedNamed: aName withParent: anRGObject behaviorStrategy: anRGBehaviorStrategy [ | aBehavior | aBehavior := self basicNew behaviorStrategy: anRGBehaviorStrategy; parent: anRGObject; initializeUnresolved. anRGBehaviorStrategy initializeUnresolved. ^ aBehavior pvtName: aName asSymbol; yourself ] { #category : 'accessing' } RGBehavior class >> unresolvedWithBehaviorStrategy: anRGBehaviorStrategy [ | aBehavior | aBehavior := self basicNew behaviorStrategy: anRGBehaviorStrategy; initializeUnresolved. anRGBehaviorStrategy initializeUnresolved. ^ aBehavior ] { #category : 'accessing' } RGBehavior class >> unresolvedWithParent: anRGObject behaviorStrategy: anRGBehaviorStrategy [ | aBehavior | aBehavior := self basicNew behaviorStrategy: anRGBehaviorStrategy; parent: anRGObject; initializeUnresolved. anRGBehaviorStrategy initializeUnresolved. ^ aBehavior ] { #category : 'accessing - backend' } RGBehavior >> addLocalMethod: anRGMethod [ self backend forBehavior addLocalMethod: anRGMethod to: self. self announcer methodAdded: anRGMethod ] { #category : 'accessing - backend' } RGBehavior >> addProtocol: aSymbol [ self announceDefinitionChangeDuring: [ self backend forBehavior addMethodTag: aSymbol to: self ] ] { #category : 'managing container' } RGBehavior >> addoptToParentStub [ self isRingResolved ifFalse: [ ^ self ]. super addoptToParentStub. self parent pvtAddBehavior: self ] { #category : 'queries - other' } RGBehavior >> allInstVarNames [ "Answer an Array of the names of the receiver's instance variables. The Array ordering is the order in which the variables are stored and accessed by the interpreter." | vars | (self superclass == self or: [ self superclass isNil ]) ifTrue: [vars := self instVarNames copy] "Guarantee a copy is answered." ifFalse: [vars := self superclass allInstVarNames , self instVarNames]. ^vars ] { #category : 'announcements' } RGBehavior >> announceDefinitionChangeDuring: aBlock [ | oldVersion | self announcer isSuspended ifTrue: [ aBlock value. ^ self ] . self announcer suspendAllWhile: [ oldVersion := self copyForBehaviorDefinition.]. aBlock value. self announcer behaviorDefinitionChangedFrom: oldVersion to: self. self announcer behaviorModificationAppliedTo: self ] { #category : 'accessing' } RGBehavior >> asYetUnclassifiedProtocolName [ ^ Protocol unclassified ] { #category : 'testing' } RGBehavior >> canMergeWith: anRGObject visited: visitedDefinitions [ | newVisited | (visitedDefinitions includes: self) ifTrue: [ ^ true ]. (self isRingFullyResolved or: [ anRGObject isRingFullyResolved]) ifTrue: [^ true]. (super canMergeWith: anRGObject visited: visitedDefinitions) ifFalse: [ ^ false ]. newVisited := visitedDefinitions copyWith: self. self superclass ~~ self ifTrue: [ (self superclass canMergeWith: anRGObject superclass visited: newVisited) ifFalse: [ ^ false ]]. self metaclass ~~ self ifTrue: [ (self metaclass canMergeWith: anRGObject metaclass visited: newVisited) ifFalse: [ ^ false ]]. ^ true ] { #category : 'accessing - definition' } RGBehavior >> classVariablesBindings [ ^ self propertyNamed: #classVariablesBindings ifAbsentPut: [ IdentityDictionary new.] ] { #category : 'accessing - definition' } RGBehavior >> classVariablesString [ "Answer a string of my class variable names separated by spaces." ^ self behaviorStrategy classVariablesString ] { #category : 'accessing - backend' } RGBehavior >> cleanLocalMethods [ | oldMethods | oldMethods := self localMethods. self backend forBehavior cleanLocalMethodsFor: self. self cleanProtocols. oldMethods do: [ :each | self announcer methodRemoved: each ] ] { #category : 'accessing - backend' } RGBehavior >> cleanProtocols [ self cleanTagsForMethods ] { #category : 'accessing - backend' } RGBehavior >> cleanTags [ self announceDefinitionChangeDuring: [ self cleanTagsWithoutAnnouncemnt ] ] { #category : 'accessing - backend' } RGBehavior >> cleanTagsForMethods [ self backend forPackage cleanTagsForMethodsFor: self ] { #category : 'accessing - backend' } RGBehavior >> cleanTagsWithoutAnnouncemnt [ self backend forBehavior cleanClassTagsFor: self ] { #category : 'accessing' } RGBehavior >> compiler [ ^ self class compiler ] { #category : 'converting' } RGBehavior >> convertToMetaclassTrait [ | metaclassTraitStrategy originalName | (self resolvedProperties includesAnyOf: #(traitComposition)) ifTrue: [self error: 'This class cannot be converted to trait']. "TODO: check empty layout" " newMetaclassTrait := RGMetaclassTrait unresolvedWithParent: self parent. newMetaclassTrait copyPropertiesFrom: self. " metaclassTraitStrategy := RGMetaclassTrait newStrategyFor: self environment. metaclassTraitStrategy owner: self. metaclassTraitStrategy pvtBaseTrait: self behaviorStrategy pvtBaseClass. self behaviorStrategy: metaclassTraitStrategy. originalName := self name. (self hasResolvedName) ifTrue: [ self pvtName: ((self name withoutSuffix: ' class'), ' classTrait') asSymbol ]. self environment ask replaceName: originalName with: self name ] { #category : 'converting' } RGBehavior >> convertToTrait [ | traitStrategy originalName | (self resolvedProperties includesAnyOf: #("superclass" traitComposition classVariables sharedPools)) ifTrue: [self error: 'This class cannot be converted to trait']. "TODO: check empty layout" "newTrait := RGTrait unresolvedWithParent: self parent. newTrait copyPropertiesFrom: self. newTrait pvtName: name. newTrait pvtLocalMethods: localMethods. newTrait pvtTags: tags. newTrait behaviorStrategy pvtComment: self behaviorStrategy comment. newTrait behaviorStrategy pvtPackage: self behaviorStrategy package." originalName := self name. traitStrategy := RGTrait newStrategyFor: self environment. traitStrategy owner: self. traitStrategy pvtClassTrait: self pvtMetaclass. traitStrategy pvtPackage: self behaviorStrategy pvtPackage. traitStrategy pvtComment: self behaviorStrategy pvtComment. self behaviorStrategy: traitStrategy. self environment ask replaceName: originalName with: self name ] { #category : 'copying' } RGBehavior >> copyForBehaviorDefinitionPostCopy [ super copyForBehaviorDefinitionPostCopy. superclass := self superclass shallowCopy. "we need the superclass name" traitComposition := self traitComposition copyForBehaviorDefinition. tagsForMethods := self tagsForMethods copy asSet. tags := self tags copy asSet. behaviorStrategy := behaviorStrategy copyForBehaviorDefinitionWithOwner: self ] { #category : 'default model values' } RGBehavior >> defaultLayout [ ^ self defaultFixedLayoutStubIn: self ] { #category : 'default model values' } RGBehavior >> defaultLocalMethods [ ^ Set new ] { #category : 'managing container' } RGBehavior >> defaultParentStub [ ^ self defaultEnvironmentStub ] { #category : 'default model values' } RGBehavior >> defaultTags [ ^ Set new ] { #category : 'default model values' } RGBehavior >> defaultTagsForMethods [ ^ Set new ] { #category : 'default model values' } RGBehavior >> defaultTraitComposition [ ^ self defaultTraitCompositionStubIn: self ] { #category : 'printing' } RGBehavior >> definitionString [ "Answer a <String> with the receiver's definition accordingly to its strategy" ^ self behaviorStrategy definitionString ] { #category : 'fileout' } RGBehavior >> definitionStringFor: aConfiguredPrinter [ ^ aConfiguredPrinter classDefinitionString ] { #category : 'queries - methods' } RGBehavior >> ensureLocalMethodNamed: aSymbol [ ^ self localMethodNamed: aSymbol ifAbsent: [ | newMethod | newMethod := RGMethod named: aSymbol asSymbol parent: self. self addLocalMethod: newMethod. newMethod] ] { #category : 'queries - tags' } RGBehavior >> ensureMethodTagNamed: aSymbol [ ^ self tagsForMethods detect: [ :each | each asSymbol = aSymbol ] ifNone: [ self addProtocol: aSymbol. aSymbol ] ] { #category : 'queries - protocols' } RGBehavior >> ensureProtocolNamed: aSymbol [ ^ self ensureMethodTagNamed: aSymbol ] { #category : 'queries - methods' } RGBehavior >> ensureUnresolvedLocalMethod [ | newMethod | newMethod := RGMethod parent: self. self addLocalMethod: newMethod. ^ newMethod ] { #category : 'documentation' } RGBehavior >> extensions [ ^ self localMethods select: [ :each | each package ~= self package ] ] { #category : 'testing' } RGBehavior >> hasComment [ ^ self comment isEmptyOrNil not ] { #category : 'queries - testing' } RGBehavior >> hasMethods [ "validates the existance of methods" ^ self methods notEmpty ] { #category : 'testing' } RGBehavior >> hasResolvedSuperclass [ ^ self hasResolved: #superclass ] { #category : 'queries - testing' } RGBehavior >> hasTraitComposition [ ^ self traitComposition transformations isEmpty not ] { #category : 'queries - methods' } RGBehavior >> includesSelector: aString [ "Answer whether the message whose selector is the argument is in the method dictionary of the receiver's class." ^ self selectors includes: aString ] { #category : 'testing - class hierarchy' } RGBehavior >> inheritsFrom: aClass [ "Answer whether the argument, aClass, is on the receiver's superclass chain." | aSuperclass | aSuperclass := self superclass. [ aSuperclass isNil ] whileFalse: [ aSuperclass == aClass ifTrue: [ ^ true ]. aSuperclass hasResolvedName ifFalse: [ ^ false ]. aSuperclass := aSuperclass superclass ]. ^ false ] { #category : 'initialization' } RGBehavior >> initialize [ super initialize. "use unresolved value for superclass to avoid infinite recursion. It needs to be set later" superclass := RGUnresolvedValue recursive. metaclass := RGUnresolvedValue recursive. localMethods := self unresolvedValue: self defaultLocalMethods. traitComposition := self unresolvedValue: self defaultTraitComposition. tagsForMethods := self unresolvedValue: self defaultTagsForMethods. tags := self unresolvedValue: self defaultTags ] { #category : 'initialization' } RGBehavior >> initializeUnresolved [ super initializeUnresolved. superclass := self. "will be set later" metaclass := self. "will be set later" localMethods := self unresolvedValue: self defaultLocalMethods. traitComposition := self unresolvedValue: self defaultTraitComposition. tagsForMethods := self unresolvedValue: self defaultTagsForMethods. tags := self unresolvedValue: self defaultTags ] { #category : 'queries - testing' } RGBehavior >> isAccessedIn: anRGMethod [ ^ (anRGMethod ast variableNodes select: [ :each | each isGlobalVariable ]) anySatisfy: [ :each | each name = self name ] ] { #category : 'testing' } RGBehavior >> isBehavior [ ^ true ] { #category : 'testing - layouts' } RGBehavior >> isBits [ ^ self layout isBitsLayout ] { #category : 'testing - layouts' } RGBehavior >> isBytes [ ^ self layout isByteLayout ] { #category : 'testing - layouts' } RGBehavior >> isCompiledMethod [ ^ self layout isCompiledMethodLayout ] { #category : 'testing - layouts' } RGBehavior >> isDoubleWords [ ^ self layout isDoubleWordLayout ] { #category : 'testing - layouts' } RGBehavior >> isEphemeron [ ^ self layout isEphemeronLayout ] { #category : 'testing - layouts' } RGBehavior >> isEphemeronClass [ ^ self layout isEphemeronLayout ] { #category : 'testing - layouts' } RGBehavior >> isImmediateClass [ ^ self layout isImmediateLayout ] { #category : 'testing' } RGBehavior >> isPointers [ ^ self isBits not ] { #category : 'queries - testing' } RGBehavior >> isRootInEnvironment [ ^ self superclass == self or: [ self superclass isNil ] ] { #category : 'testing' } RGBehavior >> isTaggedWith: aSymbol [ ^self tags includes: aSymbol ] { #category : 'testing - layouts' } RGBehavior >> isVariable [ "is the definition a variable class?" ^ self layout isVariableLayout ] { #category : 'testing' } RGBehavior >> isWeak [ ^ self layout isWeakLayout ] { #category : 'testing - layouts' } RGBehavior >> isWords [ ^ self layout isWordLayout ] { #category : 'queries - methods' } RGBehavior >> localMethodNamed: aSymbol ifAbsent: aBlock [ self localMethodsDo: [ :each | (each name = aSymbol) ifTrue: [^ each]]. ^ aBlock value ] { #category : 'queries - methods' } RGBehavior >> localMethods [ ^ self localMethodsSet asArray ] { #category : 'accessing - backend' } RGBehavior >> localMethodsDo: aBlock [ self backend forBehavior localMethodsFor: self do: aBlock ] { #category : 'queries - methods' } RGBehavior >> localMethodsSet [ | methods | methods := self defaultLocalMethods. self localMethodsDo: [ :each | methods add: each ]. ^ methods ] { #category : 'queries - methods' } RGBehavior >> localSelectors [ ^ self localMethods collect: [ :each | each name ] ] { #category : 'lookup' } RGBehavior >> lookupVar: aName [ ^ self allSlots detect: [ :slot | slot name == aName ] ifNone: [ self bindingOf: aName ] ] { #category : 'resolving' } RGBehavior >> makeResolved [ superclass := self superclass markAsRingResolved. localMethods := self localMethodsSet markAsRingResolved. traitComposition := self traitComposition markAsRingResolved. metaclass := self metaclass markAsRingResolved. tagsForMethods := self tagsForMethodsSet markAsRingResolved. tags := self tagsSet markAsRingResolved. super makeResolved ] { #category : 'accessing - backend' } RGBehavior >> metaclass [ ^ self backend forBehavior metaclassFor: self ] { #category : 'accessing - backend' } RGBehavior >> metaclass: anRGMetaclass [ self backend forBehavior setMetaclassFor: self to: anRGMetaclass ] { #category : 'queries - methods' } RGBehavior >> methodNamed: aSymbol [ | allMethods | allMethods := IdentitySet new. self methods do: [ :each | each name = aSymbol ifTrue: [^ each]]. ^ nil ] { #category : 'queries - methods' } RGBehavior >> methods [ | methodsFromTraits methodsDict | "TODO: make nicer" "^ self propertyNamed: #methods ifAbsentPut: [ " methodsFromTraits := self traitComposition methods collect: [ :each | each copy parent: self ]. methodsDict := Dictionary new. methodsFromTraits do: [ :each | methodsDict at: each name put: each ]. self localMethodsDo: [ :each | methodsDict at: each name put: each ]. ^ methodsDict values asArray"]" ] { #category : 'queries - tags' } RGBehavior >> methodsTaggedWith: aSymbol [ ^ self localMethods select: [ :each | each isTaggedWith: aSymbol ] ] { #category : 'accessing - backend' } RGBehavior >> name: aString [ | oldName subclassesWithOldDefinitions | oldName := self name. subclassesWithOldDefinitions := (self subclasses reject: [:each | each isMeta]) collect: [ :each | each -> each copyForBehaviorDefinition ]. self announceDefinitionChangeDuring: [ super name: aString ]. self announcer behaviorRenamed: self from: oldName. subclassesWithOldDefinitions do: [ :assoc | self announcer behaviorDefinitionChangedFrom: assoc value to: assoc key. self announcer behaviorModificationAppliedTo: assoc key. self announcer behaviorParentRenamed: assoc key from: oldName ] ] { #category : 'testing' } RGBehavior >> needsSlotClassDefinition [ ^ false ] { #category : 'fileout' } RGBehavior >> oldDefinition [ ^ ClassDefinitionPrinter legacy for: self; definitionString ] { #category : 'accessing' } RGBehavior >> packageTag [ ^ self tags ifEmpty: [ nil ] ifNotEmpty: [ :tgs | tgs anyOne ] ] { #category : 'printing' } RGBehavior >> printOn: aStream [ aStream nextPutAll: self name ] { #category : 'queries - protocols' } RGBehavior >> protocols [ | methodTags | methodTags := self tagsForMethods. ^ methodTags ifEmpty: [ self methods ifEmpty: [ OrderedCollection new ] ifNotEmpty: [ OrderedCollection with: self class asYetUnclassifiedProtocolName ]. ] ifNotEmpty: [ methodTags ] ] { #category : 'accessing - model' } RGBehavior >> protocolsForAllMethods [ "I act as #tagsForMethods but I also takes into account methods comming from traits" ^ self methods flatCollect: [ :each | each tags ] as: Set ] { #category : 'private - backend interface' } RGBehavior >> pvtAddLocalMethod: anRGMethod [ self environment verifyOwnership: anRGMethod. localMethods isRingResolved ifFalse: [ self pvtCleanLocalMethods ]. (self hasResolved: #tagsForMethods) ifFalse: [ self pvtCleanTagsForMethods ]. anRGMethod tags do: [ :aTag | self pvtAddMethodTag: aTag ]. localMethods add: anRGMethod ] { #category : 'private - backend access' } RGBehavior >> pvtAddMethodTag: aSymbol [ tagsForMethods isRingResolved ifFalse: [ self pvtCleanTagsForMethods ]. tagsForMethods add: aSymbol ] { #category : 'strategy' } RGBehavior >> pvtAsTrait [ | traitStrategy | (self resolvedProperties includesAnyOf: #("superclass" traitComposition classVariables sharedPools)) ifTrue: [self error: 'This class cannot be converted to trait']. "TODO: check empty layout" "newTrait := RGTrait unresolvedWithParent: self parent. newTrait copyPropertiesFrom: self. newTrait pvtName: name. newTrait pvtLocalMethods: localMethods. newTrait pvtTags: tags. newTrait behaviorStrategy pvtComment: self behaviorStrategy comment. newTrait behaviorStrategy pvtPackage: self behaviorStrategy package." traitStrategy := RGTrait newStrategyFor: self environment. traitStrategy pvtComment: self behaviorStrategy comment. traitStrategy pvtPackage: self behaviorStrategy package. self behaviorStrategy: traitStrategy. ^ self ] { #category : 'private - backend interface' } RGBehavior >> pvtCleanLocalMethods [ localMethods := self defaultLocalMethods ] { #category : 'private - backend access' } RGBehavior >> pvtCleanTags [ tags := self defaultTags. "TODO:Announce if not empty" ] { #category : 'private - backend access' } RGBehavior >> pvtCleanTagsForMethods [ tagsForMethods := self defaultTagsForMethods. "TODO:Announce if not empty" ] { #category : 'private' } RGBehavior >> pvtLocalMethods: aCollection [ "use only for low-level copying" localMethods := aCollection ] { #category : 'private - backend interface' } RGBehavior >> pvtLocalMethodsDo: aBlock [ ^ localMethods value do: aBlock ] { #category : 'private - backend access' } RGBehavior >> pvtMetaclass [ ^ metaclass value ] { #category : 'private - backend access' } RGBehavior >> pvtMetaclass: anRGMetaclass [ self environment verifyOwnership: anRGMetaclass. ^ metaclass := anRGMetaclass ] { #category : 'private - backend interface' } RGBehavior >> pvtRemoveLocalMethod: anRGMethod [ self environment verifyOwnership: anRGMethod. localMethods remove: anRGMethod ] { #category : 'private - backend access' } RGBehavior >> pvtRemoveMethodTag: aSymbol [ tagsForMethods remove: aSymbol. "TODO:Announce" ] { #category : 'private - backend interface' } RGBehavior >> pvtResolvableProperties [ ^ super pvtResolvableProperties, { #superclass -> superclass. #localMethods -> localMethods. #traitComposition -> traitComposition. #metaclass -> metaclass. #tagsForMethods -> tagsForMethods. #tags -> tags. }, self behaviorStrategy pvtResolvableProperties ] { #category : 'private - backend interface' } RGBehavior >> pvtSuperclass [ ^ superclass value ] { #category : 'private - backend interface' } RGBehavior >> pvtSuperclass: anRGBehavior [ anRGBehavior ifNotNil: [ self environment verifyOwnership: anRGBehavior.]. ^ superclass := anRGBehavior ] { #category : 'private - backend access' } RGBehavior >> pvtTagWith: aSymbol [ tags isRingResolved ifFalse: [ self pvtCleanTags ]. tags add: aSymbol ] { #category : 'private - backend access' } RGBehavior >> pvtTags: aCollection [ ^ tags := aCollection ] { #category : 'private - backend access' } RGBehavior >> pvtTagsDo: aBlock [ ^ tags value do: aBlock ] { #category : 'private - backend access' } RGBehavior >> pvtTagsForMethodsDo: aBlock [ ^ tagsForMethods value do: aBlock ] { #category : 'private - backend interface' } RGBehavior >> pvtTraitComposition [ ^ traitComposition value ] { #category : 'private - backend interface' } RGBehavior >> pvtTraitComposition: anRGTraitComposition [ self environment verifyOwnership: anRGTraitComposition. ^ traitComposition := anRGTraitComposition ] { #category : 'private - backend access' } RGBehavior >> pvtUntagFrom: aSymbol [ (tags value includes: aSymbol) ifTrue: [ tags remove: aSymbol ]. "TODO:Announce" ] { #category : 'accessing - backend' } RGBehavior >> removeLocalMethod: anRGMethod [ (anRGMethod package = self package) ifFalse: [ anRGMethod package removeExtensionMethod: anRGMethod ]. self backend forBehavior removeLocalMethod: anRGMethod from: self. self announcer methodRemoved: anRGMethod ] { #category : 'accessing - backend' } RGBehavior >> removeMethodTag: aSymbol [ self backend forPackage removeMethodTag: aSymbol from: self. self localMethodsDo: [ :method | method untagFrom: aSymbol ] ] { #category : 'accessing - backend' } RGBehavior >> removeProtocol: aSymbol [ self removeMethodTag: aSymbol ] { #category : 'queries - methods' } RGBehavior >> selectors [ ^ self methods collect: [ :each | each name ] ] { #category : 'accessing - definition' } RGBehavior >> sharedPoolsDefinitionString [ "Answer a string of my class variable names separated by spaces." ^ String streamContents: [ :str | str nextPutAll: '{ '. self sharedPools do: [ :pool | str nextPut: $#; nextPutAll: pool name ] separatedBy: [ str space; nextPut: $.; space ]. str nextPutAll: '}' ] ] { #category : 'accessing - definition' } RGBehavior >> sharedPoolsString [ "Answer a string of my class variable names separated by spaces." "TODO: check validity" ^String streamContents: [ :stream | self sharedPools do: [ :each | stream nextPutAll: each name] separatedBy: [ stream space ] ] ] { #category : 'printing' } RGBehavior >> slotDefinitionString [ "Answer a string that contains an executable description of my Slots" "^self slots ifNotEmpty: [self slots asString] ifEmpty: ['{}']" ^String streamContents: [ :str | | special | str nextPutAll: '{ '. self slots do: [:slot | str nextPutAll: slot definitionString. special := slot needsFullDefinition] separatedBy: [ str nextPutAll: ' . '. special ifTrue: [ str cr;tab;tab;tab;tab ]]. str nextPutAll: ' }'. ] ] { #category : 'slots' } RGBehavior >> slots [ ^ self layout slots ] { #category : 'slots' } RGBehavior >> slotsNeedFullDefinition [ "return true if we define something else than InstanceVariableSlots" ^self slots anySatisfy: [ :each | each needsFullDefinition ] ] { #category : 'accessing - class hierarchy' } RGBehavior >> subclasses [ | result | result := IdentitySet new. self environment behaviorsDo: [ :each | (each superclass == self) ifTrue: [ result add: each] ]. ^ result asArray ] { #category : 'accessing - backend' } RGBehavior >> superclass [ ^ self backend forBehavior superclassFor: self ] { #category : 'accessing - backend' } RGBehavior >> superclass: anRGBehavior [ self announceDefinitionChangeDuring: [ self backend forBehavior setSuperclassFor: self to: anRGBehavior ] ] { #category : 'accessing - backend' } RGBehavior >> tagWith: aSymbol [ self announceDefinitionChangeDuring: [ self backend forBehavior tagClass: self with: aSymbol. self package addClassTag: aSymbol. ] ] { #category : 'accessing - model' } RGBehavior >> tags [ ^ self tagsSet asArray ] { #category : 'accessing - backend' } RGBehavior >> tagsDo: aBlock [ self backend forBehavior tagsForClass: self do: aBlock ] { #category : 'accessing - model' } RGBehavior >> tagsForMethods [ "Retrieves the traits defined in the receiver" | allTags | allTags := self defaultTagsForMethods. self tagsForMethodsDo: [ :each | allTags add: each]. ^ allTags asArray ] { #category : 'accessing - backend' } RGBehavior >> tagsForMethodsDo: aBlock [ self backend forBehavior tagsForMethodsFor: self do: aBlock ] { #category : 'accessing - model' } RGBehavior >> tagsForMethodsSet [ "Retrieves the traits defined in the receiver" | allTags | allTags := self defaultTagsForMethods. self tagsForMethodsDo: [ :each | allTags add: each]. ^ allTags ] { #category : 'accessing - model' } RGBehavior >> tagsSet [ | allTags | allTags := self defaultTags. self tagsDo: [ :each | allTags add: each]. ^ allTags ] { #category : 'accessing - backend' } RGBehavior >> traitComposition [ ^ self backend forBehavior traitCompositionFor: self ] { #category : 'accessing - backend' } RGBehavior >> traitComposition: anRGTraitComposition [ self announceDefinitionChangeDuring: [ self backend forBehavior setTraitCompositionFor: self to: anRGTraitComposition.] ] { #category : 'accessing - definition' } RGBehavior >> traitCompositionString [ ^ self traitComposition traitCompositionString ] { #category : 'accessing - backend' } RGBehavior >> unresolveName [ | oldName subclassesWithOldDefinitions | oldName := self name. subclassesWithOldDefinitions := (self subclasses reject: [:each | each isMeta]) collect: [ :each | each -> each copyForBehaviorDefinition ]. self announceDefinitionChangeDuring: [ super unresolveName ]. self announcer behaviorRenamed: self from: oldName. subclassesWithOldDefinitions do: [ :assoc | self announcer behaviorDefinitionChangedFrom: assoc value to: assoc key. self announcer behaviorModificationAppliedTo: assoc key. self announcer behaviorParentRenamed: assoc key from: oldName ] ] { #category : 'accessing - backend' } RGBehavior >> unresolveSuperclass [ self announceDefinitionChangeDuring: [ self pvtSuperclass: (RGUnresolvedValue recursive) ] ] { #category : 'accessing - backend' } RGBehavior >> untagFrom: aSymbol [ self backend forPackage untagClass: self from: aSymbol ] { #category : 'accessing' } RGBehavior >> usedTraits [ ^ self traitComposition usedTraits ] { #category : 'accessing' } RGBehavior >> users [ ^ #() ]
0
0.648783
1
0.648783
game-dev
MEDIA
0.423105
game-dev
0.538031
1
0.538031
maksimKorzh/chess_programming
3,408
src/nnue/nnue_setup/nnue/misc.cpp
#include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include "misc.h" FD open_file(const char *name) { #ifndef _WIN32 return open(name, O_RDONLY); #else return CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL); #endif } void close_file(FD fd) { #ifndef _WIN32 close(fd); #else CloseHandle(fd); #endif } size_t file_size(FD fd) { #ifndef _WIN32 struct stat statbuf; fstat(fd, &statbuf); return statbuf.st_size; #else DWORD sizeLow, sizeHigh; sizeLow = GetFileSize(fd, &sizeHigh); return ((uint64_t)sizeHigh << 32) | sizeLow; #endif } const void *map_file(FD fd, map_t *map) { #ifndef _WIN32 *map = file_size(fd); void *data = mmap(NULL, *map, PROT_READ, MAP_SHARED, fd, 0); #ifdef MADV_RANDOM madvise(data, *map, MADV_RANDOM); #endif return data == MAP_FAILED ? NULL : data; #else DWORD sizeLow, sizeHigh; sizeLow = GetFileSize(fd, &sizeHigh); *map = CreateFileMapping(fd, NULL, PAGE_READONLY, sizeHigh, sizeLow, NULL); if (*map == NULL) return NULL; return MapViewOfFile(*map, FILE_MAP_READ, 0, 0, 0); #endif } void unmap_file(const void *data, map_t map) { if (!data) return; #ifndef _WIN32 munmap((void *)data, map); #else UnmapViewOfFile(data); CloseHandle(map); #endif } /* FEN */ static const char piece_name[] = "_KQRBNPkqrbnp_"; static const char rank_name[] = "12345678"; static const char file_name[] = "abcdefgh"; static const char col_name[] = "WwBb"; static const char cas_name[] = "KQkq"; void decode_fen(const char* fen_str, int* player, int* castle, int* fifty, int* move_number, int* piece, int* square) { /*decode fen*/ int sq,index = 2; const char* p = fen_str,*pfen; for(int r = 7;r >= 0; r--) { for(int f = 0;f <= 7;f++) { sq = r * 8 + f; if((pfen = strchr(piece_name,*p)) != 0) { int pc = int(strchr(piece_name,*pfen) - piece_name); if(pc == 1) { piece[0] = pc; square[0] = sq; } else if(pc == 7) { piece[1] = pc; square[1] = sq; } else { piece[index] = pc; square[index] = sq; index++; } } else if((pfen = strchr(rank_name,*p)) != 0) { for(int i = 0;i < pfen - rank_name;i++) { f++; } } p++; } p++; } piece[index] = 0; square[index] = 0; /*player*/ if((pfen = strchr(col_name,*p)) != 0) *player = ((pfen - col_name) >= 2); p++; p++; /*castling rights*/ *castle = 0; if(*p == '-') { p++; } else { while((pfen = strchr(cas_name,*p)) != 0) { *castle |= (1 << (pfen - cas_name)); p++; } } /*epsquare*/ int epsquare; p++; if(*p == '-') { epsquare = 0; p++; } else { epsquare = int(strchr(file_name,*p) - file_name); p++; epsquare += 16 * int(strchr(rank_name,*p) - rank_name); p++; } square[index] = epsquare; /*fifty & hply*/ p++; if(*p && *(p+1) && isdigit(*p) && ( isdigit(*(p+1)) || *(p+1) == ' ' ) ) { sscanf(p,"%d %d",fifty,move_number); if(*move_number <= 0) *move_number = 1; } else { *fifty = 0; *move_number = 1; } }
0
0.958542
1
0.958542
game-dev
MEDIA
0.635695
game-dev
0.987427
1
0.987427
libgdx/gdx-ai
4,145
gdx-ai/src/com/badlogic/gdx/ai/btree/decorator/Random.java
/******************************************************************************* * Copyright 2014 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.ai.btree.decorator; import com.badlogic.gdx.ai.btree.Decorator; import com.badlogic.gdx.ai.btree.Task; import com.badlogic.gdx.ai.btree.annotation.TaskAttribute; import com.badlogic.gdx.ai.btree.annotation.TaskConstraint; import com.badlogic.gdx.ai.btree.leaf.Failure; import com.badlogic.gdx.ai.btree.leaf.Success; import com.badlogic.gdx.ai.utils.random.ConstantFloatDistribution; import com.badlogic.gdx.ai.utils.random.FloatDistribution; import com.badlogic.gdx.math.MathUtils; /** The {@code Random} decorator succeeds with the specified probability, regardless of whether the wrapped task fails or succeeds. * Also, the wrapped task is optional, meaning that this decorator can act like a leaf task. * <p> * Notice that if success probability is 1 this task is equivalent to the decorator {@link AlwaysSucceed} and the leaf * {@link Success}. Similarly if success probability is 0 this task is equivalent to the decorator {@link AlwaysFail} and the leaf * {@link Failure}. * * @param <E> type of the blackboard object that tasks use to read or modify game state * * @author davebaol */ @TaskConstraint(minChildren = 0, maxChildren = 1) public class Random<E> extends Decorator<E> { /** Optional task attribute specifying the random distribution that determines the success probability. It defaults to * {@link ConstantFloatDistribution#ZERO_POINT_FIVE}. */ @TaskAttribute public FloatDistribution success; private float p; /** Creates a {@code Random} decorator with no child that succeeds or fails with equal probability. */ public Random () { this(ConstantFloatDistribution.ZERO_POINT_FIVE); } /** Creates a {@code Random} decorator with the given child that succeeds or fails with equal probability. * * @param task the child task to wrap */ public Random (Task<E> task) { this(ConstantFloatDistribution.ZERO_POINT_FIVE, task); } /** Creates a {@code Random} decorator with no child that succeeds with the specified probability. * * @param success the random distribution that determines success probability */ public Random (FloatDistribution success) { super(); this.success = success; } /** Creates a {@code Random} decorator with the given child that succeeds with the specified probability. * * @param success the random distribution that determines success probability * @param task the child task to wrap */ public Random (FloatDistribution success, Task<E> task) { super(task); this.success = success; } /** Draws a value from the distribution that determines the success probability. * <p> * This method is called when the task is entered. */ @Override public void start () { p = success.nextFloat(); } @Override public void run () { if (child != null) super.run(); else decide(); } @Override public void childFail (Task<E> runningTask) { decide(); } @Override public void childSuccess (Task<E> runningTask) { decide(); } private void decide () { if (MathUtils.random() <= p) success(); else fail(); } @Override protected Task<E> copyTo (Task<E> task) { Random<E> random = (Random<E>)task; random.success = success; // no need to clone since it is immutable return super.copyTo(task); } @Override public void reset() { this.p = 0; this.success = ConstantFloatDistribution.ZERO_POINT_FIVE; super.reset(); } }
0
0.796823
1
0.796823
game-dev
MEDIA
0.808878
game-dev
0.940719
1
0.940719