content
stringlengths
5
1.05M
pg = pg or {} pg.gameset = { version_major = { description = "", key_value = 1 }, version_minor = { description = "", key_value = 1 }, version_build = { description = "", key_value = 0 }, voice_version = { description = "", key_value = 1 }, code_switch = { description = "AF可能缺少淡水", key_value = 0 }, flagship_exp_percent = { description = "", key_value = 150 }, mvp_exp_percent = { description = "", key_value = 200 }, shipyard_capacity = { description = "", key_value = 150 }, equip_capacity = { description = "", key_value = 300 }, dorm_exp_ratio_by_1 = { description = "", key_value = 100 }, dorm_exp_ratio_by_2 = { description = "", key_value = 90 }, dorm_exp_ratio_by_3 = { description = "", key_value = 80 }, dorm_exp_ratio_by_4 = { description = "", key_value = 70 }, dorm_exp_ratio_by_5 = { description = "", key_value = 64 }, dorm_exp_ratio_by_6 = { description = "", key_value = 60 }, dorm_food_ratio_by_1 = { description = "", key_value = 100 }, dorm_food_ratio_by_2 = { description = "", key_value = 180 }, dorm_food_ratio_by_3 = { description = "", key_value = 240 }, dorm_food_ratio_by_4 = { description = "", key_value = 280 }, dorm_food_ratio_by_5 = { description = "", key_value = 320 }, dorm_food_ratio_by_6 = { description = "", key_value = 360 }, dorm_exp_base = { description = "", key_value = 1 }, dorm_exp_ratio_comfort_degree = { description = "", key_value = 100 }, dorm_pop_time = { description = "", key_value = 1800 }, dorm_dorm_pop_rant = { description = "", key_value = 500 }, dorm_dorm_pop_min = { description = "", key_value = 1 }, dorm_dorm_pop_max = { description = "", key_value = 3 }, dorm_intimacy_pop_rant = { description = "", key_value = 500 }, dorm_intimacy_pop_min = { description = "", key_value = 1 }, dorm_intimacy_pop_max = { description = "", key_value = 2 }, dorm_exp_once_limit_base = { description = "", key_value = 50000 }, dorm_exp_once_limit_by_level = { description = "", key_value = 1000 }, exp_admiral_a = { description = "", key_value = 50 }, exp_admiral_b = { description = "", key_value = 25 }, exp_admiral_c = { description = "", key_value = 5 }, task_first_daily_pre_id = { description = "", key_value = 4 }, task_first_weekly_pre_id = { description = "", key_value = 4 }, each_attrib_need_exp = { description = "", key_value = 10 }, strength_cost_gold = { description = "", key_value = 0 }, battle_consume_energy = { description = "", key_value = 2 }, battle_dead_energy = { description = "", key_value = 10 }, same_color_lesson_addition = { description = "", key_value = 50 }, test_ship_config_1 = { description = "", key_value = 100001 }, test_ship_config_2 = { description = "", key_value = 100011 }, test_ship_config_3 = { description = "", key_value = 100021 }, buy_oil_limit = { description = "", key_value = 16 }, equip_select_limit = { description = "", key_value = 40 }, exchange_character_id = { description = "", key_value = 100001 }, first_pay_drop = { key_value = 4000, description = { { 1, 1, 3000 }, { 1, 2, 500 }, { 2, 20001, 3 }, { 2, 15003, 3 } } }, create_guild_cost = { description = "", key_value = 300 }, modify_guild_cost = { description = "", key_value = 100 }, max_oil = { description = "", key_value = 25000 }, max_gold = { description = "", key_value = 600000 }, z_project_award = { key_value = 0, description = { { 3, 24040, 1 } } }, tip_unlock_shipIds = { key_value = 0, description = { { 101081, 103111, 203061, 312011, 402041 } } }, sham_battle_para = { description = "", key_value = 60000 }, bb_front_awards = { key_value = 0, description = { { { 2, 54039, 5 } }, { { 2, 16003, 1 }, { 2, 16023, 1 } }, { { 2, 18002, 1 }, { 2, 18012, 1 } }, { { 1, 6, 100 } }, { { 1, 2, 200 } }, { { 1, 1, 300 } } } }, bobing_memory = { key_value = 0, description = { "ZHONGQIU1", "ZHONGQIU2", "ZHONGQIU3", "ZHONGQIU4", "ZHONGQIU5", "ZHONGQIU6", "", "ZHONGQIU7" } }, level_get_proficency = { description = "", key_value = 100 }, exp_overflow_max = { description = "", key_value = 3000000 }, activity_res_id = { description = "岛风活动PT", key_value = 212 }, chapter_move_speed_1 = { description = "", key_value = 25 }, chapter_move_speed_2 = { description = "", key_value = 36 }, commander_exp_retio = { description = "", key_value = 100 }, elite_quota = { description = "", key_value = 3 }, submarine_move_speed_1 = { description = "", key_value = 10 }, submarine_move_speed_2 = { description = "", key_value = 25 }, submarine_round = { description = "", key_value = 2 }, coloring_story = { key_value = 0, description = { "ANSHAN01", "ANSHAN02", "ANSHAN03", nil, "ANSHAN04", nil, "ANSHAN05" } }, card_pairs_story = { key_value = 0, description = { "ZHONGQIU1", "ZHONGQIU2", "ZHONGQIU3", "ZHONGQIU4", "ZHONGQIU5", "ZHONGQIU6", "ZHONGQIU7", "ANSHAN05" } }, card_pairs_param = { key_value = 0, description = { showingTime = 0.5, aniTime = 0.2, firstShowingTime = 3 } }, extra_attr_level_limit = { description = "", key_value = 100 }, player_name_change_cost = { key_value = 0, description = { 2, 15009, 1 } }, player_name_change_lv_limit = { description = "", key_value = 25 }, player_name_cold_time = { description = "", key_value = 2592000 }, sos_signal_interval = { description = "", key_value = 1800 }, sos_signal_rate = { description = "", key_value = 600 }, sos_signal_max = { description = "", key_value = 16 }, login_extra_voice = { key_value = 0, description = { 40101, 30156, 10701, 30301, 20216, 10124, 40201, 40202, 40203, 20507, 40305, 20102, 30161, 20706, 30162, 20103, 40118, 20121, 10117, 30105 } }, world_starting_story = { key_value = 0, description = { "WORLD100A" } }, world_resetting_stage = { description = "", key_value = 100 }, world_resetting_sairen_chapter = { description = "", key_value = 1 }, world_resetting_story = { key_value = 0, description = { "GWORLDS07" } }, world_default_entrance = { key_value = 0, description = { { 200, 1 }, { 200, 1 } } }, world_currency_initial_num = { description = "", key_value = 2000 }, world_fleet_redeploy_cost = { key_value = 0, description = { 100, 86400 } }, world_guide_enemy_id = { key_value = 0, description = { 314001, 314002 } }, world_move_initial_step = { description = "", key_value = 3 }, world_move_initial_view = { description = "", key_value = 3 }, world_buff_morale = { key_value = 0, description = { 200, 201, 202 } }, world_buff_morale_cost = { key_value = 0, description = { 5, 10, 15 } }, world_mapbuff_list = { key_value = 0, description = { 401, 402, 403 } }, world_mapbuff_tips = { description = "", key_value = 7000 }, world_difficult_value = { key_value = 0, description = { { 0, 0, 0 }, { 10, 10, 10 }, { 20, 20, 20 }, { 40, 40, 40 }, { 60, 60, 60 }, { 90, 90, 90 }, { 120, 120, 120 } } }, world_transfer_eventlist = { key_value = 0, description = { 10110301, 10120301, 10130301, 10140301, 10210301, 10220301, 10230301, 10240301, 10250301, 10310301, 10320301, 10330301, 10340301, 10410301, 10420301, 10430301, 10440301, 10510301, 10520301, 10530301, 10540301, 10610301, 10620301, 10630301, 10640301, 10650301, 10660301, 10710301, 10720301, 10730301, 10810301, 10820301, 10830301, 10840301, 10850301, 10910301, 10920301, 10930301, 10940301, 10950301, 11010301, 11020301, 11030301, 11040301, 11050301, 11060301, 11110301, 11120301, 11130301, 11140301, 11210301, 11220301, 11230301, 11240301, 11310301, 11320301, 11330301, 11340301, 11350301, 11410301, 11420301, 11430301, 11440301, 11510301, 11520301, 11530301, 11540301, 11550301, 11560301, 11570301, 11580301, 11590301 } }, world_transfer_eventstory = { key_value = 0, description = { "W1014" } }, world_target_obtain = { description = "", key_value = 3 }, attr_world_damage_fix = { description = "", key_value = 1000 }, attr_world_value_X1 = { description = "", key_value = 7000 }, attr_world_value_X2 = { description = "", key_value = 13000 }, attr_world_value_Y1 = { description = "", key_value = 7000 }, attr_world_value_Y2 = { description = "", key_value = 13000 }, attr_world_value_Z1 = { description = "", key_value = 10000 }, attr_world_value_Z2 = { description = "", key_value = 10000 }, attr_world_value_H1 = { description = "", key_value = 7000 }, attr_world_value_H2 = { description = "", key_value = 10000 }, world_rank_min = { key_value = 0, description = { 0, 0, 60, 90, 150, 300, 750, 1500, 2400 } }, world_rank_unlocked_expedition = { key_value = 0, description = { 10, 10, 10, 10, 10, 10, 10, 10, 10 } }, world_port_service_1_interval = { key_value = 0, description = { { 50, 0.5 }, { 100, 1 }, { 120, 1.2 }, { 999, 1.5 } } }, world_port_service_1_price = { key_value = 0, description = { { 4000, 400 }, { 7000, 300 }, { 9000, 200 }, { 9500, 100 }, { 10000, 50 } } }, world_port_service_2_interval = { key_value = 0, description = { { 100, 0.5 }, { 999, 1 } } }, world_port_service_2_price = { description = "", key_value = 600 }, world_port_taskmax = { description = "", key_value = 7 }, world_movepower_maxvalue = { description = "", key_value = 200 }, world_cell_cost_movepower = { description = "", key_value = 1 }, world_movepower_recovery_interval = { description = "", key_value = 600 }, world_supply_value = { key_value = 0, description = { { 100 }, { 100 }, { 200 }, { 200 }, { 400 } } }, world_supply_price = { key_value = 0, description = { { 1, 2, 1000 }, { 1, 2, 1000 }, { 1, 2, 2000 }, { 1, 2, 2000 }, { 1, 2, 4000 } } }, world_supply_itemlist = { key_value = 0, description = { 251, 252, 253 } }, world_stage_help = { key_value = 0, description = { { 0, "helpbg/level_ui_help_1" }, { 10, "helpbg/level_ui_help_2" }, { 100, "helpbg/level_ui_help_3" } } }, world_story_special_1 = { key_value = 0, description = { "WNX01" } }, world_story_special_2 = { key_value = 0, description = { "GWORLDS05" } }, world_story_recycle_item = { key_value = 0, description = { "GWORLDS06" } }, world_expedition_level = { key_value = 0, description = { { { 1, 4, 7, 10 }, 0 }, { { 2, 5, 8, 11 }, 2 }, { { 3, 6, 9, 12, 98 }, 4 }, { { 99 }, 8 } } }, world_log_max_count = { description = "", key_value = 100 }, world_infection_level = { key_value = 0, description = { 500, 1000 } }, world_instruction_submarine = { key_value = 0, description = { 40, 3600 } }, world_instruction_detect = { key_value = 0, description = { 10, 1800 } }, world_instruction_supply = { key_value = 0, description = { 20, 1800, 310 } }, world_instruction_maintenance = { key_value = 0, description = { 50, 28800, 310 } }, world_sairen_infection = { key_value = 0, description = { 40, 80 } }, world_sairen_weekly = { key_value = 0, description = { 1, 1 } }, world_sairen_max1 = { description = "", key_value = 1 }, world_sairen_max2 = { description = "", key_value = 3 }, world_sairen_openstage = { description = "", key_value = 100 }, world_death_buff = { description = "", key_value = 1 }, world_death_hpfix = { description = "", key_value = 1000 }, world_resource_max = { description = "", key_value = 1000000 }, world_catsearch_failure = { key_value = 0, description = { "W1251" } }, world_catsearch_raritytip = { key_value = 0, description = { "W1252" } }, world_catsearch_completed = { key_value = 0, description = { "W1253", "W1255" } }, world_catsearch_special = { key_value = 0, description = { "W1254" } }, world_catsearchdrop_show = { key_value = 0, description = { { 12, 2100015, 0 }, { 12, 2115, 0 }, { 12, 2016, 0 }, { 12, 2100014, 0 }, { 12, 2114, 0 }, { 12, 2113, 0 }, { 2, 18126, 0 }, { 12, 2103, 0 }, { 2, 20013, 0 }, { 12, 2015, 0 }, { 12, 2014, 0 }, { 12, 2006, 0 }, { 12, 2005, 0 }, { 2, 18125, 0 }, { 12, 2102, 0 }, { 2, 20012, 0 }, { 12, 101, 0 }, { 12, 2101, 0 }, { 12, 100, 0 }, { 1, 1, 0 } } }, world_catsearch_score = { key_value = 0, description = { 0, 29, 69 } }, world_guide_event = { key_value = 0, description = { { 21030, "WorldG121" }, { 22011, "WorldG123" }, { 4002016, "WorldG110" }, { 4002017, "WorldG110" }, { 4002018, "WorldG110" }, { 4002019, "WorldG110" }, { 4002020, "WorldG110" } } }, world_guide_map_list = { key_value = 0, description = { 200, 201, 202, 400, 401, 500 } }, world_move_buff_desc = { description = "", key_value = 2 }, world_level_correct = { key_value = 0, description = { 1, 1, 0.3, 0.2, 0.5 } }, world_suggest_level = { key_value = 0, description = { 0, 1980, 4400, 12100, 18975, 35640, 51840 } }, world_strength_correct = { description = "", key_value = 333 }, world_movelimit_event = { key_value = 0, description = { 20740, 20745, 21530, 22520 } }, world_quickmode_skiplua = { key_value = 0, description = { "W1000", "W1001", "W1002", "W1003", "W1005", "W1006", "W1007", "W1008", "W1009", "W1010", "W1013", "W1021", "W1024", "W1025", "W1031", "W1032", "W1041", "W1042", "W1100", "W1101", "W1102", "W1103", "W1104", "W1105", "W1110", "W1111", "W1112", "W1113", "W1114", "W1115", "W1116", "W1117", "W1118", "W1120", "W1121", "W1122", "W1123", "W1124", "W1125", "W1126", "W1127", "W1128", "W1130", "W1131", "W1132", "W1133", "W1134", "W1135", "W1136", "W1137", "W1138", "W1141", "W1200", "W1201", "W1202", "W1203", "W2000", "W2001", "W2002", "W2003", "W2004", "W2005", "W2006", "W2007", "W2008", "W2009", "W2010", "W2011", "W2012", "W2012B", "W2014", "W2014B", "W2015", "W2015B", "W2016", "W2016B", "W2017", "W2026", "W2027", "W2028", "W2029", "W2030", "W2031", "W2032", "W2033", "W2034", "W2036", "W2037", "W2100", "W2101", "W2102", "W2103", "W2104", "W2105", "W2106", "W400000", "W400001", "W400002", "W400003", "W400005", "W610000", "W610001", "W610002", "W610003", "W610004", "W610005", "W610006", "W610007", "W610008", "W610010", "W610020", "W610021", "W610100", "W610101", "W610102", "W610200", "W610201", "W610202", "W610203", "W610300", "W610301", "W610305", "W610306", "W612000", "W612001", "W612002", "WTask000C", "WTask010C", "WTask020C", "WTask030C", "WTask040C", "WTask050C", "WTask300C", "WTask310C", "WTask320C", "WTask330C", "WTask340C", "WTask350C", "WTask360C", "WTask370C", "WTask380C", "WTask390C", "WTask0000", "WTask3000", "WTask3200", "WTask3600", "WTask3700", "WTask6100", "W400004" } }, world_sairenbuff_fleeticon = { key_value = 0, description = { 610, 620, 630 } }, commander_exp_a = { description = "", key_value = 7000 }, commander_exp_same_rate = { description = "", key_value = 12000 }, commander_skill_exp = { description = "", key_value = 1 }, commander_ability_reset_coldtime = { description = "", key_value = 86400 }, commander_learn_ability_total = { description = "", key_value = 4 }, commander_learn_ability_own = { description = "", key_value = 2 }, commander_ability_limit = { description = "", key_value = 5 }, commander_capacity = { description = "", key_value = 40 }, commander_form_a = { description = "", key_value = 6 }, commander_form_b = { description = "", key_value = 1500 }, commander_form_c = { description = "", key_value = 250 }, commander_form_n = { description = "", key_value = 1 }, commander_grow_form_a = { description = "", key_value = 24 }, commander_grow_form_b = { description = "", key_value = 304 }, commander_skill_reset_cost = { key_value = 0, description = { { 3000, 5600, 7800, 9600, 11000, 12000 } } }, commander_box_count = { description = "", key_value = 10 }, commander_get_cost = { key_value = 0, description = { { 0, 4999, 1 }, { 1500, 5000, 14 } } }, commander_home_number = { description = "", key_value = 8 }, academy_random_ship_count = { description = "", key_value = 5 }, academy_random_ship_coldtime = { description = "", key_value = 600 }, reactivity_time = { description = "", key_value = 900 }, reactivity_ticket_max = { description = "", key_value = 60 }, reactivity_ticket_daily = { description = "", key_value = 4 }, max_commander_bag = { description = "", key_value = 200 }, commander_rename_open = { description = "", key_value = 1 }, commander_rename_coldtime = { description = "", key_value = 86400 }, big_seven_old_skin_timestamp = { description = "", key_value = 1540396800 }, language_default = { description = "", key_value = 1 }, event_tips = { description = "", key_value = 1 }, air_dominance_level_1 = { description = "", key_value = 10011 }, air_dominance_level_2 = { description = "", key_value = 10012 }, air_dominance_level_3 = { description = "", key_value = 10013 }, air_dominance_level_4 = { description = "", key_value = 10014 }, air_dominance_level_5 = { description = "", key_value = 10015 }, air_dominance_p = { description = "", key_value = 10 }, air_dominance_q = { description = "", key_value = 5 }, air_dominance_s = { description = "", key_value = 6 }, air_dominance_t = { description = "", key_value = 4 }, air_dominance_r = { description = "", key_value = 1 }, air_dominance_a = { description = "", key_value = 8000 }, air_dominance_x = { description = "", key_value = 150 }, air_dominance_y = { description = "", key_value = 450 }, technology_protect_num = { description = "", key_value = 10 }, technology_daily_limit = { description = "", key_value = 3 }, technology_once_limit = { description = "", key_value = 1 }, vote_web_url = { description = "https://www.bilibili.com/blackboard/activity-rqtp2019.html", key_value = 0 }, skin_ticket = { description = "", key_value = 221 }, order_pt_max = { key_value = 0, description = { 1001, 25000 } }, secretary_group_unlock = { key_value = 0, description = { { 304, 2 }, { 604, 3 }, { 904, 4 }, { 1204, 5 } } }, award_ship_limit = { description = "奖励超过20只就不一个一个展示获得界面,直接显示全部获得", key_value = 20 }, night_collection_begin = { description = "", key_value = 21 }, night_collection_end = { description = "", key_value = 3 }, fate_sim_ssr = { description = "", key_value = 165 }, fate_sim_ur = { description = "", key_value = 215 }, technology_catchup_itemid = { key_value = 0, description = { { 20101, 10000 }, { 20102, 10000 } } }, urpt_chapter_max = { key_value = 0, description = { 59010, 4000 } }, doa_fever_count = { description = "", key_value = 4 }, doa_fever_buff = { key_value = 8761, description = { 8765, 8767, 8769 } }, doa_fever_recover = { description = "", key_value = 0 }, doa_fever_strategy = { key_value = 10021, description = { 10031, 10032, 10033 } }, meta_skill_exp_double = { description = "", key_value = 9000 }, meta_skill_exp_max = { description = "", key_value = 30000 }, world_boss_stage = { description = "", key_value = 23 }, joint_boss_oil_consume = { key_value = 0, description = { 0, 40, 20, 20, 10, 10, 10, 10, 5, 5, 5, 5, 5, 5, 5, 5, 1 } }, joint_boss_ap_recove_cnt_pre_day = { description = "", key_value = 3 }, world_boss_resfresh = { description = "", key_value = 5 }, joint_boss_ap_max = { description = "", key_value = 3 }, joint_boss_world_time = { description = "", key_value = 1800 }, joint_boss_bonus_time = { description = "", key_value = 86400 }, joint_boss_fighter_max = { description = "", key_value = 30 }, joint_boss_ticket = { key_value = 0, description = { 100, 100 } }, world_boss_joindamage = { description = "", key_value = 200 }, boss_cnt_limit = { key_value = 0, description = { 30, 10, 10, 10 } }, world_fleet_unlock_level = { key_value = 0, description = { { "fleet_totle_level", 2, 1, 480 } } }, world_metaboss_supportattack = { key_value = 0, description = { 31, 75, 8832 } }, weekly_target = { key_value = 0, description = { 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000 } }, weekly_drop = { key_value = 0, description = { 7400, 7401, 7402, 7403, 7404, 7405, 7406, 7407, 7408, 7409, 7410, 7411, 7412, 7413, 7414, 7415, 7416, 7417, 7418, 7419 } }, weekly_drop_client = { key_value = 0, description = { { { 1, 2, 500 }, { 2, 59900, 15 } }, { { 1, 1, 1000 }, { 2, 54013, 5 } }, { { 2, 20001, 3 }, { 2, 15003, 5 } }, { { 4, 100001, 1 }, { 1, 8, 200 } }, { { 1, 2, 500 }, { 8, 59011, 100 } }, { { 1, 1, 1500 }, { 2, 15001, 5 } }, { { 2, 20001, 3 }, { 2, 15003, 5 } }, { { 1, 2, 500 }, { 2, 50003, 5 } }, { { 4, 100001, 1 }, { 1, 6, 60 } }, { { 1, 1, 1500 }, { 8, 59011, 100 } }, { { 1, 3, 300 }, { 2, 50004, 5 } }, { { 1, 1, 1500 }, { 2, 54013, 5 } }, { { 4, 100001, 1 }, { 2, 54003, 1 } }, { { 1, 1, 2000 }, { 2, 50005, 2 } }, { { 2, 20001, 6 }, { 8, 59011, 200 } }, { { 4, 100011, 1 } }, { { 1, 2, 500 }, { 2, 54033, 2 } }, { { 1, 1, 2000 }, { 2, 20012, 1 } }, { { 1, 2, 500 }, { 2, 54051, 1 } }, { { 1, 1, 2000 }, { 2, 52003, 2 } } } }, weekly_bonus_task = { description = "", key_value = 2 }, daily_task_new = { key_value = 0, description = { 7201, 7202, 7203, 7204, 7205, 7206, 7207, 7208, 7209 } }, main_normal_chapter_list = { description = "[101,102,103,104,201,202,203,204,301,302,303,304,401,402,403,404,501,502,503,504,601,602,603,604,701,702,703,704,801,802,803,804,901,902,903,904,1001,1002,1003,1004,1101,1102,1103,1104,1201,1202,1203,1204,1301,1302,1303,1304]", key_value = 0 }, main_hard_chapter_list = { description = "[10101,10102,10103,10104,10201,10202,10203,10204,10301,10302,10303,10304,10401,10402,10403,10404,10501,10502,10503,10504,10601,10602,10603,10604,10701,10702,10703,10704,10801,10802,10803,10804,10901,10902,10903,10904,11001,11002,11003,11004,11101,11102,11103,11104]", key_value = 0 }, permanent_mark = { description = "20210715", key_value = 0 }, vow_prop_conversion = { key_value = 0, description = { 15006, 15011 } }, blueprint_pursue_discount_ssr = { key_value = 0, description = { { 1, 0 }, { 3, 10 }, { 5, 20 }, { 8, 40 }, { 11, 70 }, { 16, 100 } } }, dayandnight_bgm = { key_value = 4050, description = { { { 0, 5 }, "bg_main_night", "idom-Tender" }, { { 5, 8 }, "bg_main_twilight", "idom-MainBGM" }, { { 8, 16 }, "bg_main_day", "idom-MainBGM" }, { { 16, 19 }, "bg_main_twilight", "idom-MainBGM" }, { { 19, 24 }, "bg_main_night", "idom-Tender" } } } } return
TurretIngredients[WeaponType.ShortRangeMissile] = { {name = "Servo", amount = 15, investable = 10, minimum = 5, weaponStat = "fireRate", investFactor = 1.0, changeType = StatChanges.Percentage}, {name = "Rocket", amount = 5, investable = 6, minimum = 1, weaponStat = "damage", }, {name = "High Pressure Tube", amount = 2, investable = 6, minimum = 1, weaponStat = "reach", investFactor = 0.75 }, {name = "Fuel", amount = 2, investable = 6, minimum = 1, weaponStat = "reach", investFactor = 0.5 }, {name = "Targeting Card", amount = 5, investable = 0, minimum = 0,}, {name = "Steel", amount = 8, investable = 10, minimum = 3,}, {name = "Wire", amount = 5, investable = 10, minimum = 3,}, }
----------------------------------------------------------------------------------- -- File: double-shift.lua -- Author: Joaquín Cuitiño -- Adapted from: https://github.com/jhkuperus/dotfiles/blob/master/hammerspoon/double-shift.lua -- License: MIT ----------------------------------------------------------------------------------- -- Toggles Caps Lock state when double shift is pressed. local eventtap = require("hs.eventtap") local timer = require("hs.timer") local events = eventtap.event.types local module = {} -- What is the maximum number of seconds over which the double-press will be considered a double press module.timeFrame = 0.3 -- Change what this function does to change the behavior under double shift (can be overridden when including this module) module.action = function() -- On double-tap of shift, we are sending CMD-Space to the OS to activate Spotlight (or whatever is on that shortcut) hs.hid.capslock.set(not hs.hid.capslock.get()) end local timeFirstPress, firstDown, secondDown = 0, false, false -- Function to check if the event is "clear" event where no modifier is pressed local noFlags = function(ev) local result = true for k, v in pairs(ev:getFlags()) do if v then result = false break end end return result end -- Function to check if the event is a shift-press only (no other modifiers down) local onlyShift = function(ev) local result = ev:getFlags().shift for k,v in pairs(ev:getFlags()) do if k~="shift" and v then result = false break end end return result end -- The function actually watching events and keeping track of the shift presses module.eventWatcher = eventtap.new({events.flagsChanged, events.keyDown}, function(ev) if (timer.secondsSinceEpoch() - timeFirstPress) > module.timeFrame then timeFirstPress, firstDown, secondDown = 0, false, false end if ev:getType() == events.flagsChanged then if noFlags(ev) and firstDown and secondDown then -- shift up and we've seen two, do action if module.action then module.action() end timeFirstPress, firstDown, secondDown = 0, false, false elseif onlyShift(ev) and not firstDown then -- first shift down, start timer firstDown = true timeFirstPress = timer.secondsSinceEpoch() elseif onlyShift(ev) and firstDown then -- second shift down secondDown = true elseif not noFlags(ev) then -- some other key was pressed in between, cancel timer timeFirstPress, firstDown, secondDown = 0, false, false end else -- some other key (other than modifiers) was pressed, cancel timer timeFirstPress, firstDown, secondDown = 0, false, false end return false end):start() return module
local http = require("http") local plugin = require("plugin") local time = require("time") local plugin_body = [[ local http = require("http_server") local server, err = http.server("127.0.0.1:3113") if err then error(err) end while true do local request, response = server:accept() -- raise internal error if request.request_uri == "/bug" then error("get /bug") end response:code(200) -- write header response:write(request.request_uri) response:done() end ]] local p = plugin.do_string(plugin_body) p:run() time.sleep(1) local client = http.client({timeout=1}) local req, err = http.request("GET", "http://127.0.0.1:3113") if err then error(err) end -- no error request local _, err = client:do_request(req) if err then error(err) end -- stop plugin p:stop() time.sleep(1) if p:error() then error(err) end -- must error request local _, err = client:do_request(req) if (err == nil) then error("must be error") end p:run() time.sleep(1) if p:error() then error( p:error() ) end -- no error request local _, err = client:do_request(req) if err then error(err) end -- raise internal error local req_bug, err = http.request("GET", "http://127.0.0.1:3113/bug") if err then error(err) end local _, err = client:do_request(req_bug) if not(err) then error("must be internal error") end if not(p:error()) then error("must be internal error") end -- test successful start p:stop() time.sleep(1) p:run() time.sleep(1) if p:error() then error( p:error() ) end -- no error request local _, err = client:do_request(req) if err then error(err) end
--- Administration functions. -- -- @module cartridge.admin local errors = require('errors') errors.deprecate( "Module `cartridge.admin` is internal." .. " You should use `require('cartridge').admin_*` functions instead." ) local lua_api_stat = require('cartridge.lua-api.stat') local lua_api_boxinfo = require('cartridge.lua-api.boxinfo') local lua_api_topology = require('cartridge.lua-api.topology') local lua_api_failover = require('cartridge.lua-api.failover') local lua_api_vshard = require('cartridge.lua-api.vshard') local lua_api_deprecated = require('cartridge.lua-api.deprecated') return { get_stat = lua_api_stat.get_stat, get_info = lua_api_boxinfo.get_info, get_self = lua_api_topology.get_self, get_servers = lua_api_topology.get_servers, get_replicasets = lua_api_topology.get_replicasets, get_topology = lua_api_topology.get_topology, edit_topology = lua_api_topology.edit_topology, probe_server = lua_api_topology.probe_server, enable_servers = lua_api_topology.enable_servers, disable_servers = lua_api_topology.disable_servers, get_failover_enabled = lua_api_failover.get_failover_enabled, set_failover_enabled = lua_api_failover.set_failover_enabled, bootstrap_vshard = lua_api_vshard.bootstrap_vshard, edit_replicaset = lua_api_deprecated.edit_replicaset, -- deprecated edit_server = lua_api_deprecated.edit_server, -- deprecated join_server = lua_api_deprecated.join_server, -- deprecated expel_server = lua_api_deprecated.expel_server, -- deprecated }
return {'urn','urne','urnenmuur','urnenveld','urntje','urnen','urnenvelden','urntjes'}
-- local function data(file, tag, names, stripFunc, postFunc) local parser = require "otherData.featParser" local names = { "First Aid Expertise", "Let Me Help You With That", "Poké Ball Crafter", "PokéManiac", "Psionic Sight", "Skill Monkey" } -- local function strip(parser, str) -- local firstFeat = parser.names[1] -- return string.match(str, ".*\r\n(" .. firstFeat .. ".+)Pokémon Raising and Battling Features") -- end return parser("other.txt", "Other", names)
--[[ ceres map header start ]] ceres = ceres or {} ceres.modules = {} ceres.initialized = ceres.initialized or false do function _G.print(...) local args = { ... } local msgs = {} for k, v in pairs(args) do table.insert(msgs, tostring(v)) end local msg = table.concat(msgs, " ") DisplayTimedTextToPlayer(GetLocalPlayer(), 0, 0, 60, msg) end ceres.hooks = ceres.hooks or { ["reload::before"] = {}, ["reload::after"] = {}, } function ceres.hookCall(hookName) for _, callback in ipairs(ceres.hooks[hookName]) do callback() end end function ceres.addHook(hookName, callback) if not ceres.hooks[hookName] then error(("can't register non-existent Ceres hook '%s'"):format(hookName)) end table.insert(ceres.hooks[hookName], ceres.wrapSafeCall(callback)) end function ceres.safeCall(callback, ...) local success, err = pcall(callback, ...) if not success then print("ERROR: " .. err) else return err end end function ceres.wrapSafeCall(callback) return function(...) ceres.safeCall(callback, ...) end end _G.require = function(name, optional) local module = ceres.modules[name] if module ~= nil then if module.initialized then return module.cached else module.initialized = true local compiled, err = load(module.source, "module " .. name) if not compiled then error("failed to compile module " .. name .. ": " .. err) end module.cached = compiled() return module.cached end elseif not optional then error("module not found") end end local mainSuppressed = false local configSuppressed = false function ceres.suppressDefaultMain() mainSuppressed = true end function ceres.suppressDefaultConfig() configSuppressed = true end function ceres.init() if not ceres.initialized then ceres.oldMain = main or function() end ceres.oldConfig = config or function() end local success, err function _G.main() if ceres.modules["init"] and not success then print("|c00ff0000CRITICAL ERROR:|r Init script failed to load:\n") print(err) end if ceres.modules["main"] then ceres.safeCall(require, "main") if not mainSuppressed then ceres.safeCall(ceres.oldMain) end else ceres.safeCall(ceres.oldMain) end ceres.initialized = true end function _G.config() if ceres.modules["config"] then ceres.safeCall(require, "config") if configSuppressed then ceres.safeCall(ceres.oldConfig) end else ceres.safeCall(ceres.oldConfig) end end if ceres.modules["init"] then success, err = pcall(require, "init") end else ceres.hookCall("reload::before") ceres.hooks["reload::before"] = {} ceres.hooks["reload::after"] = {} local success, error = pcall(require, "main") if not success then print("|c00ff0000CRITICAL ERROR:|r Main map script failed to REload:\n") print(tostring(error)) return end ceres.hookCall("reload::after") end end end --[[ ceres map header end ]]
local Widget = require "widgets/widget" local ImageButton = require "widgets/imagebutton" require "os" local RoGUpgrade = Class(Widget, function(self, owner) Widget._ctor(self, "RoGUpgrade") self.owner = owner if PLATFORM ~= "PS4" then self.button = self:AddChild(ImageButton("images/fepanels.xml", "DLCpromo_button.tex", "DLCpromo_button_rollover.tex")) else if APP_REGION == "SCEE" then self.button = self:AddChild(ImageButton("images/fepanels_ps4.xml", "DLCpromo_PS4_button2.tex", "DLCpromo_PS4_button2.tex")) else self.button = self:AddChild(ImageButton("images/fepanels_ps4.xml", "DLCpromo_PS4_button.tex", "DLCpromo_PS4_button.tex")) end end self.button:SetOnClick(self.OnClick) MainMenuStatsAdd("seen_rog_upgrade") SendMainMenuStats() end) local steamlink = "http://store.steampowered.com/app/282470/" local kleilink = "http://bit.ly/buy-rog" local function GetLink() return PLATFORM == "WIN32_STEAM" and steamlink or kleilink end function RoGUpgrade:OnClick() --Set Metric! MainMenuStatsAdd("click_rog_upgrade") SendMainMenuStats() VisitURL(GetLink()) end return RoGUpgrade
--- === PasteRegister === --- --- Allow the saving of the pastebuffer to registers identified by --- letters of the alphabet, and sequently loading it from those --- registers. Registers persist by virtual of being stored in --- hs.settings. local PasteRegister = {} -- Metadata {{{ -- PasteRegister.name="PasteRegister" PasteRegister.version="0.5" PasteRegister.author="Von Welch" PasteRegister.license="Creative Commons Zero v1.0 Universal" PasteRegister.homepage="https://github.com/von/PasteRegister.spoon" -- }}} Metadata -- -- Constants {{{ -- local NoMod = {} local Unbound = nil local NoMsg = nil local NoFunc = nil local Indefinite = "indefinite" -- For alerts -- }}} Constants -- -- Class variables {{{ -- -- The following are used by internal functions -- Key used to store registers in hs.settings -- What we store is a table with registers as keys PasteRegister.settingsKey = "PasteRegisters" -- List of legal registers PasteRegister.legalRegisters = "0123456789abcdefghijklmnopqrstuvwxyz" -- }}} Class variables -- -- PasteRegister:init() {{{ -- --- PasteRegister:init() --- Function --- Initializes a PasteRegister --- --- Parameters: --- * None --- --- Returns: --- * PasteRegister object function PasteRegister:init() self.log = hs.logger.new("PasteRegister") -- Precreate images for chooser -- image code kudos: https://github.com/Hammerspoon/hammerspoon/pull/2062 self.images = {} for register in PasteRegister.legalRegisters:gmatch(".") do self.images[register] = hs.canvas.new{ h = 50, w = 50 }:appendElements{ { type = "rectangle", -- alpha = 0 -> transparent strokeColor = { alpha = 0 }, fillColor = { alpha = 0 }, }, { frame = { h = 50, w = 50, x = 0, y = -6 }, text = hs.styledtext.new(register, { color = { white = 1 }, font = { name = ".AppleSystemUIFont", size = 50 }, paragraphStyle = { alignment = "center" } }), type = "text", } }:imageFromCanvas() end return self end -- }}} PasteRegister:init() -- -- PasteRegister:debug() {{{ -- --- PasteRegister:debug() --- Function --- Enable or disable debugging --- --- Parameters: --- * enable - Boolean indicating whether debugging should be on --- --- Returns: --- * Nothing function PasteRegister:debug() if enable then self.log.setLogLevel('debug') self.log.d("Debugging enabled") else self.log.d("Disabling debugging") self.log.setLogLevel('info') end end -- }}} PasteRegister:debug() -- -- PasteRegister:bindHotKeys() {{{ -- --- PasteRegister:bindHotKeys(table) --- Function --- Accepts a table of key bindings, e.g.: --- --- { --- chooser = {{"cmd", "alt"}, "c"}, --- load = {{"cmd", "alt"}, "l"}, --- paste = {{"cmd", "alt"}, "p"}, --- save = {{"cmd", "alt"}, "s"} --- } --- --- Parameters: --- * table - Table of action to key mappings --- --- Returns: --- * PasteRegister object function PasteRegister:bindHotKeys(table) local spec = { chooser = hs.fnutils.partial(self.chooser, self), load = hs.fnutils.partial(self.queryAndLoadPasteBuffer, self), paste = hs.fnutils.partial(self.queryAndPasteRegister, self), save = hs.fnutils.partial(self.queryAndSavePasteBuffer, self) } hs.spoons.bindHotkeysToSpec(spec, mapping) return s end -- }}} PasteRegister:bindHotKeys() -- -- wrapRegisterFunction() {{{ -- -- wrapRegisterFunction() -- Internal function -- Given a callback that manipulates a register, create a modal that -- allows selection of a register and passes it to the callback. -- -- Parameters: -- * callback - function to call when hotkey pressed -- * msg - String displayed when callback is activated. -- -- Returns: -- * A function to activate the modal. local function wrapRegisterFunction(callback, msg) local modal = hs.hotkey.modal.new(NoMod, Unbound, NoMsg) -- Create bindings for all legal registers -- Since hs.hotkey doesn't pass character to callback, we create a separate -- call back function for each key. -- TODO: Find a way to throw an error for non-legal registers -- Kudos for string iterator: https://stackoverflow.com/a/832414/197789 for c in PasteRegister.legalRegisters:gmatch(".") do local wrappedCallback = function() -- Need to exit modal before callback. If callback is pasting text, -- modal will eat it if still active. modal:exit() callback(c) end modal:bind(NoMod, c, NoMsg, wrappedCallback, NoFunc, NoFunc) end modal:bind(NoMod, "escape", "Canceled", function() modal:exit() end) -- Display message while in modal modal.entered = function() local uuid = hs.alert(msg, Indefinite) modal.exited = function() hs.alert.closeSpecific(uuid) end end return function() modal:enter() end end -- }}} wrapRegisterFunction() -- -- savePasterBuffer() {{{ -- -- savePasterBuffer() -- Internal Function -- Save PasteBuffer to register -- -- Parameters: -- * register: Character identifying register to which to save -- -- Returns: -- * True if the operation succeeded, otherwise false local function savePasteBuffer(register) local data = hs.pasteboard.readAllData() if data then hs.alert.show("Saving paste buffer to register " .. register) local registers = hs.settings.get(PasteRegister.settingsKey) or {} registers[register] = data hs.settings.set(PasteRegister.settingsKey, registers) else hs.alert.show("Paste buffer empty") end return true end -- }}} savePasterBuffer() -- -- PasteRegister:queryAndSavePasteBuffer() {{{ -- --- PasteRegister:queryAndSavePasteBuffer() --- Function --- Ask the user to select a register and save the paste buffer --- to that register. --- --- Parameters: --- * None --- --- Returns: --- * True if the operation succeeded, otherwise false local queryAndSavePasteBuffer = wrapRegisterFunction(savePasteBuffer, "Press key for register to save to") function PasteRegister:queryAndSavePasteBuffer() return queryAndSavePasteBuffer() end -- }}} PasteRegister:queryAndSavePasteBuffer() -- -- loadPasteBuffer() {{{ -- -- loadPasteBuffer() -- Internal Function -- Load PasteBuffer from register -- -- Parameters: -- * register: Character identifying register from which to load -- -- Returns: -- * True if the operation succeeded, otherwise false local function loadPasteBuffer(register) local registers = hs.settings.get(PasteRegister.settingsKey) or {} local contents = registers[register] if contents then hs.alert.show("Loading paste buffer from register " .. register) return hs.pasteboard.writeAllData(nil, contents) else hs.alert.show("Register " .. register .. " empty.") return false end end -- }}} loadPasteBuffer() -- -- PasteRegister:queryAndLoadPasteBuffer() {{{ -- --- PasteRegister:queryAndLoadPasteBuffer() --- Function --- Ask the user to select a register and load the paste buffer --- from that register. --- --- Parameters: --- * None --- --- Returns: --- * True if the operation succeeded, otherwise false local queryAndLoadPasteBuffer = wrapRegisterFunction(loadPasteBuffer, "Press key for register to load") function PasteRegister:queryAndLoadPasteBuffer() return queryAndLoadPasteBuffer() end -- }}} PasteRegister:queryAndLoadPasteBuffer() -- -- pasteRegister() {{{ -- -- PasteRegister.pasteRegister() -- Internal Function -- Paste directly from register without changing default pastebuffer -- -- Parameters: -- * register: Character identifying register from which to load -- -- Returns: -- * Nothing local function pasteRegister(register) -- hs.eventtap.keyStrokes() cannot handle styledtext local registers = hs.settings.get(PasteRegister.settingsKey) or {} local contents = registers[register] if contents then hs.alert.show("Pasting from register " .. register) hs.eventtap.keyStrokes(contents) else hs.alert.show("Register " .. register .. " empty.") end end -- }}} pasteRegister() -- -- PasteRegister.queryAndPasteRegister() {{{ -- --- PasteRegister.queryAndPasteRegister() --- Function --- Ask the user to select a register and then paste that register's --- contents directly (via keyStrokes()) --- --- Parameters: --- * None --- --- Returns: --- * Nothing local queryAndPasteRegister = wrapRegisterFunction(pasteRegister, "Press key for register to paste") function PasteRegister:queryAndPasteRegister() queryAndPasteRegister() end -- }}} PasteRegister:queryAndPasteRegister() -- -- clearRegister() {{{ -- -- PasteRegister.clearRegister() -- Internal Function -- Clear a register. -- -- Parameters: -- * register: Character identifying register to clear -- -- Returns: -- * Nothing local function clearRegister(register) local registers = hs.settings.get(PasteRegister.settingsKey) or {} registers[register] = nil hs.settings.set(PasteRegister.settingsKey, registers) end -- }}} clearRegister() -- -- PasteRegister.queryAndClearRegister() {{{ -- --- PasteRegister.queryAndClearRegister() --- Function --- Ask the user to select a register and then clear it. --- --- Parameters: --- * None --- --- Returns: --- * Nothing local queryAndClearRegister = wrapRegisterFunction(clearRegister, "Press key for register to clear") function PasteRegister:queryAndClearRegister() queryAndClearRegister() end -- }}} PasteRegister:queryAndClearRegister() -- -- PasteRegister:chooser() {{{ -- --- PasteRegister:chooser() --- Function --- Open a hs.chooser instance with registers that have content. --- --- Parameters: --- * None --- --- Returns: --- * Nothing function PasteRegister:chooser() local function chooserCallback(choice) if choice == nil then return end loadPasteBuffer(choice.register) end local registers = hs.settings.get(PasteRegister.settingsKey) or {} local choices = {} for register in PasteRegister.legalRegisters:gmatch(".") do local contents = registers[register] if contents then if type(contents) == "table" then contents = contents["public.utf8-plain-text"] end table.insert(choices, { text = string.format("%.40s", contents), image = self.images[register], register = register }) end end local chooser = hs.chooser.new(chooserCallback) chooser:choices(choices) chooser:show() end -- }}} PasteRegister:chooser() -- return PasteRegister -- vim: foldmethod=marker:
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:25' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_TABBAR_MOVEMENT_TYPES = { PAGE_FORWARD = ZO_PARAMETRIC_MOVEMENT_TYPES.LAST, PAGE_BACK = ZO_PARAMETRIC_MOVEMENT_TYPES.LAST + 1, PAGE_NAVIGATION_FAILED = ZO_PARAMETRIC_MOVEMENT_TYPES.LAST + 2 } ZO_PARAMETRIC_SCROLL_MOVEMENT_SOUNDS = { [ZO_PARAMETRIC_MOVEMENT_TYPES.MOVE_NEXT] = SOUNDS.GAMEPAD_MENU_DOWN, [ZO_PARAMETRIC_MOVEMENT_TYPES.MOVE_PREVIOUS] = SOUNDS.GAMEPAD_MENU_UP, [ZO_PARAMETRIC_MOVEMENT_TYPES.JUMP_NEXT] = SOUNDS.GAMEPAD_MENU_JUMP_DOWN, [ZO_PARAMETRIC_MOVEMENT_TYPES.JUMP_PREVIOUS] = SOUNDS.GAMEPAD_MENU_JUMP_UP, [ZO_TABBAR_MOVEMENT_TYPES.PAGE_FORWARD] = SOUNDS.GAMEPAD_PAGE_FORWARD, [ZO_TABBAR_MOVEMENT_TYPES.PAGE_BACK] = SOUNDS.GAMEPAD_PAGE_BACK, [ZO_TABBAR_MOVEMENT_TYPES.PAGE_NAVIGATION_FAILED] = SOUNDS.GAMEPAD_PAGE_NAVIGATION_FAILED, } local function GamepadParametricScrollListPlaySound(movementType) PlaySound(ZO_PARAMETRIC_SCROLL_MOVEMENT_SOUNDS[movementType]) end -------------------------------------------- -- ZO_GamepadVerticalParametricScrollList -------------------------------------------- ZO_GamepadVerticalParametricScrollList = ZO_ParametricScrollList:Subclass() function ZO_GamepadVerticalParametricScrollList:New(...) local list = ZO_ParametricScrollList.New(self, ...) return list end function ZO_GamepadVerticalParametricScrollList:Initialize(control) ZO_ParametricScrollList.Initialize(self, control, PARAMETRIC_SCROLL_LIST_VERTICAL, ZO_GamepadOnDefaultScrollListActivatedChanged) self:SetHeaderPadding(GAMEPAD_HEADER_DEFAULT_PADDING, GAMEPAD_HEADER_SELECTED_PADDING) self:SetUniversalPostPadding(GAMEPAD_DEFAULT_POST_PADDING) self:SetPlaySoundFunction(GamepadParametricScrollListPlaySound) end -------------------------------------------- -- ZO_GamepadVerticalItemParametricScrollList -------------------------------------------- ZO_GamepadVerticalItemParametricScrollList = ZO_GamepadVerticalParametricScrollList:Subclass() function ZO_GamepadVerticalItemParametricScrollList:New(control) local list = ZO_GamepadVerticalParametricScrollList.New(self, control) list:SetUniversalPostPadding(GAMEPAD_DEFAULT_POST_PADDING) return list end -------------------------------------------- -- ZO_GamepadHorizontalParametricScrollList -------------------------------------------- ZO_GamepadHorizontalParametricScrollList = ZO_ParametricScrollList:Subclass() function ZO_GamepadHorizontalParametricScrollList:New(control, onActivatedChangedFunction, onCommitWithItemsFunction, onClearedFunction) onActivatedChangedFunction = onActivatedChangedFunction or ZO_GamepadOnDefaultScrollListActivatedChanged local list = ZO_ParametricScrollList.New(self, control, PARAMETRIC_SCROLL_LIST_HORIZONTAL, onActivatedChangedFunction, onCommitWithItemsFunction, onClearedFunction) list:SetHeaderPadding(GAMEPAD_HEADER_DEFAULT_PADDING, GAMEPAD_HEADER_SELECTED_PADDING) list:SetPlaySoundFunction(GamepadParametricScrollListPlaySound) return list end -------------------------------------------- -- ZO_GamepadTabBarScrollList -------------------------------------------- ZO_TABBAR_ICON_WIDTH = 50 ZO_TABBAR_ICON_HEIGHT = 50 ZO_GamepadTabBarScrollList = ZO_GamepadHorizontalParametricScrollList:Subclass() function ZO_GamepadTabBarScrollList:New(control, leftIcon, rightIcon, onActivatedChangedFunction, onCommitWithItemsFunction, onClearedFunction) local list = ZO_GamepadHorizontalParametricScrollList.New(self, control, onActivatedChangedFunction, onCommitWithItemsFunction, onClearedFunction) list:EnableAnimation(false) list:SetDirectionalInputEnabled(false) list:SetHideUnselectedControls(true) local function CreateIconTexture(name, parent, keyCode, anchor) local iconTexture = CreateControlFromVirtual(name, parent, "ZO_KeyTexture") iconTexture:SetKeyCode(keyCode) iconTexture:SetDimensions(ZO_TABBAR_ICON_WIDTH, ZO_TABBAR_ICON_HEIGHT) iconTexture:SetAnchor(anchor, control, anchor) return iconTexture end list.leftIcon = leftIcon or CreateButtonIcon("$(parent)LeftIcon", control, KEY_GAMEPAD_LEFT_SHOULDER, LEFT) list.rightIcon = rightIcon or CreateButtonIcon("$(parent)RightIcon", control, KEY_GAMEPAD_RIGHT_SHOULDER, RIGHT) list:SetEntryAnchors({ BOTTOM, BOTTOM }) list:InitializeKeybindStripDescriptors() list.control = control list:SetPlaySoundFunction(GamepadParametricScrollListPlaySound) control:SetHandler("OnEffectivelyHidden", ZO_ConveyorSceneFragment_ResetMovement) return list end function ZO_GamepadTabBarScrollList:Activate() KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptor) ZO_GamepadHorizontalParametricScrollList.Activate(self) end function ZO_GamepadTabBarScrollList:Deactivate() KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptor) ZO_GamepadHorizontalParametricScrollList.Deactivate(self) end function ZO_GamepadTabBarScrollList:InitializeKeybindStripDescriptors() local control = self:GetControl() local debugName = "Gamepad Tab Bar" if control then debugName = debugName .. " " .. control:GetName() end self.keybindStripDescriptor = { { --Ethereal binds show no text, the name field is used to help identify the keybind when debugging. This text does not have to be localized. name = debugName .. " Left Shoulder", keybind = "UI_SHORTCUT_LEFT_SHOULDER", ethereal = true, callback = function() if self.active then self:MovePrevious() end end, }, { --Ethereal binds show no text, the name field is used to help identify the keybind when debugging. This text does not have to be localized. name = debugName .. " Right Shoulder", keybind = "UI_SHORTCUT_RIGHT_SHOULDER", ethereal = true, callback = function() if self.active then self:MoveNext() end end, }, } end function ZO_GamepadTabBarScrollList:Commit(dontReselect) if #self.dataList > 1 then self.leftIcon:SetHidden(false) self.rightIcon:SetHidden(false) else self.leftIcon:SetHidden(true) self.rightIcon:SetHidden(true) end ZO_GamepadHorizontalParametricScrollList.Commit(self, dontReselect) self:RefreshPips() end function ZO_GamepadTabBarScrollList:SetPipsEnabled(enabled, divider) self.pipsEnabled = enabled if not divider then -- There is a default divider in the tabbar control divider = self.control:GetNamedChild("Divider") end if not self.pips and enabled then self.pips = ZO_GamepadPipCreator:New(divider) end self:RefreshPips() end function ZO_GamepadTabBarScrollList:RefreshPips() if not self.pipsEnabled then if self.pips then self.pips:RefreshPips() end return end local selectedIndex = self.targetSelectedIndex or self.selectedIndex local numPips = 0 local selectedPipIndex = 0 for i = 1,#self.dataList do if self.dataList[i].canSelect ~= false then numPips = numPips + 1 local active = (selectedIndex == i) if active then selectedPipIndex = numPips end end end self.pips:RefreshPips(numPips, selectedPipIndex) end function ZO_GamepadTabBarScrollList:SetSelectedIndex(selectedIndex, allowEvenIfDisabled, forceAnimation) ZO_GamepadHorizontalParametricScrollList.SetSelectedIndex(self, selectedIndex, allowEvenIfDisabled, forceAnimation) self:RefreshPips() end function ZO_GamepadTabBarScrollList:MovePrevious(allowWrapping, suppressFailSound) ZO_ConveyorSceneFragment_SetMovingBackward() local succeeded = ZO_ParametricScrollList.MovePrevious(self) if not succeeded and allowWrapping then ZO_ConveyorSceneFragment_SetMovingForward() self:SetLastIndexSelected() --Wrap succeeded = true end if succeeded then self.onPlaySoundFunction(ZO_TABBAR_MOVEMENT_TYPES.PAGE_BACK) elseif not suppressFailSound then self.onPlaySoundFunction(ZO_TABBAR_MOVEMENT_TYPES.PAGE_NAVIGATION_FAILED) end return succeeded end function ZO_GamepadTabBarScrollList:MoveNext(allowWrapping, suppressFailSound) ZO_ConveyorSceneFragment_SetMovingForward() local succeeded = ZO_ParametricScrollList.MoveNext(self) if not succeeded and allowWrapping then ZO_ConveyorSceneFragment_SetMovingBackward() ZO_ParametricScrollList.SetFirstIndexSelected(self) succeeded = true end if succeeded then self.onPlaySoundFunction(ZO_TABBAR_MOVEMENT_TYPES.PAGE_FORWARD) elseif not suppressFailSound then self.onPlaySoundFunction(ZO_TABBAR_MOVEMENT_TYPES.PAGE_NAVIGATION_FAILED) end return succeeded end -------------------------------------------- -- ZO_GamepadVerticalParametricScrollListSubList -------------------------------------------- -- This is a parametric scroll list meant to be embedded as an entry within another parametric scroll list. -- The main purpose of this class is to prevent managers that create a list with these type of entries from --having to handle the logic for switching. local SUB_LIST_CENTER_OFFSET = -70 --for aligning the sublist and the parent list entries ZO_GamepadVerticalParametricScrollListSubList = ZO_GamepadVerticalParametricScrollList:Subclass() function ZO_GamepadVerticalParametricScrollListSubList:New(control, parentList, parentKeybinds, onDataChosen) local manager = ZO_GamepadVerticalParametricScrollList.New(self, control, parentList, parentKeybinds, onDataChosen) return manager end function ZO_GamepadVerticalParametricScrollListSubList:Initialize(control, parentList, parentKeybinds, onDataChosen) ZO_GamepadVerticalParametricScrollList.Initialize(self, control) self.parentList = parentList self.parentKeybinds = parentKeybinds self.onDataChosen = onDataChosen self:InitializeKeybindStrip() self.control:SetHidden(true) self:SetFixedCenterOffset(SUB_LIST_CENTER_OFFSET) end function ZO_GamepadVerticalParametricScrollListSubList:Commit(dontReselect) ZO_ParametricScrollList.Commit(self, dontReselect) --no override in ZO_GamepadVerticalParametricScrollList --The list isn't shown yet, so we need to ensure the default selection is updated self:UpdateAnchors(self.targetSelectedIndex) --Need to do the callback for the default selection self.onDataChosen(self:GetTargetData()) end function ZO_GamepadVerticalParametricScrollListSubList:CancelSelection() --If the list is recommitted while open, the original index may be invalid local indexToReturnTo = zo_clamp(self.indexOnOpen, 1, #self.dataList) self.targetSelectedIndex = indexToReturnTo self:UpdateAnchors(indexToReturnTo) self.onDataChosen(self:GetDataForDataIndex(indexToReturnTo)) end function ZO_GamepadVerticalParametricScrollListSubList:InitializeKeybindStrip() local function OnEntered() self.onDataChosen(self:GetTargetData()) self.didSelectEntry = true self:Deactivate() end local function OnBack() self:Deactivate() end self.keybindStripDescriptor = {} ZO_Gamepad_AddForwardNavigationKeybindDescriptors(self.keybindStripDescriptor, GAME_NAVIGATION_TYPE_BUTTON, OnEntered) ZO_Gamepad_AddBackNavigationKeybindDescriptors(self.keybindStripDescriptor, GAME_NAVIGATION_TYPE_BUTTON, OnBack) ZO_Gamepad_AddListTriggerKeybindDescriptors(self.keybindStripDescriptor, self) end function ZO_GamepadVerticalParametricScrollListSubList:Activate() self.parentList:Deactivate() KEYBIND_STRIP:RemoveKeybindButtonGroup(self.parentKeybinds) ZO_GamepadVerticalParametricScrollList.Activate(self) KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptor) self.control:SetHidden(false) self.indexOnOpen = self.selectedIndex self.didSelectEntry = false end function ZO_GamepadVerticalParametricScrollListSubList:Deactivate() if not self.active then return end if self.active and not self.didSelectEntry then self:CancelSelection() end ZO_GamepadVerticalParametricScrollList.Deactivate(self) KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptor) self.parentList:Activate() KEYBIND_STRIP:AddKeybindButtonGroup(self.parentKeybinds) self.control:SetHidden(true) end
local current_dir = _SCRIPT_DIR function IncludeHelpers() local refcount = IncludePackage("helpers") local _project = project() sysincludedirs(current_dir .. "/include") links("helpers") if refcount == 1 then dofile(current_dir .. "/premake5_create_project.lua") project(_project.name) end end
function Esc.AddBatton( Button ) FalloutTable[#FalloutTable + 1] = Button end function Esc.BaseMenu() if IsValid(Menu) and not Menu.Closed then Menu:SetVisible(false) Menu.Closed = true return elseif IsValid(Menu) and Menu.Closed then Menu:SetVisible(true) Menu.Closed = false return end Menu = vgui.Create("DPanel") Menu:SetSize( ScrW(), ScrH() ) Menu:MakePopup() Menu.Paint = function(self) Esc.Background() TextBlurBig(GetHostName(), 10, ScrH()/2 - 80, FalloutEsc.TextColor, FalloutEsc.ColorBlur, 3) TextBlur(GAMEMODE.Name, 15, ScrH()/2 - 15, FalloutEsc.TextColor, FalloutEsc.ColorBlur, 3) end for k, v in ipairs(FalloutTable) do local Button = vgui.Create("DButton", Menu) Button:SetText( "" ) Button:SetPos(ScrW() - 290, ScrH()/2 - 120 + ((k - 1) * 30)) Button:SetSize( 280, 30 ) Button.Paint = function( self ) DrawBox( 0, 0, Button:GetWide(), Button:GetTall(), self.Hovered and FalloutEsc.HoverBg or Color(0,0,0,0)) surface.SetDrawColor( self.Hovered and FalloutEsc.HoverBorder or Color(0,0,0,0)) Button:DrawOutlinedRect( 0, 0, Button:GetWide(), Button:GetTall()) TextBlur(v.Name, 260, 2.5, FalloutEsc.TextColor, FalloutEsc.ColorBlur, 2) end Button.DoClick = v.Click end end function Esc.ExitMenu() local MenuExit = vgui.Create("DPanel", Menu) MenuExit:SetSize(400, 160) MenuExit:Center() MenuExit:MakePopup() MenuExit.Paint = function(self) DrawBox(0, 0, MenuExit:GetWide(), MenuExit:GetTall(), FalloutEsc.WindowBg) surface.SetDrawColor( Color(255,180,95) ) MenuExit:DrawOutlinedRect( 0, 0, MenuExit:GetWide(), MenuExit:GetTall()) TextBlur("Are you sure you want to quit?", MenuExit:GetWide()/2, 40, FalloutEsc.TextColor, FalloutEsc.ColorBlur, 1) end local ButtonExit = vgui.Create("DButton", MenuExit) ButtonExit:SetText( "" ) ButtonExit:SetSize( 100, 30 ) ButtonExit:SetPos(40,100) ButtonExit.Paint = function(self) DrawBox( 0, 0, ButtonExit:GetWide(), ButtonExit:GetTall(), self.Hovered and FalloutEsc.HoverBg or Color(0,0,0,0)) surface.SetDrawColor( self.Hovered and FalloutEsc.HoverBorder or Color(0,0,0,0) ) ButtonExit:DrawOutlinedRect( 0, 0, ButtonExit:GetWide(), ButtonExit:GetTall()) TextBlur("Exit", 95, 2.5, FalloutEsc.TextColor, FalloutEsc.ColorBlur, 2) end ButtonExit.DoClick = function() RunConsoleCommand("disconnect") end local ButtonClose = vgui.Create("DButton", MenuExit) ButtonClose:SetText( "" ) ButtonClose:SetSize( 100, 30 ) ButtonClose:SetPos(260, 100) ButtonClose.Paint = function(self) DrawBox( 0, 0, ButtonClose:GetWide(), ButtonClose:GetTall(), self.Hovered and FalloutEsc.HoverBg or Color(0,0,0,0)) surface.SetDrawColor( self.Hovered and FalloutEsc.HoverBorder or Color(0,0,0,0) ) ButtonClose:DrawOutlinedRect( 0, 0, ButtonClose:GetWide(), ButtonClose:GetTall()) TextBlur("Cancel", 95, 2.5, FalloutEsc.TextColor, FalloutEsc.ColorBlur, 2) end ButtonClose.DoClick = function() MenuExit:Remove() end end function Esc.ReConMenu() local ReConMenu = vgui.Create("DPanel", Menu) ReConMenu:SetSize(400, 160) ReConMenu:Center() ReConMenu:MakePopup() ReConMenu.Paint = function(self) DrawBox(0, 0, ReConMenu:GetWide(), ReConMenu:GetTall(), FalloutEsc.WindowBg) surface.SetDrawColor( Color(255,180,95) ) ReConMenu:DrawOutlinedRect( 0, 0, ReConMenu:GetWide(), ReConMenu:GetTall()) TextBlur("Are you sure you want to reconnect?", ReConMenu:GetWide()/2, 40, FalloutEsc.TextColor, FalloutEsc.ColorBlur, 1) end local ReConMenuYes = vgui.Create("DButton", ReConMenu) ReConMenuYes:SetText( "" ) ReConMenuYes:SetSize( 100, 30 ) ReConMenuYes:SetPos(40,100) ReConMenuYes.Paint = function(self) DrawBox( 0, 0, ReConMenuYes:GetWide(), ReConMenuYes:GetTall(), self.Hovered and FalloutEsc.HoverBg or Color(0,0,0,0)) surface.SetDrawColor( self.Hovered and FalloutEsc.HoverBorder or Color(0,0,0,0) ) ReConMenuYes:DrawOutlinedRect( 0, 0, ReConMenuYes:GetWide(), ReConMenuYes:GetTall()) TextBlur("Yes", 95, 2.5, FalloutEsc.TextColor, FalloutEsc.ColorBlur, 2) end ReConMenuYes.DoClick = function() RunConsoleCommand("retry") end local ReConMenuClose = vgui.Create("DButton", ReConMenu) ReConMenuClose:SetText( "" ) ReConMenuClose:SetSize( 100, 30 ) ReConMenuClose:SetPos(260, 100) ReConMenuClose.Paint = function(self) DrawBox( 0, 0, ReConMenuClose:GetWide(), ReConMenuClose:GetTall(), self.Hovered and FalloutEsc.HoverBg or Color(0,0,0,0)) surface.SetDrawColor( self.Hovered and FalloutEsc.HoverBorder or Color(0,0,0,0) ) ReConMenuClose:DrawOutlinedRect( 0, 0, ReConMenuClose:GetWide(), ReConMenuClose:GetTall()) TextBlur("Cancel", 95, 2.5, FalloutEsc.TextColor, FalloutEsc.ColorBlur, 2) end ReConMenuClose.DoClick = function() ReConMenu:Remove() end end hook.Add("PreRender", "PreRender", function() if input.IsKeyDown(KEY_ESCAPE) and gui.IsGameUIVisible() then if ValidPanel(Menu) then gui.HideGameUI() Esc.BaseMenu() else gui.HideGameUI() Esc.BaseMenu() end end end)
--- Simple menu to quickly execute common commands. --[[=begin gui/quickcmd ============ A list of commands which you can edit while in-game, and which you can execute quickly and easily. For stuff you use often enough to not want to type it, but not often enough to be bothered to find a free keybinding. =end]] --[[ Copyright (c) 2014, Michon van Dooren All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the {organization} 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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. ]] local gui = require 'gui' local widgets = require 'gui.widgets' local dlg = require 'gui.dialogs' local HOTKEYWIDTH = 7 local COMMANDWIDTH = 28 - HOTKEYWIDTH - 3 local STORAGEKEY = 'quickcmd.command' local HOTKEYS = 'asdfghjklqwertyuiopzxcvbnm' QCMDDialog = defclass(QCMDDialog, gui.FramedScreen) QCMDDialog.focus_path = 'QuickCMDDialog' QCMDDialog.ATTRS { frame_title = 'Quick Command', } function QCMDDialog:init(info) self:addviews{ widgets.Panel{ frame = { t = 0, r = 0, b = 0, l = 0 }, frame_inset = 1, subviews = { widgets.Label{ frame = { t = 0 }, text = { { text = 'Hotkey', width = HOTKEYWIDTH }, ' ', { text = 'Command', width = COMMANDWIDTH }, }, }, widgets.List{ view_id = 'list', frame = { t = 2, b = 3 }, not_found_label = 'Command list is empty.', }, widgets.Label{ frame = { b = 0, h = 2 }, text = { { key = 'CUSTOM_SHIFT_A', text = ': Add command', on_activate = self:callback('onAddCommand') }, ' ', { key = 'CUSTOM_SHIFT_D', text = ': Delete command', on_activate = self:callback('onDelCommand') }, NEWLINE, { key = 'CUSTOM_SHIFT_E', text = ': Edit command', on_activate = self:callback('onEditCommand') }, ' ', }, } }, }, } self:updateList() end function QCMDDialog:updateList() -- Get the stored commands. local entries = dfhack.persistent.get_all(STORAGEKEY) or {} -- Build the list entries. self.commands = {} for i, entry in ipairs(entries) do -- Get the hotkey for this entry. local hotkey = nil if i <= HOTKEYS:len() then hotkey = HOTKEYS:sub(i, i) end -- Store the entry. table.insert(self.commands, { text = { { text = hotkey or '', width = HOTKEYWIDTH }, ' ', { text = entry.value, width = COMMANDWIDTH }, }, entry = entry, command = entry.value, hotkey = 'CUSTOM_' .. hotkey:upper(), }) end self.subviews.list:setChoices(self.commands); end function QCMDDialog:getWantedFrameSize(rect) return 40, 28 end function QCMDDialog:onInput(keys) if keys.LEAVESCREEN then self:dismiss() else -- If the pressed key is a hotkey, perform that command and close. for _, command in pairs(self.commands) do if keys[command.hotkey] then dfhack.run_command(command.command) self:dismiss() return end end -- Else, let the parent handle it. QCMDDialog.super.onInput(self, keys) end end function QCMDDialog:onAddCommand() dlg.showInputPrompt( 'Add command', 'Enter new command:', COLOR_GREEN, '', function(command) dfhack.persistent.save({ key = STORAGEKEY, value = command }, true) self:updateList() end ) end function QCMDDialog:onDelCommand() -- Get the selected command. local index, item = self.subviews.list:getSelected() if not item then return end -- Prompt for confirmation. dlg.showYesNoPrompt( 'Delete command', 'Are you sure you want to delete this command: ' .. NEWLINE .. item.entry.value, COLOR_GREEN, function() item.entry:delete() self:updateList() end ) end function QCMDDialog:onEditCommand() -- Get the selected command. local index, item = self.subviews.list:getSelected() if not item then return end -- Prompt for new value. dlg.showInputPrompt( 'Edit command', 'Enter command:', COLOR_GREEN, item.entry.value, function(command) item.entry.value = command item.entry:save() self:updateList() end ) end local screen = QCMDDialog{} screen:show()
--Child Folders includeFile("tangible/storyteller/prop/serverobjects.lua") -- Server Objects
describe('input', function() local Input = require 'input' Input.bind_callbacks() local setTime = love.timer.setTime local nextFrame = function(ts) setTime(ts) love.draw() end local newJoystick = function(id) return { id = id, getID = function(self) return self.id end } end before_each(function() setTime(0) Input.init_state() end) describe('down, pressed, released', function() it('down should return state with data and duration', function() love.keypressed('a') love.mousepressed(1, 2, 1) local js = newJoystick(1) love.gamepadpressed(js, 'a') love.gamepadaxis(js, 'leftx', 0.5) love.gamepadaxis(js, 'lefty', 0.01) assert.is_same({ Input.down('a') }, { true, nil, 0 }) assert.is_same({ Input.pressed('a') }, { true, nil, nil }) assert.is_same({ Input.released('a') }, { false, nil, nil }) assert.is_same({ Input.down('fdown') }, { true, nil, 0 }) assert.is_same({ Input.down('leftx') }, { true, 0.5, 0 }) assert.is_same({ Input.down('lefty') }, { false, nil, nil }) assert.is_same({ Input.down('mouse1') }, { true, { x = 1, y = 2 }, 0 }) love.gamepadreleased(js, 'a') setTime(1.5) assert.is_same({ Input.down('a') }, { true, nil, 0 }) assert.is_same({ Input.down('mouse1') }, { true, { x = 1, y = 2 }, 0 }) assert.is_same({ Input.down('fdown') }, { false, nil, nil }) assert.is_same({ Input.pressed('fdown') }, { false, nil, nil }) assert.is_same({ Input.down('leftx') }, { true, 0.5, 0 }) assert.is_same({ Input.down('lefty') }, { false, nil, nil }) love.draw() love.gamepadpressed(js, 'a') assert.is_same({ Input.down('a') }, { true, nil, 1.5 }) assert.is_same({ Input.pressed('a') }, { false, nil, nil }) assert.is_same({ Input.released('a') }, { false, nil, nil }) assert.is_same({ Input.down('mouse1') }, { true, { x = 1, y = 2 }, 1.5 }) assert.is_same({ Input.down('fdown') }, { true, nil, 0 }) assert.is_same({ Input.pressed('fdown') }, { true, nil, 1.5 }) assert.is_same({ Input.down('leftx') }, { true, 0.5, 1.5 }) assert.is_same({ Input.down('lefty') }, { false, nil, nil }) love.keyreleased('a') love.gamepadaxis(js, 'lefty', 0.1) assert.is_same({ Input.down('a') }, { false }) assert.is_same({ Input.pressed('a') }, { false, nil, nil }) assert.is_same({ Input.released('a') }, { true, nil, 1.5 }) assert.is_same({ Input.down('mouse1') }, { true, { x = 1, y = 2 }, 1.5 }) assert.is_same({ Input.down('fdown') }, { true, nil, 0 }) assert.is_same({ Input.down('leftx') }, { true, 0.5, 1.5 }) assert.is_same({ Input.down('lefty') }, { true, 0.1, 0 }) setTime(2.1) love.gamepadaxis(js, 'lefty', 0.09) love.draw() assert.is_same({ Input.down('a') }, { false }) assert.is_same({ Input.pressed('a') }, { false, nil, nil }) assert.is_same({ Input.released('a') }, { false, nil, nil }) assert.is_same({ Input.down('mouse1') }, { true, { x = 1, y = 2 }, 2.1 }) assert.is_same({ Input.down('fdown') }, { true, nil, 2.1 - 1.5 }) assert.is_same({ Input.down('leftx') }, { true, 0.5, 2.1 }) assert.is_same({ Input.down('lefty') }, { false, nil, nil }) end) it('should check delay and interval for down', function() love.keypressed('a') assert.is_same({ Input.down('a', 0, 0.1) }, { true, nil, 0 }) assert.is_same({ Input.down('a', 0.1, 0.1) }, { false, nil, nil }) assert.is_same({ Input.down('a', 0, 0) }, { true, nil, 0 }) nextFrame(0.05) assert.is_same({ Input.down('a', 0, 0.1) }, { false, nil, nil }) assert.is_same({ Input.down('a', 0.05, 0.1) }, { true, nil, 0.05 }) assert.is_same({ Input.down('a', 0, 0) }, { true, nil, 0.05 }) nextFrame(0.1) assert.is_same({ Input.down('a', 0, 0.1) }, { true, nil, 0.1 }) assert.is_same({ Input.down('a', 0, 0) }, { true, nil, 0.1 }) nextFrame(0.25) assert.is_same({ Input.down('a', 0, 0.1) }, { true, nil, 0.25 }) assert.is_same({ Input.down('a', 0.05, 0.1) }, { true, nil, 0.25 }) assert.is_same({ Input.down('a', 0, 0) }, { true, nil, 0.25 }) nextFrame(0.29) assert.is_same({ Input.down('a', 0, 0.1) }, { false, nil, nil }) assert.is_same({ Input.down('a', 0.05, 0.1) }, { false, nil, nil }) nextFrame(0.301) assert.is_same({ Input.down('a', 0, 0.1) }, { true, nil, 0.301 }) assert.is_same({ Input.down('a', 0.05, 0.1) }, { false, nil, nil }) assert.is_same({ Input.down('a', 0.301) }, { true, nil, 0.301 }) end) it('pressed and released should return data and duration of previous state', function() love.keypressed('a') love.keypressed('b') love.keyreleased('b') -- for empty previous state assert.is_same({ Input.pressed('a') }, { true, nil, nil }) assert.is_same({ Input.released('a') }, { false, nil, nil }) assert.is_same({ Input.pressed('b') }, { false, nil, nil }) assert.is_same({ Input.released('b') }, { true, nil, 0 }) nextFrame(0.1) love.keyreleased('a') love.keypressed('b') assert.is_same({ Input.pressed('a') }, { false, nil, nil }) assert.is_same({ Input.released('a') }, { true, nil, 0.1 }) assert.is_same({ Input.pressed('b') }, { true, nil, 0.1 }) assert.is_same({ Input.released('b') }, { false, nil, nil }) end) end) describe('multidown', function() it('should return key data and duration', function() love.keypressed('a') love.keypressed('b') assert.is_same({ Input.multidown({ 'a', 'b' }) }, { true, nil, 0 }) assert.is_same({ Input.multidown({ 'b', 'a' }) }, { true, nil, 0 }) nextFrame(0.1) love.keypressed('c') love.keypressed('d') love.keyreleased('a') assert.is_same({ Input.multidown({ 'a', 'b' }) }, { false, nil, nil }) assert.is_same({ Input.multidown({ 'b', 'a' }) }, { false, nil, nil }) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }) }, { true, nil, 0 }) end) it('should return key data and duration with delay and interval', function() love.keypressed('a') love.keypressed('b') assert.is_same({ Input.multidown({ 'a', 'b' }, 0, 0.1) }, { true, nil, 0 }) nextFrame(0.1) love.keypressed('c') love.keypressed('d') love.wheelmoved(0, 2) love.keyreleased('a') assert.is_same({ Input.multidown({ 'a', 'b' }, 0, 0.1) }, { false, nil, nil }) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0, 0.1) }, { true, nil, 0 }) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0.05, 0.1) }, { false, nil, nil }) assert.is_same({ Input.multidown({ 'c', 'b', 'd', 'wheely' }) }, { true, 2, 0 }) nextFrame(0.151) assert.is_same({ Input.multidown({ 'a', 'b' }, 0, 0.1) }, { false, nil, nil }) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0, 0.1) }, { false, nil, nil }) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0.05, 0.1) }, { true, nil, 0.151 - 0.1 }) nextFrame(0.2) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0, 0.1) }, { true, nil, 0.1 }) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0.05, 0.1) }, { false, nil, nil }) nextFrame(0.22) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0, 0.1) }, { false, nil, nil }) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0.05, 0.1) }, { false, nil, nil }) nextFrame(0.251) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0, 0.1) }, { false, nil, nil }) assert.is_same({ Input.multidown({ 'c', 'b', 'd' }, 0.05, 0.1) }, { true, nil, 0.251 - 0.1 }) end) end) describe('sequence', function() it('should return state ', function() love.keypressed('a') love.keypressed('b') love.keypressed('c') nextFrame(0.15) love.keypressed('d') assert.is_same({ Input.sequence({ 'a', 'b', 'c' }) }, { false, nil }) assert.is_same({ Input.sequence({ 'a', 'b', 'c', 'd' }) }, { true, nil }) assert.is_same({ Input.sequence({ 'b', 'c', 'd' }) }, { true, nil }) assert.is_same({ Input.sequence({ 'c', 'd' }) }, { true, nil }) assert.is_same({ Input.sequence({ 'd' }) }, { true, nil }) end) it('should check key with down interval', function() love.keypressed('a') love.keypressed('b') assert.is_same({ Input.sequence({ 'a', 'b' }) }, { true, nil }) assert.is_same({ Input.sequence({ 'a', 'b' }, 0.1) }, { false, nil }) assert.is_same({ Input.sequence({ 'b', 'c', 'xxx' }) }, { false, nil }) nextFrame(0.15) love.keypressed('c') assert.is_same({ Input.sequence({ 'a', 'b', 'c' }, 0, 0.1) }, { false, nil }) assert.is_same({ Input.sequence({ 'a', 'b', 'c' }, 0.05, 0.2) }, { false, nil }) assert.is_same({ Input.sequence({ 'a', 'b', 'c' }, 0.2, 0.3) }, { false, nil }) assert.is_same({ Input.sequence({ 'b', 'c' }, 0, 0.1) }, { false, nil }) assert.is_same({ Input.sequence({ 'b', 'c' }, 0.05, 0.2) }, { true, nil }) end) end) describe('duration', function() it('should return action duration', function() love.keypressed('a') assert.is_equal(Input.duration('a'), 0) assert.is_equal(Input.duration('xxx'), nil) nextFrame(1) assert.is_equal(Input.duration('a'), 1) assert.is_equal(Input.duration('a', true), 1) setTime(1.5) assert.is_equal(Input.duration('a'), 1) assert.is_equal(Input.duration('a', true), 1.5) end) end) describe('get_data', function() it('should return action duration', function() love.wheelmoved(1, 2) assert.is_equal(Input.get_data('a'), nil) assert.is_equal(Input.get_data('wheelx'), 1) assert.is_equal(Input.get_data('wheely'), 2) nextFrame(1) love.wheelmoved(3, 0) assert.is_equal(Input.get_data('wheelx'), 3) assert.is_equal(Input.get_data('wheely'), nil) nextFrame(2) assert.is_equal(Input.get_data('wheelx'), nil) assert.is_equal(Input.get_data('wheely'), nil) end) end) describe('get_history', function() it('should return pressed keys', function() local keys = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', '1', '2', '3', '4', '5' } local ts = 0 for i, k in ipairs(keys) do love.keypressed(k) ts = ts + i setTime(ts) love.keyreleased(k) end setTime(ts + 1) love.gamepadpressed('js', 'a') setTime(ts + 2) love.gamepadaxis('js', 'triggerleft', 1) assert.is_same(Input.get_history(3), { { key = 'l2', interval = 1 }, { key = 'fdown', interval = 13 }, { key = '5', interval = 11 } }) assert.is_same(#Input.get_history(20), 10) end) end) describe('get_down_keys', function() it('should return all down keys', function() local keys = { 'a', 'b', 'c', '1', '2', '3' } local ts = 0 for i, k in ipairs(keys) do love.keypressed(k) ts = ts + i setTime(ts) if i % 2 == 0 then love.keyreleased(k) end end setTime(ts + 1) love.gamepadpressed('js', 'a') setTime(ts + 2) love.gamepadaxis('js', 'triggerleft', 1) local dkeys = Input.get_down_keys() table.sort(dkeys) assert.is_same(dkeys, { '2', 'a', 'c', 'fdown', 'l2' }) end) end) describe('misc', function() it('should ignore key for sequence if a key in except list', function() Input.sequence_except_keys['a'] = true love.keypressed('a') assert.is_same({ Input.down('a') }, { true, nil, 0 }) -- cannot check a key that is excepted assert.is_same({ Input.sequence({ 'a' }) }, { false, nil, nil }) assert.is_same(Input.get_history(), {}) end) it('should add id to gamepad keys if Input.multiple_gamepad is true', function() local js1 = newJoystick('a') local js2 = newJoystick('b') local js3 = newJoystick('c') love.gamepadpressed(js1, 'a') Input.multiple_gamepad = true love.gamepadpressed(js1, 'a') love.gamepadpressed(js2, 'a') love.gamepadpressed(js2, 'b') love.gamepadaxis(js3, 'leftx', -0.5) local dkeys = Input.get_down_keys() table.sort(dkeys) assert.is_same(dkeys, { 'fdown', 'fdown:1', 'fdown:2', 'fright:2', 'leftx:3' }) end) end) end)
local gen_code = require("Q/UTILS/lua/gen_code") local operators = { 'cum_cnt' } local val_qtypes = { 'I1', 'I2', 'I4', 'I8', 'F4', 'F8' } local cnt_qtypes = { 'I1', 'I2', 'I4', 'I8' } local num_produced = 0 for i, operator in ipairs(operators) do local fn_name = operator .. "_specialize" local sp_fn = assert(require(fn_name)) for i, val_qtype in ipairs(val_qtypes) do for j, cnt_qtype in ipairs(cnt_qtypes) do local optargs = {}; optargs.cnt_qtype = cnt_qtype status, subs = pcall(sp_fn, val_qtype, nil, optargs) if ( status ) then assert(type(subs) == "table") gen_code.doth(subs, subs.incdir) gen_code.dotc(subs, subs.srcdir) print("Produced ", subs.fn) num_produced = num_produced + 1 else print(subs) print(operator) print(fldtype) error("premature") end end end end assert(num_produced > 0)
-- Compiled with roblox-ts v1.0.0-beta.8 local function makeHello(name) return "Hello from " .. name .. "!" end return { makeHello = makeHello, }
-- Path of Building -- -- Class: Search Host -- Search host -- local SearchHostClass = newClass("SearchHost", function(self, listAccessor, valueAccessor) self.searchListAccessor = listAccessor self.valueAccessor = valueAccessor self.searchTerm = "" self.searchInfos = {} end) local function splitWords(s) local words = {} for word in s:gmatch("%S+") do table.insert(words, word) end return words end local function letterToCaselessPattern(c) return string.format("[%s%s]", string.lower(c), string.upper(c)) end local function wordsToCaselessPatterns(words) local patterns = {} for idx = 1, #words do -- escape all non alphanumeric chars patterns[idx] = string.gsub(words[idx], "%W", "%%%1") -- make pattern case insensitive patterns[idx] = string.gsub(patterns[idx], "%a", letterToCaselessPattern) end return patterns end local function matchWords(searchWords, entry, valueAccessor) local value = valueAccessor and valueAccessor(entry) or entry local searchInfo = { ranges = {}, matches = true } local lastMatchEnd = 0 for _, word in ipairs(searchWords) do local from, to = string.find(value, word, lastMatchEnd + 1) if (from) then local range = { from = from, to = to } table.insert(searchInfo.ranges, range) lastMatchEnd = to else -- at least one search word did not match at least once (respecting order) searchInfo.matches = false end end return searchInfo end local function matchTerm(searchTerm, list, valueAccessor) if not searchTerm or searchTerm == "" or not list then return {} end local searchInfos = {} local searchPatterns = wordsToCaselessPatterns(splitWords(searchTerm)) for idx, entry in ipairs(list) do searchInfos[idx] = matchWords(searchPatterns, entry, valueAccessor) end return searchInfos end function SearchHostClass:IsSearchActive() return self.searchTerm and self.searchTerm ~= "" end function SearchHostClass:OnSearchChar(char) if char:match("%s") then -- dont allow space char if search is empty or last character is already a space char if self.searchTerm == "" or self.searchTerm:sub(-1):match("%s") then return self end end if not char:match("%c") then self.searchTerm = self.searchTerm .. char self:UpdateSearch() end return self end function SearchHostClass:OnSearchKeyDown(key) if self:IsSearchActive() and key == "ESCAPE" then self:ResetSearch() return self elseif self:IsSearchActive() and key == "BACK" then self.searchTerm = self.searchTerm:sub(1, -2) self:UpdateSearch() return self end end function SearchHostClass:UpdateMatchCount() local matchCount = 0 for _, info in ipairs(self.searchInfos) do if (info and info.matches) then matchCount = matchCount + 1 end end self.matchCount = matchCount end function SearchHostClass:GetMatchCount() return self.matchCount end function SearchHostClass:UpdateSearch() if self.searchListAccessor then self.searchInfos = matchTerm(self.searchTerm, self.searchListAccessor(), self.valueAccessor) self:UpdateMatchCount() end end function SearchHostClass:ResetSearch() self.searchTerm = "" self.matchCount = 0 self.searchInfos = {} end function SearchHostClass:GetSearchTermPretty() local color = self:IsSearchActive() and self.matchCount > 0 and "^xFFFFFF" or "^xFF0000" return color .. self.searchTerm end
---------------------------------------- -- Sassilization -- http://sassilization.com -- By Sassafrass / Spacetech / LuaPineapple ---------------------------------------- assert( unit ) local nw_manager = {} unit.NW_Manager = nw_manager nw_manager.NWEnts = {} nw_manager.NWEntCount = 0 function nw_manager:RegisterUnit( Unit ) for _, NWEnt in ipairs( self.NWEnts ) do if( NWEnt.UnitCount < 4 ) then NWEnt:AddUnit( Unit ) return end end self:CreateNWEnt():AddUnit( Unit ) end function nw_manager:CreateNWEnt() Msg( "NWManager: Creating new NW Ent\n" ) local NWEnt = ents.Create( "unit_nw_entity" ) NWEnt:Spawn() NWEnt:Activate() self.NWEnts[ self.NWEntCount + 1 ] = NWEnt self.NWEntCount = self.NWEntCount + 1 return NWEnt end
Class = require "lib.hump.class" Enemy = require "game.enemy" vector = require "lib.hump.vector" Timer = require "lib.hump.timer" Spark = require "game.projectiles.spark" Gamestate = require "lib.hump.gamestate" Fatso = Class{__includes = Enemy, init = function(self, x, y) Enemy.init(self, x, y) self.health = 140 self.l = x - 12 self.t = y - 14 self.w = 24 self.h = 28 self.hover = false self.wakeRange = 240 self.moveSpeed = 10 end, image = love.graphics.newImage("data/img/enemies/fatso/fatso.png") } function Fatso:update(dt) Enemy.update(self, dt) end function Fatso:findPlayer() self.desiredLocation = self:getPlayer().position end function Fatso:attackPlayer() local toPlayer = self:getPlayer().position - self.position local aimVector = toPlayer:normalized() local state = Gamestate:current() for i = -60, 60, 30 do local fragmentAimVector = aimVector:rotated(math.rad(i)) local projectileVelocity = fragmentAimVector * 140 local projectile = Spark( self.position.x + (aimVector.x * 10), self.position.y + (aimVector.y * 10), projectileVelocity.x + math.random(-15, 15), projectileVelocity.y + math.random(-15, 15) ) state:addEntity(projectile) end end function Fatso:onWake() Enemy.onWake(self) self.desiredLocation = self:getPlayer().position self.timer:addPeriodic(0.5 + (math.random(0, 5) / 10), function() self:findPlayer() end) self.timer:addPeriodic(math.random(8, 12) / 10, function() self:attackPlayer() end) end function Fatso:onDestroy() state = Gamestate:current() state.player:takeXP(500) for i = 0, math.random(10, 30), 1 do state:addParticle( SimpleParticle( self.position.x + math.random(-16, 16), -- x self.position.y + math.random(-16, 16), -- y math.random(4, 8), -- size math.random(-100, 100), -- dx math.random(-100, 100), -- dy 160, -- red 20, -- green 20, -- blue 160, -- alpha 200 -- decay ) ) end self.timer:clear() Enemy.destroy(self) end function Fatso:draw() local x,y = self.position:unpack() love.graphics.setColor(255, 255, 255) self.image:setFilter("nearest", "nearest") love.graphics.draw(self.image, x-16, y-16) Entity.draw(self) end return Fatso
-- pass in something like -- -- build_rows([[1, 2, 0, 2], [1, 1, 1, 1]]) -- -- to create rows: start with the bottom row -- 1 = red, 2 = green, 3 = blue, 4 = grey, 0 = nothing function build_rows (rows) local cells = game.state.board.cells for i = 1, #rows, 1 do local y = game.height - #rows + i for j = 1, #(rows[i]), 1 do local x = j local color = rows[i][j] if color ~= 0 then cells[y][x] = build_block({ x = x, y = y, color = color }) end end end end function row_matches(row, blocks) print("--> assert", "row " .. row .. " matches " .. inspect(blocks)) local cells = game.state.board.cells for i = 1, #blocks, 1 do local block = blocks[i] if block == 0 then if (cells[row][i] ~= EMPTY) then error("x: " .. i .. ", y: " .. row .. " did not match\n expected: " .. "false\n" .. " was: " .. inspect(block_color(cells[row][i]))) end else if (cells[row][i] ~= EMPTY) then if (block_color(cells[row][i]) ~= game.colors[block]) then error("x: " .. i .. ", y: " .. row .. " did not match\n expected: " .. inspect(game.colors[block]) .. "\n" .. " was: " .. inspect(block_color(cells[row][i]))) end else print("row: ", inspect(cells[row])) error("expected a block but it was empty:\n x: " .. i .. ", y: " .. row .. " did not match\n expected: " .. inspect(game.colors[block]) .. "\n" .. " was: " .. inspect(cells[row][i])) end end end end function player_block_exists () print("--> assert", "player block exists") game.state.player.enabled = true if (game.state.block == nil) then error("FAILED: is nil!") end end function player_block_is_nil () print("--> assert", "player block is nil") game.state.player.enabled = false if (game.state.block ~= nil) then error("FAILED: exists!\n " .. inspect(game.state.block)) end end function is_an_integer (x, subject) print("--> assert", subject .. " is an integer") if (math.abs(x)~= math.floor(math.abs(x))) then error("FAILED: " .. subject .. " = " .. x .. " is no integer!\n") end end function block_is_crumbling (y, x) local cells = game.state.board.cells print("--> assert", "block " .. tostring(cells[y][x]) .. " is crumbling") if (not cells[y][x]) then error(" there was no block at y: " .. y .. " x: " .. x) end if (cells[y][x].crumbling == -1) then error(" block was not crumbling!") end end function block_has_hp (y, x, hp) local cells = game.state.board.cells print("--> assert", "block " .. tostring(cells[y][x]) .. " has " .. hp .. " hp") if (not cells[y][x]) then error(" there was no block at y: " .. y .. " x: " .. x) end if (cells[y][x].hp ~= hp) then error(" expected: " .. hp .. "\n was: " .. cells[y][x].hp) end end function run_update (steps) for i = 1, steps, 1 do love.update(game.step) end end function a_row_of_four_is_cleared () print("a row of four is cleared") -- context, when the player drops a piece build_game() -- [x][x][ ][x] build_rows({ { 1, 1, 0, 1 } }) game.state.block = build_block({ x = 3, y = game.height - 1, color = RED }) game.step = test.step love.update(game.step) player_block_exists() love.update(game.step) player_block_is_nil() row_matches(game.height - 0, { 1, 1, 1, 1 }) run_update(game.animations.exploding + 2) row_matches(game.height - 0, { 0, 0, 0, 0 }) end function a_row_of_three_becomes_grey () print("a row of three becomes grey") -- context, when the player drops a piece build_game() -- [x][x][ ][x] build_rows({ { 1, 1, 0, 0 } }) game.state.block = build_block({ x = 3, y = game.height - 1, color = RED }) game.step = test.step love.update(game.step) player_block_exists() love.update(game.step) player_block_is_nil() row_matches(game.height - 0, { 1, 1, 1, 0 }) run_update(game.animations.hardening + 2) row_matches(game.height - 0, { 8, 8, 8, 0 }) end function a_chain_of_two () print("a chain of two is cleared") -- context, when the player drops a piece build_game() -- [x][x][ ][x] build_rows({ { 2, 2, 0, 0 }, { 1, 1, 0, 0 }, { 2, 2, 1, 0 }, { 3, 3, 1, 0 } }) game.state.block = build_block({ x = 3, y = game.height - 3, color = RED }) game.step = test.step love.update(game.step) player_block_exists() love.update(game.step) player_block_is_nil() row_matches(game.height - 2, { 1, 1, 1, 0 }) -- TODO WHY PLUS TWO??? run_update(game.animations.exploding + 2) -- the blocks above have not fallen into place row_matches(game.height - 2, { 0, 0, 0, 0 }) run_update(4) -- TODO it takes 4 frames for a block to fall one square row_matches(game.height - 2, { 2, 2, 0, 0 }) run_update(game.animations.exploding + 2) -- the blocks above have not fallen into place row_matches(game.height - 2, { 0, 0, 0, 0 }) end function a_chain_of_two_with_grey_three_in_a_row () print(" three in a row") -- context, when the player drops a piece build_game() -- [x][x][ ][x] build_rows({ { 0, 0, 0, 0 }, { 0, 0, 3, 0 }, { 1, 0, 1, 0 }, { 3, 3, 1, 0 } }) game.state.block = build_block({ x = 2, y = game.height - 2, color = RED }) game.step = test.step love.update(game.step) player_block_exists() love.update(game.step) player_block_is_nil() row_matches(game.height - 1, { 1, 1, 1, 0 }) row_matches(game.height - 0, { 3, 3, 1, 0 }) run_update(game.animations.exploding + 2) -- the blocks above have not fallen into place row_matches(game.height - 2, { 0, 0, 3, 0 }) row_matches(game.height - 1, { 0, 0, 0, 0 }) row_matches(game.height - 0, { 3, 3, 0, 0 }) -- drop the block twice run_update(4) run_update(4) -- run the hardening animation run_update(game.animations.hardening + 2) row_matches(game.height - 0, { 8, 8, 8, 0 }) end function a_chain_of_two_with_grey_three_in_an_L () print(" three in an L") -- context, when the player drops a piece build_game() -- [x][x][ ][x] build_rows({ { 0, 3, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 }, { 3, 3, 1, 0 } }) game.state.block = build_block({ x = 3, y = game.height - 2, color = RED }) game.step = test.step love.update(game.step) player_block_exists() love.update(game.step) player_block_is_nil() row_matches(game.height - 2, { 0, 1, 0, 0 }) row_matches(game.height - 1, { 0, 1, 1, 0 }) row_matches(game.height - 0, { 3, 3, 1, 0 }) run_update(game.animations.exploding + 2) -- the blocks above have not fallen into place row_matches(game.height - 3, { 0, 3, 0, 0 }) row_matches(game.height - 2, { 0, 0, 0, 0 }) row_matches(game.height - 1, { 0, 0, 0, 0 }) row_matches(game.height - 0, { 3, 3, 0, 0 }) -- drop the block twice run_update(4) run_update(4) -- run the hardening animation run_update(game.animations.hardening + 2) row_matches(game.height - 1, { 0, 8, 0, 0 }) row_matches(game.height - 0, { 8, 8, 0, 0 }) end function a_chain_of_two_with_grey () print("a chain of two with grey") a_chain_of_two_with_grey_three_in_a_row() a_chain_of_two_with_grey_three_in_an_L() end function a_chain_of_three_with_grey () print("a chain of three with grey") -- context, when the player drops a piece build_game() -- [x][x][ ][x] build_rows({ { 3, 0, 0, 0 }, { 2, 2, 0, 0 }, { 1, 1, 0, 0 }, { 2, 2, 1, 0 }, { 3, 3, 1, 0 } }) game.state.block = build_block({ x = 3, y = game.height - 3, color = RED }) game.step = test.step love.update(game.step) player_block_exists() love.update(game.step) player_block_is_nil() row_matches(game.height - 2, { 1, 1, 1, 0 }) row_matches(game.height - 0, { 3, 3, 1, 0 }) run_update(game.animations.exploding + 2) -- the blocks above have not fallen into place row_matches(game.height - 2, { 0, 0, 0, 0 }) row_matches(game.height - 0, { 3, 3, 0, 0 }) -- give the blocks time to fall love.update(game.step) love.update(game.step) love.update(game.step) love.update(game.step) row_matches(game.height - 1, { 2, 2, 0, 0 }) row_matches(game.height - 2, { 2, 2, 0, 0 }) row_matches(game.height - 0, { 3, 3, 0, 0 }) run_update(game.animations.exploding + 2) row_matches(game.height - 2, { 0, 0, 0, 0 }) row_matches(game.height - 0, { 3, 3, 0, 0 }) -- give the blocks time to fall two rows run_update(4) run_update(4) run_update(game.animations.hardening + 2) row_matches(game.height - 3, { 0, 0, 0, 0 }) row_matches(game.height - 2, { 0, 0, 0, 0 }) row_matches(game.height - 1, { 8, 0, 0, 0 }) row_matches(game.height - 0, { 8, 8, 0, 0 }) end function a_grey_block_is_destroyed () print("a grey block is destroyed") -- context, when the player drops a piece build_game() -- [x][x][ ][x] build_rows({ { 0, 3, 0, 0 }, { 0, 3, 0, 0 }, { 0, 2, 0, 0 }, { 0, 2, 0, 0 }, { 2, 1, 0, 0 }, { 2, 1, 0, 0}, { 8, 8, 1, 1 } }) game.state.block = build_block({ x = 3, y = game.height - 2, color = RED }) game.step = test.step love.update(game.step) player_block_exists() love.update(game.step) player_block_is_nil() -- before clearing the red blocks row_matches(game.height - 2, { 2, 1, 0, 0 }) row_matches(game.height - 1, { 2, 1, 1, 0 }) row_matches(game.height - 0, { 8, 8, 1, 1 }) run_update(game.animations.exploding + 2) -- after clearing the red blocks row_matches(game.height - 4, { 0, 2, 0, 0 }) row_matches(game.height - 3, { 0, 2, 0, 0 }) row_matches(game.height - 2, { 2, 0, 0, 0 }) row_matches(game.height - 1, { 2, 0, 0, 0 }) row_matches(game.height - 0, { 8, 8, 0, 0 }) block_has_hp(game.height, 1, game.block_max_hp) block_has_hp(game.height, 2, game.block_max_hp - 1) -- the green blocks need to fall two cells run_update(4) run_update(4) block_has_hp(game.height, 1, game.block_max_hp - 1) block_has_hp(game.height, 2, game.block_max_hp - 2) row_matches(game.height - 4, { 0, 3, 0, 0 }) row_matches(game.height - 3, { 0, 3, 0, 0 }) row_matches(game.height - 2, { 2, 2, 0, 0 }) row_matches(game.height - 1, { 2, 2, 0, 0 }) row_matches(game.height - 0, { 8, 8, 0, 0 }) -- the blue blocks need to fall two cells run_update(game.animations.exploding) row_matches(game.height - 4, { 0, 3, 0, 0 }) row_matches(game.height - 3, { 0, 3, 0, 0 }) row_matches(game.height - 2, { 0, 0, 0, 0 }) row_matches(game.height - 1, { 0, 0, 0, 0 }) row_matches(game.height - 0, { 8, 8, 0, 0 }) love.update(4) love.update(4) -- they are not in position row_matches(game.height - 2, { 0, 3, 0, 0 }) row_matches(game.height - 1, { 0, 3, 0, 0 }) row_matches(game.height - 0, { 8, 8, 0, 0 }) game.state.block = build_block({ x = 3, y = game.height - 1, color = BLUE }) love.update(game.step) player_block_exists() love.update(game.step) player_block_exists() love.update(game.step) player_block_is_nil() row_matches(game.height - 2, { 0, 3, 0, 0 }) row_matches(game.height - 1, { 0, 3, 0, 0 }) row_matches(game.height - 0, { 8, 8, 3, 0 }) game.state.block = build_block({ x = 3, y = game.height - 2, color = BLUE }) -- we must update once between disabling and enabling the player -- so that the update timer gets reset love.update(game.step) player_block_exists() love.update(game.step) player_block_exists() love.update(game.step) player_block_is_nil() -- before clearing row_matches(game.height - 2, { 0, 3, 0, 0 }) row_matches(game.height - 1, { 0, 3, 3, 0 }) row_matches(game.height - 0, { 8, 8, 3, 0 }) run_update(1) block_has_hp(game.height, 2, 0) run_update(1) block_is_crumbling(game.height, 2) run_update(game.animations.exploding) -- after clearing row_matches(game.height - 2, { 0, 0, 0, 0 }) row_matches(game.height - 1, { 0, 0, 0, 0 }) row_matches(game.height - 0, { 8, 0, 0, 0 }) end function camera_cy_is_always_an_interger () print("camera.cy is always an integer") -- context, when the player drops a piece configure_game() game.block_max_hp = 1 game.state = build_game_state() -- [x][x][ ][x] build_rows({ { 1, 1, 0, 1 } }) game.state.block = build_block({ x = 3, y = game.height - 3, color = RED }) game.step = test.step run_update(3) player_block_exists() love.update(game.step) player_block_is_nil() row_matches(game.height - 0, { 1, 1, 1, 1 }) run_update(game.animations.exploding + 2) row_matches(game.height - 0, { 0, 0, 0, 0 }) row_matches(game.height + 1, { 0, 0, 0, 0 }) game.state.block = build_block({ x = 3, y = game.height - 0, color = RED }) player_block_exists() run_update(2) player_block_is_nil() row_matches(game.height + 1, { 0, 0, 1, 0 }) -- now let the camera scroll down run_update(7) is_an_integer(game.camera.cy, "camera.cy") end function run_tests () -- build a board with some pieces and run update test = {} test.step = 0.16 a_row_of_four_is_cleared() a_row_of_three_becomes_grey() a_chain_of_two() a_chain_of_two_with_grey() a_chain_of_three_with_grey() a_grey_block_is_destroyed() camera_cy_is_always_an_interger() player_can_move_a_block() an_obstructed_block_cannot_move() player_can_drop_a_block() print("PASSED") -- context, when the piece lands by stepping -- context, when the piece lands by gravity -- -- three pieces should become grey -- four pieces should vanish (multiple configurations) end
local tree_cb = require("nvim-tree.config").nvim_tree_callback vim.g.nvim_tree_indent_markers = 1 vim.g.nvim_tree_git_hl = 1 vim.g.nvim_tree_width_allow_resize = 0 vim.g.nvim_tree_add_trailing = 1 vim.g.nvim_tree_group_empty = 1 -- vim.g.nvim_tree_bindings = { -- { key = "l", cb = tree_cb("edit") }, -- { key = "h", cb = tree_cb("close_node") }, -- } vim.g.nvim_tree_icons = { default = "", symlink = "", git = { unstaged = "✚", staged = "✚", unmerged = "≠", renamed = "≫", untracked = "★", }, } require("nvim-tree").setup({ ignore_ft_on_setup = { ".git", "node_modules" }, auto_close = true, tab_open = true, update_focused_file = { enable = true, }, view = { mappings = { list = { { key = "l", cb = tree_cb("edit") }, { key = "h", cb = tree_cb("close_node") }, }, }, }, }) edn.keymap("<leader>te", "<cmd>NvimTreeToggle<cr>")
local testing = require 'tests.testing' local fn = require 'fn' local M = {} function M.test_1_5() testing.forstats({count = 5, sum = 15}, fn.fromto(1, 5)) end function M.test_2_2() testing.forstats({count = 1, sum = 2}, fn.fromto(2, 2)) end function M.test_4_1() testing.forstats({count = 0, sum = 0}, fn.fromto(4, 1)) end function M.test_m3_3() testing.forstats({count = 7, sum = 0}, fn.fromto(-3, 3)) end return M
-- Configuration file for the Storm backend local cpumode = ( builder:get_option( 'cpumode' ) or 'arm' ):lower() specific_files = "platform.c interface.c libstorm.c libmsgpack.c libstormarray.c" local ldscript = "kernelpayload.ld" -- Prepend with path specific_files = utils.prepend_path( specific_files, sf( "src/platform/%s", platform ) ) specific_files = specific_files .. "../../contrib/native.c" ldscript = sf( "src/platform/%s/%s", platform, ldscript ) addm{ "FOR" .. comp.cpu:upper(), 'gcc' } -- Standard GCC flags addcf{ '-ffunction-sections', '-fdata-sections', '-fno-strict-aliasing', "-g3", '-Wall' , '-mthumb'} --addlf{ '-nostartfiles', '-nostdlib', '-T', ldscript, , '-mthumb','-Wl,--gc-sections', '-Wl,--allow-multiple-definition' } addlf{ '-nostartfiles','-mcpu=cortex-m4', '-T', ldscript, '-mthumb', '-Wl,--gc-sections', "-g3", '-Wl,--allow-multiple-definition' } addaf{ '-x', 'assembler-with-cpp', '-Wall' } addlib{ 'c','gcc','m' } -- Special target configuration local target_flags = { '-mcpu=cortex-m4' } addm( 'CPUMODE_THUMB' ) addcf( target_flags ) -- addlf{ target_flags, '-Wl,-e,HardReset' } addaf{ target_flags,'-D__ASSEMBLY__' } -- Toolset data tools.storm = {} -- Array of file names that will be checked against the 'prog' target; their absence will force a rebuild tools.storm.prog_flist = { output .. ".bin" } -- We use 'gcc' as the assembler toolset.asm = toolset.compile
--[[ # Element: Auras Handles creation and updating of aura icons. ## Widget Auras - A Frame to hold `Button`s representing both buffs and debuffs. Buffs - A Frame to hold `Button`s representing buffs. Debuffs - A Frame to hold `Button`s representing debuffs. ## Notes At least one of the above widgets must be present for the element to work. ## Options .disableMouse - Disables mouse events (boolean) .disableCooldown - Disables the cooldown spiral (boolean) .size - Aura icon size. Defaults to 16 (number) .onlyShowPlayer - Shows only auras created by player/vehicle (boolean) .showStealableBuffs - Displays the stealable texture on buffs that can be stolen (boolean) .spacing - Spacing between each icon. Defaults to 0 (number) .['spacing-x'] - Horizontal spacing between each icon. Takes priority over `spacing` (number) .['spacing-y'] - Vertical spacing between each icon. Takes priority over `spacing` (number) .['growth-x'] - Horizontal growth direction. Defaults to 'RIGHT' (string) .['growth-y'] - Vertical growth direction. Defaults to 'UP' (string) .initialAnchor - Anchor point for the icons. Defaults to 'BOTTOMLEFT' (string) .filter - Custom filter list for auras to display. Defaults to 'HELPFUL' for buffs and 'HARMFUL' for debuffs (string) ## Options Auras .numBuffs - The maximum number of buffs to display. Defaults to 32 (number) .numDebuffs - The maximum number of debuffs to display. Defaults to 40 (number) .numTotal - The maximum number of auras to display. Prioritizes buffs over debuffs. Defaults to the sum of .numBuffs and .numDebuffs (number) .gap - Controls the creation of an invisible icon between buffs and debuffs. Defaults to false (boolean) .buffFilter - Custom filter list for buffs to display. Takes priority over `filter` (string) .debuffFilter - Custom filter list for debuffs to display. Takes priority over `filter` (string) ## Options Buffs .num - Number of buffs to display. Defaults to 32 (number) ## Options Debuffs .num - Number of debuffs to display. Defaults to 40 (number) ## Attributes button.caster - the unit who cast the aura (string) button.filter - the filter list used to determine the visibility of the aura (string) button.isDebuff - indicates if the button holds a debuff (boolean) button.isPlayer - indicates if the aura caster is the player or their vehicle (boolean) ## Examples -- Position and size local Buffs = CreateFrame('Frame', nil, self) Buffs:SetPoint('RIGHT', self, 'LEFT') Buffs:SetSize(16 * 2, 16 * 16) -- Register with oUF self.Buffs = Buffs --]] local _, ns = ... local oUF = ns.oUF local VISIBLE = 1 local HIDDEN = 0 local function UpdateTooltip(self) GameTooltip:SetUnitAura(self:GetParent().__owner.unit, self:GetID(), self.filter) end local function onEnter(self) if(not self:IsVisible()) then return end GameTooltip:SetOwner(self, 'ANCHOR_BOTTOMRIGHT') self:UpdateTooltip() end local function onLeave() GameTooltip:Hide() end local function createAuraIcon(element, index) local button = CreateFrame('Button', element:GetDebugName() .. 'Button' .. index, element) button:RegisterForClicks('RightButtonUp') local cd = CreateFrame('Cooldown', '$parentCooldown', button, 'CooldownFrameTemplate') cd:SetAllPoints() local icon = button:CreateTexture(nil, 'BORDER') icon:SetAllPoints() local count = button:CreateFontString(nil, 'OVERLAY', 'NumberFontNormal') count:SetPoint('BOTTOMRIGHT', button, 'BOTTOMRIGHT', -1, 0) local overlay = button:CreateTexture(nil, 'OVERLAY') overlay:SetTexture([[Interface\Buttons\UI-Debuff-Overlays]]) overlay:SetAllPoints() overlay:SetTexCoord(.296875, .5703125, 0, .515625) button.overlay = overlay local stealable = button:CreateTexture(nil, 'OVERLAY') stealable:SetTexture([[Interface\TargetingFrame\UI-TargetingFrame-Stealable]]) stealable:SetPoint('TOPLEFT', -3, 3) stealable:SetPoint('BOTTOMRIGHT', 3, -3) stealable:SetBlendMode('ADD') button.stealable = stealable button.UpdateTooltip = UpdateTooltip button:SetScript('OnEnter', onEnter) button:SetScript('OnLeave', onLeave) button.icon = icon button.count = count button.cd = cd --[[ Callback: Auras:PostCreateIcon(button) Called after a new aura button has been created. * self - the widget holding the aura buttons * button - the newly created aura button (Button) --]] if(element.PostCreateIcon) then element:PostCreateIcon(button) end return button end local function customFilter(element, unit, button, name) if((element.onlyShowPlayer and button.isPlayer) or (not element.onlyShowPlayer and name)) then return true end end local function updateIcon(element, unit, index, offset, filter, isDebuff, visible) local name, texture, count, debuffType, duration, expiration, caster, isStealable, nameplateShowSelf, spellID, canApply, isBossDebuff, casterIsPlayer, nameplateShowAll, timeMod, effect1, effect2, effect3 = UnitAura(unit, index, filter) -- RayUI block if element.forceShow then spellID = 47540 name, _, texture = GetSpellInfo(spellID) count, debuffType, duration, expiration, caster, isStealable, nameplateShowSelf, canApplyAura, isBossDebuff = 5, 'Magic', 0, 60, 'player', nil, nil, nil, nil end -- end Block if(name) then local position = visible + offset + 1 local button = element[position] if(not button) then --[[ Override: Auras:CreateIcon(position) Used to create the aura button at a given position. * self - the widget holding the aura buttons * position - the position at which the aura button is to be created (number) ## Returns * button - the button used to represent the aura (Button) --]] button = (element.CreateIcon or createAuraIcon) (element, position) table.insert(element, button) element.createdIcons = element.createdIcons + 1 end button.caster = caster button.filter = filter button.isDebuff = isDebuff button.isPlayer = caster == 'player' or caster == 'vehicle' --[[ Override: Auras:CustomFilter(unit, button, ...) Defines a custom filter that controls if the aura button should be shown. * self - the widget holding the aura buttons * unit - the unit on which the aura is cast (string) * button - the button displaying the aura (Button) * ... - the return values from [UnitAura](http://wowprogramming.com/docs/api/UnitAura.html) ## Returns * show - indicates whether the aura button should be shown (boolean) --]] -- RayUI changed block local show = true if not element.forceShow then show = (element.CustomFilter or customFilter) (element, unit, button, name, texture, count, debuffType, duration, expiration, caster, isStealable, nameplateShowSelf, spellID, canApply, isBossDebuff, casterIsPlayer, nameplateShowAll,timeMod, effect1, effect2, effect3) end -- end block if(show) then -- We might want to consider delaying the creation of an actual cooldown -- object to this point, but I think that will just make things needlessly -- complicated. if(button.cd and not element.disableCooldown) then if(duration and duration > 0) then button.cd:SetCooldown(expiration - duration, duration) button.cd:Show() else button.cd:Hide() end end if(button.overlay) then if((isDebuff and element.showDebuffType) or (not isDebuff and element.showBuffType) or element.showType) then local color = element.__owner.colors.debuff[debuffType] or element.__owner.colors.debuff.none button.overlay:SetVertexColor(color[1], color[2], color[3]) button.overlay:Show() else button.overlay:Hide() end end if(button.stealable) then if(not isDebuff and isStealable and element.showStealableBuffs and not UnitIsUnit('player', unit)) then button.stealable:Show() else button.stealable:Hide() end end if(button.icon) then button.icon:SetTexture(texture) end if(button.count) then button.count:SetText(count > 1 and count) end local size = element.size or 16 button:SetSize(size, size) button:EnableMouse(not element.disableMouse) button:SetID(index) button:Show() --[[ Callback: Auras:PostUpdateIcon(unit, button, index, position) Called after the aura button has been updated. * self - the widget holding the aura buttons * unit - the unit on which the aura is cast (string) * button - the updated aura button (Button) * index - the index of the aura (number) * position - the actual position of the aura button (number) * duration - the aura duration in seconds (number?) * expiration - the point in time when the aura will expire. Comparable to GetTime() (number) * debuffType - the debuff type of the aura (string?)['Curse', 'Disease', 'Magic', 'Poison'] * isStealable - whether the aura can be stolen or purged (boolean) --]] if(element.PostUpdateIcon) then element:PostUpdateIcon(unit, button, index, position, duration, expiration, debuffType, isStealable) end return VISIBLE else return HIDDEN end end end local function SetPosition(element, from, to) local sizex = (element.size or 16) + (element['spacing-x'] or element.spacing or 0) local sizey = (element.size or 16) + (element['spacing-y'] or element.spacing or 0) local anchor = element.initialAnchor or 'BOTTOMLEFT' local growthx = (element['growth-x'] == 'LEFT' and -1) or 1 local growthy = (element['growth-y'] == 'DOWN' and -1) or 1 local cols = math.floor(element:GetWidth() / sizex + 0.5) for i = from, to do local button = element[i] -- Bail out if the to range is out of scope. if(not button) then break end local col = (i - 1) % cols local row = math.floor((i - 1) / cols) button:ClearAllPoints() button:SetPoint(anchor, element, anchor, col * sizex * growthx, row * sizey * growthy) end end local function filterIcons(element, unit, filter, limit, isDebuff, offset, dontHide) if(not offset) then offset = 0 end local index = 1 local visible = 0 local hidden = 0 while(visible < limit) do local result = updateIcon(element, unit, index, offset, filter, isDebuff, visible) if(not result) then break elseif(result == VISIBLE) then visible = visible + 1 elseif(result == HIDDEN) then hidden = hidden + 1 end index = index + 1 end if(not dontHide) then for i = visible + offset + 1, #element do element[i]:Hide() end end return visible, hidden end local function UpdateAuras(self, event, unit) if(self.unit ~= unit) then return end local auras = self.Auras if(auras) then --[[ Callback: Auras:PreUpdate(unit) Called before the element has been updated. * self - the widget holding the aura buttons * unit - the unit for which the update has been triggered (string) --]] if(auras.PreUpdate) then auras:PreUpdate(unit) end local numBuffs = auras.numBuffs or 32 local numDebuffs = auras.numDebuffs or 40 local max = auras.numTotal or numBuffs + numDebuffs local visibleBuffs, hiddenBuffs = filterIcons(auras, unit, auras.buffFilter or auras.filter or 'HELPFUL', math.min(numBuffs, max), nil, 0, true) local hasGap if(visibleBuffs ~= 0 and auras.gap) then hasGap = true visibleBuffs = visibleBuffs + 1 local button = auras[visibleBuffs] if(not button) then button = (auras.CreateIcon or createAuraIcon) (auras, visibleBuffs) table.insert(auras, button) auras.createdIcons = auras.createdIcons + 1 end -- Prevent the button from displaying anything. if(button.cd) then button.cd:Hide() end if(button.icon) then button.icon:SetTexture() end if(button.overlay) then button.overlay:Hide() end if(button.stealable) then button.stealable:Hide() end if(button.count) then button.count:SetText() end button:EnableMouse(false) button:Show() --[[ Callback: Auras:PostUpdateGapIcon(unit, gapButton, visibleBuffs) Called after an invisible aura button has been created. Only used by Auras when the `gap` option is enabled. * self - the widget holding the aura buttons * unit - the unit that has the invisible aura button (string) * gapButton - the invisible aura button (Button) * visibleBuffs - the number of currently visible aura buttons (number) --]] if(auras.PostUpdateGapIcon) then auras:PostUpdateGapIcon(unit, button, visibleBuffs) end end local visibleDebuffs, hiddenDebuffs = filterIcons(auras, unit, auras.debuffFilter or auras.filter or 'HARMFUL', math.min(numDebuffs, max - visibleBuffs), true, visibleBuffs) auras.visibleDebuffs = visibleDebuffs if(hasGap and visibleDebuffs == 0) then auras[visibleBuffs]:Hide() visibleBuffs = visibleBuffs - 1 end auras.visibleBuffs = visibleBuffs auras.visibleAuras = auras.visibleBuffs + auras.visibleDebuffs local fromRange, toRange --[[ Callback: Auras:PreSetPosition(max) Called before the aura buttons have been (re-)anchored. * self - the widget holding the aura buttons * max - the maximum possible number of aura buttons (number) ## Returns * from - the offset of the first aura button to be (re-)anchored (number) * to - the offset of the last aura button to be (re-)anchored (number) --]] if(auras.PreSetPosition) then fromRange, toRange = auras:PreSetPosition(max) end if(fromRange or auras.createdIcons > auras.anchoredIcons) then --[[ Override: Auras:SetPosition(from, to) Used to (re-)anchor the aura buttons. Called when new aura buttons have been created or if :PreSetPosition is defined. * self - the widget that holds the aura buttons * from - the offset of the first aura button to be (re-)anchored (number) * to - the offset of the last aura button to be (re-)anchored (number) --]] (auras.SetPosition or SetPosition) (auras, fromRange or auras.anchoredIcons + 1, toRange or auras.createdIcons) auras.anchoredIcons = auras.createdIcons end --[[ Callback: Auras:PostUpdate(unit) Called after the element has been updated. * self - the widget holding the aura buttons * unit - the unit for which the update has been triggered (string) --]] if(auras.PostUpdate) then auras:PostUpdate(unit) end end local buffs = self.Buffs if(buffs) then if(buffs.PreUpdate) then buffs:PreUpdate(unit) end local numBuffs = buffs.num or 32 local visibleBuffs, hiddenBuffs = filterIcons(buffs, unit, buffs.filter or 'HELPFUL', numBuffs) buffs.visibleBuffs = visibleBuffs local fromRange, toRange if(buffs.PreSetPosition) then fromRange, toRange = buffs:PreSetPosition(numBuffs) end if(fromRange or buffs.createdIcons > buffs.anchoredIcons) then (buffs.SetPosition or SetPosition) (buffs, fromRange or buffs.anchoredIcons + 1, toRange or buffs.createdIcons) buffs.anchoredIcons = buffs.createdIcons end if(buffs.PostUpdate) then buffs:PostUpdate(unit) end end local debuffs = self.Debuffs if(debuffs) then if(debuffs.PreUpdate) then debuffs:PreUpdate(unit) end local numDebuffs = debuffs.num or 40 local visibleDebuffs, hiddenDebuffs = filterIcons(debuffs, unit, debuffs.filter or 'HARMFUL', numDebuffs, true) debuffs.visibleDebuffs = visibleDebuffs local fromRange, toRange if(debuffs.PreSetPosition) then fromRange, toRange = debuffs:PreSetPosition(numDebuffs) end if(fromRange or debuffs.createdIcons > debuffs.anchoredIcons) then (debuffs.SetPosition or SetPosition) (debuffs, fromRange or debuffs.anchoredIcons + 1, toRange or debuffs.createdIcons) debuffs.anchoredIcons = debuffs.createdIcons end if(debuffs.PostUpdate) then debuffs:PostUpdate(unit) end end end local function Update(self, event, unit) if(self.unit ~= unit) then return end UpdateAuras(self, event, unit) -- Assume no event means someone wants to re-anchor things. This is usually -- done by UpdateAllElements and :ForceUpdate. if(event == 'ForceUpdate' or not event) then local buffs = self.Buffs if(buffs) then (buffs.SetPosition or SetPosition) (buffs, 1, buffs.createdIcons) end local debuffs = self.Debuffs if(debuffs) then (debuffs.SetPosition or SetPosition) (debuffs, 1, debuffs.createdIcons) end local auras = self.Auras if(auras) then (auras.SetPosition or SetPosition) (auras, 1, auras.createdIcons) end end end local function ForceUpdate(element) return Update(element.__owner, 'ForceUpdate', element.__owner.unit) end local function Enable(self) if(self.Buffs or self.Debuffs or self.Auras) then self:RegisterEvent('UNIT_AURA', UpdateAuras) local buffs = self.Buffs if(buffs) then buffs.__owner = self buffs.ForceUpdate = ForceUpdate buffs.createdIcons = buffs.createdIcons or 0 buffs.anchoredIcons = 0 buffs:Show() end local debuffs = self.Debuffs if(debuffs) then debuffs.__owner = self debuffs.ForceUpdate = ForceUpdate debuffs.createdIcons = debuffs.createdIcons or 0 debuffs.anchoredIcons = 0 debuffs:Show() end local auras = self.Auras if(auras) then auras.__owner = self auras.ForceUpdate = ForceUpdate auras.createdIcons = auras.createdIcons or 0 auras.anchoredIcons = 0 auras:Show() end return true end end local function Disable(self) if(self.Buffs or self.Debuffs or self.Auras) then self:UnregisterEvent('UNIT_AURA', UpdateAuras) if(self.Buffs) then self.Buffs:Hide() end if(self.Debuffs) then self.Debuffs:Hide() end if(self.Auras) then self.Auras:Hide() end end end oUF:AddElement('Auras', Update, Enable, Disable)
local cv = require 'cv._env' require 'cutorch' require 'cv.features2d' -- TODO: remove this after gathering all CUDA packages in a single submodule cv.cuda = cv.cuda or require 'cv._env_cuda' local ffi = require 'ffi' ffi.cdef[[ struct PtrWrapper createBFMatcher(int normType); bool DescriptorMatcher_isMaskSupported(struct PtrWrapper ptr); void DescriptorMatcher_add( struct PtrWrapper ptr, struct TensorArray descriptors); struct TensorArray DescriptorMatcher_getTrainDescriptors( struct cutorchInfo info, struct PtrWrapper ptr); void DescriptorMatcher_clear(struct PtrWrapper ptr); bool DescriptorMatcher_empty(struct PtrWrapper ptr); void DescriptorMatcher_train(struct PtrWrapper ptr); struct TensorWrapper DescriptorMatcher_match( struct cutorchInfo info, struct PtrWrapper ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, struct TensorWrapper mask); struct TensorWrapper DescriptorMatcher_match_masks( struct cutorchInfo info, struct PtrWrapper ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper matches, struct TensorArray masks); struct DMatchArray DescriptorMatcher_matchConvert( struct PtrWrapper ptr, struct TensorWrapper gpu_matches); struct TensorWrapper DescriptorMatcher_knnMatch( struct cutorchInfo info, struct PtrWrapper ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, int k, struct TensorWrapper mask); struct TensorWrapper DescriptorMatcher_knnMatch_masks( struct cutorchInfo info, struct PtrWrapper ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, int k, struct TensorArray masks); struct DMatchArrayOfArrays DescriptorMatcher_knnMatchConvert( struct PtrWrapper ptr, struct TensorWrapper gpu_matches, bool compactResult); struct TensorWrapper DescriptorMatcher_radiusMatch( struct cutorchInfo info, struct PtrWrapper ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, float maxDistance, struct TensorWrapper mask); struct TensorWrapper DescriptorMatcher_radiusMatch_masks( struct cutorchInfo info, struct PtrWrapper ptr, struct TensorWrapper queryDescriptors, struct TensorWrapper trainDescriptors, struct TensorWrapper matches, float maxDistance, struct TensorArray masks); struct DMatchArrayOfArrays DescriptorMatcher_radiusMatchConvert( struct PtrWrapper ptr, struct TensorWrapper gpu_matches, bool compactResult); void Feature2DAsync_dtor(struct Feature2DAsyncPtr ptr); struct TensorWrapper Feature2DAsync_detectAsync( struct cutorchInfo info, struct Feature2DAsyncPtr ptr, struct TensorWrapper image, struct TensorWrapper keypoints, struct TensorWrapper mask); struct TensorArray Feature2DAsync_computeAsync( struct cutorchInfo info, struct Feature2DAsyncPtr ptr, struct TensorWrapper image, struct TensorWrapper keypoints, struct TensorWrapper descriptors); struct TensorArray Feature2DAsync_detectAndComputeAsync( struct cutorchInfo info, struct Feature2DAsyncPtr ptr, struct TensorWrapper image, struct TensorWrapper mask, struct TensorWrapper keypoints, struct TensorWrapper descriptors, bool useProvidedKeypoints); struct KeyPointArray Feature2DAsync_convert( struct Feature2DAsyncPtr ptr, struct TensorWrapper gpu_keypoints); struct FastFeatureDetectorPtr FastFeatureDetector_ctor( int threshold, bool nonmaxSuppression, int type, int max_npoints); void FastFeatureDetector_dtor(struct FastFeatureDetectorPtr ptr); void FastFeatureDetector_setMaxNumPoints(struct FastFeatureDetectorPtr ptr, int val); int FastFeatureDetector_getMaxNumPoints(struct FastFeatureDetectorPtr ptr); struct ORBPtr ORB_ctor( int nfeatures, float scaleFactor, int nlevels, int edgeThreshold, int firstLevel, int WTA_K, int scoreType, int patchSize, int fastThreshold, bool blurForDescriptor); void ORB_setBlurForDescriptor(struct ORBPtr ptr, bool val); bool ORB_getBlurForDescriptor(struct ORBPtr ptr); ]] local C = ffi.load(cv.libPath('cudafeatures2d')) require 'cv.Classes' local Classes = ffi.load(cv.libPath('Classes')) do local DescriptorMatcher = torch.class('cuda.DescriptorMatcher', 'cv.Algorithm', cv.cuda) function DescriptorMatcher.createBFMatcher(t) local argRules = { {"normType", default = cv.NORM_L2} } local retval = torch.factory('cuda.DescriptorMatcher')() retval.ptr = ffi.gc(C.createBFMatcher(cv.argcheck(t, argRules)), Classes.Algorithm_dtor) return retval end function DescriptorMatcher:isMaskSupported() return C.DescriptorMatcher_isMaskSupported(self.ptr) end function DescriptorMatcher:add(t) local argRules = { {"descriptors", required = true} } C.DescriptorMatcher_add(self.ptr, cv.wrap_tensors(descriptors)) end function DescriptorMatcher:getTrainDescriptors() return cv.unwrap_tensors(C.DescriptorMatcher_getTrainDescriptors( cv.cuda._info(), self.ptr) , true) end function DescriptorMatcher:clear() C.DescriptorMatcher_clear(self.ptr) end function DescriptorMatcher:empty() return C.DescriptorMatcher_empty(self.ptr) end function DescriptorMatcher:train() C.DescriptorMatcher_train(self.ptr) end function DescriptorMatcher:match(t) local argRules = { {"queryDescriptors", required = true, operator = cv.wrap_tensor}, {"trainDescriptors", default = nil, operator = cv.wrap_tensor}, {"matches", default = nil, operator = cv.wrap_tensor}, {"mask", default = nil, operator = cv.wrap_tensor}, {"masks", default = nil, operator = cv.wrap_tensors} } assert(not (t.mask and t.masks) and not (t[4] and t[5])) if t.masks or t[5] then return cv.unwrap_tensors(C.DescriptorMatcher_match_masks( cv.cuda._info(), self.ptr, cv.argcheck(t, argRules))) else return cv.unwrap_tensors(C.DescriptorMatcher_match( cv.cuda._info(), self.ptr, cv.argcheck(t, argRules))) end end function DescriptorMatcher:matchConvert(t) local argRules = { {"gpu_matches", required = true, operator = cv.wrap_tensor} } return cv.gcarray(C.DescriptorMatcher_matchConvert(self.ptr, cv.argcheck(t, argRules))) end function DescriptorMatcher:knnMatch(t) local argRules = { {"queryDescriptors", required = true, operator = cv.wrap_tensor}, {"trainDescriptors", default = nil, operator = cv.wrap_tensor}, {"matches", default = nil, operator = cv.wrap_tensor}, {"k", required = true}, {"mask", default = nil, operator = cv.wrap_tensor}, {"masks", default = nil, operator = cv.wrap_tensors} } assert(not (t.mask and t.masks) and not (t[5] and t[6])) if t.masks or t[6] then return cv.unwrap_tensors(C.DescriptorMatcher_knnMatch_masks( cv.cuda._info(), self.ptr, cv.argcheck(t, argRules))) else return cv.unwrap_tensors(C.DescriptorMatcher_knnMatch( cv.cuda._info(), self.ptr, cv.argcheck(t, argRules))) end end function DescriptorMatcher:knnMatchConvert(t) local argRules = { {"gpu_matches", required = true, operator = cv.wrap_tensor}, {"compactResult", default = false} } local result = cv.gcarray(C.DescriptorMatcher_knnMatchConvert(self.ptr, cv.argcheck(t, argRules))) local retval = {} for i = 0, result.size-1 do retval[i+1] = cv.gcarray(result[i]) end return retval end function DescriptorMatcher:radiusMatch(t) local argRules = { {"queryDescriptors", required = true, operator = cv.wrap_tensor}, {"trainDescriptors", default = nil, operator = cv.wrap_tensor}, {"matches", default = nil, operator = cv.wrap_tensor}, {"maxDistance", required = true}, {"mask", default = nil, operator = cv.wrap_tensor}, {"masks", default = nil, operator = cv.wrap_tensors} } assert(not (t.mask and t.masks) and not (t[5] and t[6])) if t.masks or t[6] then return cv.unwrap_tensors(C.DescriptorMatcher_radiusMatch_masks( cv.cuda._info(), self.ptr, cv.argcheck(t, argRules))) else return cv.unwrap_tensors(C.DescriptorMatcher_radiusMatch( cv.cuda._info(), self.ptr, cv.argcheck(t, argRules))) end end function DescriptorMatcher:radiusMatchConvert(t) local argRules = { {"gpu_matches", required = true, operator = cv.wrap_tensor}, {"compactResult", default = false} } local result = cv.gcarray(C.DescriptorMatcher_radiusMatchConvert(self.ptr, cv.argcheck(t, argRules))) local retval = {} for i = 0, result.size-1 do retval[i+1] = cv.gcarray(result[i]) end return retval end end do local Feature2DAsync = torch.class('cuda.Feature2DAsync', 'cv.Feature2D', cv.cuda) function Feature2DAsync:detect(t) local argRules = { {"image", required = true, operator = cv.wrap_tensor}, {"keypoints", default = nil, operator = cv.wrap_tensor}, {"mask", default = nil, operator = cv.wrap_tensor} } return cv.unwrap_tensors(C.Feature2DAsync_detectAsync( cv.cuda._info(), self.ptr, cv.argcheck(t, argRules))) end function Feature2DAsync:compute(t) local argRules = { {"image", required = true, operator = cv.wrap_tensor}, {"keypoints", default = nil, operator = cv.wrap_tensor}, {"descriptors", default = nil, operator = cv.wrap_tensor} } return cv.unwrap_tensors(C.Feature2DAsync_computeAsync( cv.cuda._info(), self.ptr, cv.argcheck(t, argRules))) end function Feature2DAsync:detectAndCompute(t) local argRules = { {"image", required = true, operator = cv.wrap_tensor}, {"mask", default = nil, operator = cv.wrap_tensor}, {"keypoints", default = nil, operator = cv.wrap_tensor}, {"descriptors", default = nil, operator = cv.wrap_tensor}, {"useProvidedKeypoints", default = false} } return cv.unwrap_tensors(C.Feature2DAsync_detectAndComputeAsync( cv.cuda._info(), self.ptr, cv.argcheck(t, argRules))) end function Feature2DAsync:convert(t) local argRules = { {"gpu_keypoints", required = true, operator = cv.wrap_tensor} } return cv.gcarray(C.Feature2DAsync_convert(self.ptr, cv.argcheck(t, argRules))) end end do local FastFeatureDetector = torch.class( 'cuda.FastFeatureDetector', 'cuda.Feature2DAsync', cv.cuda) function FastFeatureDetector:__init(t) local argRules = { {"threshold", default = 10}, {"nonmaxSuppression", default = true}, {"type", default = cv.FastFeatureDetector_TYPE_9_16}, {"max_npoints", default = 5000} } self.ptr = ffi.gc(C.FastFeatureDetector_ctor( cv.argcheck(t, argRules), C.Feature2DAsync_dtor)) end function FastFeatureDetector:setMaxNumPoints(t) local argRules = { {"val", required = true} } C.FastFeatureDetector_setMaxNumPoints(self.ptr, cv.argcheck(t, argRules)) end function FastFeatureDetector:getMaxNumPoints() return C.FastFeatureDetector_getMaxNumPoints(self.ptr) end end do local ORB = torch.class('cuda.ORB', 'cuda.Feature2DAsync', cv.cuda) function ORB:__init(t) local argRules = { {"nfeatures", default = 500}, {"scaleFactor", default = 1.2}, {"nlevels", default = 8}, {"edgeThreshold", default = 31}, {"firstLevel", default = 0}, {"WTA_K", default = 2}, {"scoreType", default = cv.ORB_HARRIS_SCORE}, {"patchSize", default = 31}, {"fastThreshold", default = 20}, {"blurForDescriptor", default = false} } self.ptr = ffi.gc(C.ORB_ctor( cv.argcheck(t, argRules), C.Feature2DAsync_dtor)) end function ORB:setsetBlurForDescriptorMaxNumPoints(t) local argRules = { {"val", required = true} } C.ORB_setBlurForDescriptor(self.ptr, cv.argcheck(t, argRules)) end function ORB:getBlurForDescriptor() return C.ORB_getBlurForDescriptor(self.ptr) end end return cv.cuda
while true do local a = {feed()} if -a == 0 then break end process(a) end
local tiny = require('lib.tiny') local class = require('lib.middleclass') local System = tiny.processingSystem(class('system.input.touch')) function System:initialize() self.filter = tiny.requireAll('isPlayer', 'left', 'right', 'space') end function System:process(e, dt) if e.left or e.right or e.space then return end local w, h = love.window.getMode() for i, id in pairs(love.touch.getTouches()) do local x, y = love.touch.getPosition(id) local above = y < h / 2 e.left = e.left or not above and (x < w / 2) e.right = e.right or not above and (x > w / 2) e.space = e.space or above end end return System
return { SOCKETFUNCTION = {'FUNCTIONPOINT', 1}, SOCKETDATA = {'OBJECTPOINT', 2}, PIPELINING = {'LONG', 3}, TIMERFUNCTION = {'FUNCTIONPOINT', 4}, TIMERDATA = {'OBJECTPOINT', 5}, MAXCONNECTS = {'LONG', 6}, MAX_HOST_CONNECTIONS = {'LONG', 7}, MAX_PIPELINE_LENGTH = {'LONG', 8}, CONTENT_LENGTH_PENALTY_SIZE = {'OFF_T', 9}, CHUNK_LENGTH_PENALTY_SIZE = {'OFF_T', 10}, PIPELINING_SITE_BL = {'OBJECTPOINT', 11}, PIPELINING_SERVER_BL = {'OBJECTPOINT', 12}, MAX_TOTAL_CONNECTIONS = {'LONG', 13}, PUSHFUNCTION = {'FUNCTIONPOINT', 14}, PUSHDATA = {'OBJECTPOINT', 15}, };
local konami = { name = "konami", instances = {}, } setmetatable(konami, konami) function konami.add(f) assert(f and f.pattern, "Why would you add a pattern ... with no pattern?") local obj = f setmetatable(obj, konami) obj.enabled = true obj.active = false obj.time, obj.current = 0, 0 table.insert(konami.instances, obj) return obj end function konami:update_self(dt) if self.active and self.duration then self.time = self.time + dt if self.time > self.duration then self.active = false self.current = 0 if self.on_end then self.on_end() end end end end function konami:keypressed_self(key) if not self.active then if key == self.pattern[self.current + 1] then self.current = self.current + 1 if self.on_success then self.on_success() end if self.current == #self.pattern then self.active = self.duration or false self.current = self.duration and self.current or 0 self.time = 0 if self.on_start then self.on_start() end end elseif self.current ~= 0 then self.current = 0 if self.on_fail then self.on_fail() end end end end function konami.update(dt) for i = #konami.instances, 1, -1 do if konami.instances[i] then konami.instances[i]:update_self(dt) end end end function konami:get_length() return #self.pattern end function konami:get_position() return self.current end function konami:is_active() return self.active end function konami:remove() for i = #konami.instances, 1, -1 do if konami.instances[i] == self then table.remove(konami.instances, i) self = nil end end end function konami.clear() for i = 1, #konami.instances do konami.instances[i] = nil end end function konami.keypressed(key) for i = #konami.instances, 1, -1 do if konami.instances[i] then konami.instances[i]:keypressed_self(key) end end end return konami
--[[ Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved @file UriJudge.lua @author sunnnychan@gmail.com @date 2016/03/12 11:27:24 @brief uri judge ]]-- local BDLOG = require('lua.bdlib.BdLogWrite') local setmetatable = setmetatable local tostring = tostring local tonumber = tonumber local Method = require('models.service.rule.JudgeMethods') local UriJudge = {} function UriJudge:new(uriInput, ruleType, ruleContentInput) local instance = {} instance.strReMatch = 8 instance.strEqualsen = 9 instance.strEqualInsen = 10 instance.uri = uriInput instance.ruleType = tonumber(ruleType) instance.ruleContent = ruleContentInput setmetatable(instance, {__index = self}) return instance end function UriJudge:judge() if self.ruleType == self.strReMatch then local pattern, model = self.ruleContent['re_pattern'], '' if (self.ruleContent['re_model']) then model = self.ruleContent['re_model'] end return Method.checkStrReMatch(self.uri, pattern, model) elseif self.ruleType == self.strEqualsen then return Method.checkStrEqualCaseSensitive(self.uri, self.ruleContent) elseif self.ruleType == self.strEqualInsen then return Method.checkStrEqualCaseInsensitive(self.uri, self.ruleContent) else BDLOG.log_fatal('unsupported rule type by Uri judge. [rule type] : %s', self.ruleType) return false end end return UriJudge
--------------------------------------------------------------------------------------------------- -- User story: Smoke -- Use case: Speak -- Item: Happy path -- -- Requirement summary: -- [Speak] SUCCESS on TTS.Speak -- -- Description: -- Mobile application sends Speak request with valid parameters to SDL -- -- Pre-conditions: -- a. HMI and SDL are started -- b. appID is registered and activated on SDL -- -- Steps: -- Application sends Speak request with valid parameters to SDL -- -- Expected: -- SDL validates parameters of the request -- SDL checks if TTS interface is available on HMI -- SDL checks if Speak is allowed by Policies -- SDL checks if all parameters are allowed by Policies -- SDL transfers the TTS part of request with allowed parameters to HMI -- SDL receives TTS part of response from HMI with "SUCCESS" result code -- SDL transfers response to mobile app --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/Smoke/commonSmoke') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Functions ]] local function getRequestParams() return { ttsChunks = { { text ="a", type ="TEXT" } } } end local function speakSuccess() print("Waiting 20s ...") local cid = common.getMobileSession():SendRPC("Speak", getRequestParams()) common.getHMIConnection():ExpectRequest("TTS.Speak", getRequestParams()) :Do(function(_, data) common.getHMIConnection():SendNotification("TTS.Started") local function sendSpeakResponse() common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", { }) common.getHMIConnection():SendNotification("TTS.Stopped") end local function sendOnResetTimeout() common.getHMIConnection():SendNotification("BasicCommunication.OnResetTimeout", { requestID = data.id, methodName = data.method }) end common.runAfter(sendOnResetTimeout, 9000) common.runAfter(sendSpeakResponse, 18000) end) common.getMobileSession():ExpectNotification("OnHMIStatus", { systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "ATTENUATED" }, { systemContext = "MAIN", hmiLevel = "FULL", audioStreamingState = "AUDIBLE" }) :Times(2) :Timeout(20000) common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" }) :Timeout(20000) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Update Preloaded PT", common.updatePreloadedPT) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Register App", common.registerApp) runner.Step("Activate App", common.activateApp) runner.Title("Test") runner.Step("Speak Positive Case", speakSuccess) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
PlayerCorpse = { type = "PlayerCorpse", Properties = { }, } function PlayerCorpse:IsActionable(user) -- Log("[ PlayerCorpse ] IsActionable"); if (g_gameRules.game:IsActionable(user.id, self.id)) then return 1; else return 0; end end function PlayerCorpse:GetActions(user) -- Log("[ PlayerCorpse ] GetActions"); local actions = {}; actions = g_gameRules.game:GetActions(user.id, self.id, actions); return actions; end function PlayerCorpse:PerformAction(user, action) -- Log("[ PlayerCorpse ] PerformAction: action="..action); return g_gameRules.game:PerformAction(user.id, self.id, action); end
--- -- Execute a query with no result required -- -- @param query -- @param params -- @param func -- @param Transaction transaction -- -- @return coroutine -- function MySQL.Async.execute(query, params, func, transaction) local Command = MySQL.Utils.CreateCommand(query, params, transaction) local executeTask = Command.ExecuteNonQueryAsync(); local callback = func or function() end local connection if transaction then connection = nil else connection = Command.Connection end clr.Brouznouf.FiveM.Async.ExecuteCallback(executeTask, MySQL.Async.wrapQuery( callback, connection, Command.CommandText, MySQL.Utils.ConvertObject )) end --- -- Execute a query and fetch all results in an async way -- -- @param query -- @param params -- @param func -- @param Transaction transaction -- -- @return coroutine -- function MySQL.Async.fetchAll(query, params, func, transaction) local Command = MySQL.Utils.CreateCommand(query, params, transaction) local executeReaderTask = Command.ExecuteReaderAsync(); local callback = func or function(Result) return Result end local connection if transaction then connection = nil else connection = Command.Connection end clr.Brouznouf.FiveM.Async.ExecuteReaderCallback(executeReaderTask, MySQL.Async.wrapQuery( callback, connection, Command.CommandText, MySQL.Utils.ConvertResultToTable )) end --- -- Execute a query and fetch the first column of the first row -- Useful for count function by example -- -- @param query -- @param params -- @param func -- @param Transaction transaction -- -- @return coroutine -- function MySQL.Async.fetchScalar(query, params, func, transaction) local Command = MySQL.Utils.CreateCommand(query, params, transaction) local executeScalarTask = Command.ExecuteScalarAsync(); local callback = func or function() end local connection if transaction then connection = nil else connection = Command.Connection end clr.Brouznouf.FiveM.Async.ExecuteScalarCallback(executeScalarTask, MySQL.Async.wrapQuery( callback, connection, Command.CommandText, MySQL.Utils.ConvertObject )) end --- -- Create a transaction -- -- @param function func -- -- @return coroutine -- function MySQL.Async.beginTransaction(func) local connection = MySQL:createConnection(); local beginTransactionTask = connection.BeginTransactionAsync(clr.System.Threading.CancellationToken.None); local callback = func or function() end clr.Brouznouf.FiveM.Async.BeginTransactionCallback(beginTransactionTask, MySQL.Async.wrapQuery( callback, nil, 'BEGIN TRANSACTION' )) end --- -- Commit the transaction -- -- @param Transaction transaction -- @param function func -- function MySQL.Async.commitTransaction(transaction, func) local commitTransactionTrask = transaction.CommitAsync(clr.System.Threading.CancellationToken.None); local callback = func or function() end clr.Brouznouf.FiveM.Async.CommitTransactionCallback(commitTransactionTrask, MySQL.Async.wrapQuery( callback, transaction.Connection, 'COMMIT' )) end --- -- Rollback the transaction -- -- @param Transaction transaction -- @param function func -- function MySQL.Async.rollbackTransaction(transaction, func) local rollbackTransactionTask = transaction.RollbackAsync(clr.System.Threading.CancellationToken.None); local callback = func or function() end clr.Brouznouf.FiveM.Async.RollbackTransactionCallback(rollbackTransactionTask, MySQL.Async.wrapQuery( callback, transaction.Connection, 'ROLLBACK' )) end function MySQL.Async.wrapQuery(next, Connection, Message, Transformer) Transformer = Transformer or function (Result) return Result end local Stopwatch = clr.System.Diagnostics.Stopwatch() Stopwatch.Start() return function (Result, Error) if Error ~= nil then Logger:Error(Error.ToString()) if Connection then Connection.Close() Connection.Dispose() end return nil end local ConnectionId = -1; Result = Transformer(Result) if Connection then ConnectionId = Connection.ServerThread Connection.Close() Connection.Dispose() end Stopwatch.Stop() Logger:Info(string.format('[%s][%d][%dms] %s', GetInvokingResource(), ConnectionId, Stopwatch.ElapsedMilliseconds, Message)) next(Result) return Result end end
--[[ Path : ltrace.lua Author : Roc <RocAltair@gmail.com> CreateTime : 2016-01-21 19:15:34 Description : Description --]] local IS_LUAJIT = jit and true or false local ltrace_getenv local getstack_from local getstack local dumpvalue local dumptable local dumpframe local dumpstack local getfulltrace local mTABLE_MAX_DEEP = 3 local mVALUE_MAX_LEN = 5120 local traceback = {} local setfenv = _G.setfenv or function(f, t) f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func) local name local up = 0 repeat up = up + 1 name = debug.getupvalue(f, up) until name == '_ENV' or name == nil if name then debug.upvaluejoin(f, up, function() return name end, 1) -- use unique upvalue debug.setupvalue(f, up, t) end return f end local getfenv = _G.getfenv or function(f) f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func) local name, val local up = 0 repeat up = up + 1 name, val = debug.getupvalue(f, up) until name == '_ENV' or name == nil return val end local function canPrint(k, v) if type(v) ~= "table" then return true end if v == _G then return false end return true end function ltrace_getenv(realframe) local env = {} local indexmap = {} local i = 1 local funcinfo = debug.getinfo(realframe, "nlSf") if not funcinfo then return end local k, v = debug.getlocal(realframe, i) while k do indexmap[k] = i env[k] = v i = i + 1 k, v = debug.getlocal(realframe, i) end setmetatable(env, {__index = getfenv(funcinfo.func)}) return env, funcinfo, indexmap end function getstack_from(callfile, callline, maxframesz) assert(callfile and callline) local realframe = 0 local framestack = {} local env, funcinfo, indexmap = ltrace_getenv(realframe) while funcinfo do if funcinfo.currentline == callline and funcinfo.short_src == callfile then break end realframe = realframe + 1 env, funcinfo, indexmap = ltrace_getenv(realframe) end while funcinfo do realframe = realframe + 1 env, funcinfo, indexmap = ltrace_getenv(realframe) if not funcinfo then break end table.insert(framestack, { realframe = realframe, env = env, funcinfo = funcinfo, indexmap = indexmap, }) if maxframesz and #framestack >= maxframesz then break end end return framestack end local function get_params(func) if not IS_LUAJIT or _VERSION <= "Lua 5.1" then return {}, -1, false end local info = debug.getinfo(func, "u") if not info then return end local argNameList = {} for i = 1, info.nparams do local name = debug.getlocal(func, i) table.insert(argNameList, name) end if info.isvararg then table.insert(argNameList, "...") end return argNameList, info.nparams, info.isvararg end local uncomparedTypeMap = { ["table"] = true, ["userdata"] = true, ["function"] = true, ["boolean"] = true, ["thread"] = true, } local function compare(a, b) local ta = type(a) local tb = type(b) if ta ~= tb or uncomparedTypeMap[ta] or uncomparedTypeMap[tb] then return tostring(a) < tostring(b) end return a < b end local function pairs_orderly(t, comp) comp = comp or compare local keys = {} for k, v in pairs(t) do table.insert(keys, k) end local size = #keys table.sort(keys, comp) local i = 0 return function(tbl, k) i = i + 1 if i > size then return end return keys[i], t[keys[i]] end end local ignoreMap = { } function dumptable(value, depth) assert(type(value) == "table") local tostr local meta = getmetatable(value) if meta and meta.__tostring then tostr = meta.__tostring elseif value.__tostring then tostr = value.__tostring end if tostr then return tostr(value) end local rettbl = {} depth = (depth or 0) + 1 if depth > mTABLE_MAX_DEEP then return "{...}" end table.insert(rettbl, '{') local content = {} for k, v in pairs_orderly(value) do if not ignoreMap[k] and canPrint(k, v) then local line = {} table.insert(line, dumpkey(k, depth) .. "=") table.insert(line, dumpvalue(v, depth)) table.insert(content, table.concat(line)) end end table.insert(rettbl, table.concat(content, ", ")) table.insert(rettbl, '}') return table.concat(rettbl) end function dumpkey(key, depth) local vtype = type(key) if vtype == "table" then return "[" .. dumptable(key, depth) .. "]" elseif vtype == "string" then if key:match("^%d") or key:match("%w+") ~= key then return "[" .. string.format("%q", key) .. "]" end return tostring(key) end return "[" .. tostring(key) .. "]" end function dumpvalue(v, depth) local vtype = type(v) if vtype == "table" then return dumptable(v, depth) elseif vtype == "string" then return string.format("%q", v) elseif vtype == "number" or vtype == "boolean" then return tostring(v) end return string.format("<%s>", tostring(v)) end function dumpframe(frameidx, env, funcinfo, indexmap) local fix = -1 if funcinfo.what ~= "Lua" then return string.format("%d[C] : in <%s>", frameidx + fix, funcinfo.name or funcinfo.what or funcinfo.namewhat ) end local out = {} local args = get_params(funcinfo.func) local funcstr = "" if funcinfo.name then funcstr = string.format("in <%s(%s)>", funcinfo.name, table.concat(args, ",")) end table.insert(out, string.format("%d @%s:%d %s", frameidx + fix, funcinfo.short_src or "<stdin>", funcinfo.currentline, funcstr)) local valuelines = {} local function compare(k1, k2) return indexmap[k1] < indexmap[k2] end for k, v in pairs_orderly(env, compare) do if canPrint(k, v) then local vs = dumpvalue(v) if #vs > mVALUE_MAX_LEN then vs = vs:sub(1, mVALUE_MAX_LEN) .. "..." end -- table.insert(valuelines, string.format("\t%s<%s>:%s", k, indexmap[k] or "", vs)) table.insert(valuelines, string.format("\t%s:%s", k, vs)) end end table.insert(out, table.concat(valuelines, "\n")) return table.concat(out, "\n") end function dumpstack(stack) local list = {} for i, v in pairs(stack) do local s = dumpframe(i, v.env, v.funcinfo, v.indexmap) table.insert(list, s) end return list end function getstack(level, maxframesz) level = level or 2 local info = debug.getinfo(level, "nlSf") local stacklist = getstack_from(info.short_src, info.currentline, maxframesz) return stacklist end function getfulltrace(level, maxframesz) local fullstack = getstack(level, maxframesz) local list = dumpstack(fullstack) local ret = {} for i, v in pairs(list) do table.insert(ret, v) end return table.concat(ret, "\n") end function settdmaxdeep(depth) mTABLE_MAX_DEEP = depth or mTABLE_MAX_DEEP end function setvdmaxlen(len) mVALUE_MAX_LEN = len or mVALUE_MAX_LEN end traceback.setvdmaxlen = setvdmaxlen traceback.settdmaxdeep = settdmaxdeep traceback.getenv = getenv traceback.getstack_from = getstack_from traceback.getstack = getstack traceback.dumpvalue = dumpvalue traceback.dumptable = dumptable traceback.dumpframe = dumpframe traceback.dumpstack = dumpstack traceback.getfulltrace = getfulltrace return traceback
local main = require(game.Nanoblox) local command = {} command.name = script.Name -- the name used to display and execute the command command.aliases = {} -- additional names (typically shorthand) which activate the command command.description = "" -- a brief description which appears in the menu command.contributors = {} -- the names or IDs or people who developed this command command.opposites = {} -- the names to undo (revoke) the command, e.g. 'invisible' would have 'visible' command.prefixes = {} -- any additional prefixes from the system prefix to activate the command command.tags = {} -- tags associated with commands for grouping and searching; these are also used by roles to inherit commands (e.g. 'level1', 'level2', etc) command.blockPeers = false -- when 'true', prevents users of the same role (i.e. 'peers') executing the command on each other command.blockJuniors = false -- when 'true', prevents users of lower roles (i.e. 'junior') executing the command on higher ('i.e. 'senior') roles command.autoPreview = false -- preview the commands menu before executing command.requiresRig = nil -- e.g. Enum.HumanoidRigType.R15 command.args = {} -- the arguments to be processed and passed through the the command; see the 'Args' module for a list of all arguments function command:invoke(this, caller, args) end function command:revoke(this, caller, args) end return command
return { Name = "setCash"; Aliases = {}; Description = "Sets a player's cash"; Group = "Admin"; Args = { { Type = "player"; Name = "target"; Description = "Player to set"; }, { Type = "integer"; Name = "value"; Description = "Value to set cash to"; Default = 100; }, }; }
------------------------------------------------------------------------------- -- ElvUI Chat Tweaks By Crackpotx (US, Lightbringer) -- Based on functionality provided by Prat and/or Chatter ------------------------------------------------------------------------------- local Module = ElvUI_ChatTweaks:NewModule("Repeat Command", "AceConsole-3.0", "AceTimer-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("ElvUI_ChatTweaks", false) Module.name = L["Repeat Command"] Module.namespace = string.gsub(Module.name, " ", "") local CreateFrame = _G["CreateFrame"] local ClearFocus = _G["ClearFocus"] local IsSecureCmd = _G["IsSecureCmd"] local format = string.format local db, options local defaults = { global = { interval = 1 } } local EditBox = CreateFrame("EditBox", "RepeatCommandEditBox") EditBox:SetAutoFocus(false) EditBox:ClearFocus() function Module:RunCommand(command) if self.repeater and (self.times <= self.maxTimes) then EditBox:SetText(command) ChatEdit_SendText(EditBox) EditBox:Show() self.times = self.times + 1 if self.times == self.maxTimes then self:CancelTimer(self.repeater, true) self.times, self.maxTimes = 0, 0 end end end function Module:OnEnable() self:RegisterChatCommand("rpt", function(args) local rpt, command = args:match("^([^%s]+)%s+(.*)$") rpt = tonumber(rpt) if not rpt or not command or #command == 0 then print(L["|cffffff00Usage: /rpt <times> <command>|r"]) elseif IsSecureCmd(command) then print(format(L["|cffffff00Unable to execute secure command.|r |cffffffff%s|r"], command)) else self.times = 0 self.maxTimes = rpt self.repeater = self:ScheduleRepeatingTimer("RunCommand", db.interval, command) end end) end function Module:OnDisable() self:UnregisterChatCommand("rpt") end function Module:OnInitialize() self.db = ElvUI_ChatTweaks.db:RegisterNamespace(Module.namespace, defaults) db = self.db.global self.debug = ElvUI_ChatTweaks.db.global.debugging end function Module:GetOptions() if not options then options = { interval = { type = "range", name = L["Execution Interval"], desc = L["Time, in seconds, in between running the command."], get = function() return db.interval end, set = function(_, value) db.interval = value end, min = 0.5, max = 60, step = 0.5 } } end return options end function Module:Info() return L["Similar to the |cffffffIn Command|r module, except it will repeat the command X times."] end
local map = {} map.__index = map function map.new(size,world) local self = setmetatable({}, map) self.color = {127,127,127} self.maxtimer = 5 self.timer = 0 self.remove = 1 self.size = size self.world = world self.level = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0}, {0,0,0,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,0,0,0}, {0,0,0,1,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,0,0,0}, {0,0,0,1,2,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,8,8,8,8,8,8,8,8,8,8,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,9,9,9,9,9,9,9,9,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,10,10,10,10,10,10,10,10,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,10,11,11,11,11,11,11,10,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,12,12,12,11,10,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,99,99,12,11,10,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,99,99,12,11,10,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,12,12,12,11,10,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,10,11,11,11,11,11,11,10,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,10,10,10,10,10,10,10,10,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,9,9,9,9,9,9,9,9,9,9,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,8,8,8,8,8,8,8,8,8,8,8,8,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,3,2,1,0,0,0}, {0,0,0,1,2,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,2,1,0,0,0}, {0,0,0,1,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,0,0,0}, {0,0,0,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,0,0,0}, {0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}} self.levelitems = {} for y = 1, #self.level do self.levelitems[y] = {} for x = 1, #self.level do if self.level[y][x] >= 1 then --player name för att det fixar så bullets inte fastnar i marken local item = {name = 'x'..x..'y'..y, playername = 'ground', ground = true} self.levelitems[y][x] = item world:add(item,(x-1)*self.size,(y-1)*self.size,self.size,self.size) end end end return self end function map:update(world,dt) --Gör kartan mindre efter x sekunder self.timer = self.timer + dt if self.timer >= self.maxtimer then for y = 1, #self.level do for x = 1, #self.level do if self.level[y][x] == self.remove and self.levelitems[y][x] ~= nil and self.remove ~= 99 then world:remove(self.levelitems[y][x]) self.levelitems[y][x] = nil self.level[y][x] = -1 end end end self.timer = 0 self.remove = self.remove + 1 end end function map:draw() love.graphics.setColor(self.color) for y = 1, #self.level do for x = 1, #self.level do if self.level[y][x] >= 1 then love.graphics.rectangle('line', (x-1)*self.size, (y-1)*self.size, self.size, self.size) end end end love.graphics.setColor(255,255,255) end return map
-- Detect optional mods. local technic_path = minetest.get_modpath("technic") local chains_path = minetest.get_modpath("chains") if technic_path and chains_path then minetest.register_craft({ output = "elevator:elevator", recipe = { {"technic:cast_iron_ingot", "chains:chain", "technic:cast_iron_ingot"}, {"technic:cast_iron_ingot", "default:mese_crystal", "technic:cast_iron_ingot"}, {"technic:stainless_steel_ingot", "default:glass", "technic:stainless_steel_ingot"}, }, }) minetest.register_craft({ output = "elevator:shaft", recipe = { {"technic:cast_iron_ingot", "default:glass"}, {"default:glass", "glooptest:chainlink"}, }, }) minetest.register_craft({ output = "elevator:motor", recipe = { {"default:diamond", "technic:control_logic_unit", "default:diamond"}, {"default:steelblock", "technic:motor", "default:steelblock"}, {"chains:chain", "default:diamond", "chains:chain"} }, }) elseif technic_path and farming and farming.mod and farming.mod == "redo" then -- add alternative recipe with hemp rope minetest.register_craft({ output = "elevator:elevator", recipe = { {"technic:cast_iron_ingot", "farming:hemp_rope", "technic:cast_iron_ingot"}, {"technic:cast_iron_ingot", "default:mese_crystal", "technic:cast_iron_ingot"}, {"technic:stainless_steel_ingot", "default:glass", "technic:stainless_steel_ingot"}, }, }) minetest.register_craft({ output = "elevator:shaft", recipe = { {"technic:cast_iron_ingot", "default:glass"}, {"default:glass", "farming:hemp_rope"}, }, }) minetest.register_craft({ output = "elevator:motor", recipe = { {"default:diamond", "technic:control_logic_unit", "default:diamond"}, {"default:steelblock", "technic:motor", "default:steelblock"}, {"farming:hemp_rope", "default:diamond", "farming:hemp_rope"} }, }) -- Recipes without technic & chains required. -- Recipes for default dependency fallback. else minetest.register_craft({ output = "elevator:elevator", recipe = { {"default:steel_ingot", "farming:cotton", "default:steel_ingot"}, {"default:steel_ingot", "default:mese_crystal", "default:steel_ingot"}, {"xpanes:pane_flat", "default:glass", "xpanes:pane_flat"}, }, }) minetest.register_craft({ output = "elevator:shaft", recipe = { {"default:steel_ingot", "default:obsidian_glass"}, {"default:obsidian_glass", "default:steel_ingot"}, }, }) minetest.register_craft({ output = "elevator:motor", recipe = { {"default:diamond", "default:copper_ingot", "default:diamond"}, {"default:steelblock", "default:furnace", "default:steelblock"}, {"farming:cotton", "default:diamond", "farming:cotton"} }, }) end
-- Tokenlist.lua local setmetatable = setmetatable local getfenv = getfenv local assert = assert local pairs = pairs local ipairs = ipairs local print = print local tostring = tostring local table = table local string = string local format = string.format local printt = printt module(...) local C = {} local M = setmetatable(getfenv(), C) M.__index = M function C:__call(init) init = init or {} local m = setmetatable(init, M) m.rules = {} m.tokens = {} return m end function M:clear() self.rules = {} self.tokens = {} end function M:append(tok, rule) for i=1, #self.tokens do if( self.tokens[i] == tok and self.rules[i] == rule ) then return end end self.tokens[#self.tokens+1] = tok self.rules[#self.rules+1] = rule end function M:remove(rule) for i=#self.rules, 1, -1 do if(self.rules[i] == rule) then table.remove(self.rules, i) table.remove(self.tokens, i) end end end function M:findtoken(tok) for i=1, #self.tokens do if(self.tokens[i] == tok) then return i end end end function M:token(idx) if(idx < 0) then return self.tokens[#self.tokens+idx+1] else return self.tokens[idx] end end function M:rule(idx) if(idx < 0) then return self.rules[#self.rules+idx+1] else return self.rules[idx] end end function M:print() local len = #self.rules local lenstr = tostring(len) for i=1, len do local istr = tostring(i) local str = string.rep(" ", lenstr:len() - istr:len())..istr str = str.." "..self.tokens[i] str = str..string.rep(" ", 15-self.tokens[i]:len()) str = str..self.rules[i] print(str) end end
module:log("error", "mod_pep_plus has been renamed to mod_pep, please update your config file. Auto-loading mod_pep..."); module:depends("pep");
--- Collisions component. Inherited from @{l2df.class.component|l2df.class.Component} class. -- @classmod l2df.class.component.collision -- @author Abelidze -- @author Kasai -- @copyright Atom-TM 2020 local core = l2df or require(((...):match('(.-)class.+$') or '') .. 'core') assert(type(core) == 'table' and core.version >= 1.0, 'Collisions works only with l2df v1.0 and higher') local helper = core.import 'helper' local Component = core.import 'class.component' local PhysixManager = core.import 'manager.physix' local KindsManager = core.import 'manager.kinds' local sqrt = math.sqrt local min = math.min local max = math.max local copy = helper.copyTable local Collision = Component:extend({ unique = true }) --- Component was added to @{l2df.class.entity|Entity} event. -- @param l2df.class.entity obj Entity's instance. -- @param[opt] table kwargs Keyword arguments. Not actually used. function Collision:added(obj, kwargs) if not obj then return false end kwargs = kwargs or { } local data = obj.data data.itrs = kwargs.itrs or { } data.itrs.___shallow = true data.bodies = kwargs.bodies or { } data.bodies.___shallow = true data.facing = data.facing or 1 data.yorientation = data.yorientation or 1 data.x = data.x or 0 data.y = data.y or 0 data.z = data.z or 0 data.mx = data.mx or 0 data.my = data.my or 0 data.mz = data.mz or 0 data.centerx = data.centerx or 0 data.centery = data.centery or 0 end --- Wrap collider with @{l2df.class.entity|entity} and callback function. -- Generates new @{l2df.manager.physix.Collider|Collider's} table. -- @param l2df.class.entity obj Entity's instance. -- @param table col Collider's description table. -- @param[opt=0] number|string col.kind ID / name of the kind associated with this collider. -- @param[opt=0] number col.x Collider's box X position. -- @param[opt=0] number col.y Collider's box Y position. -- @param[opt=0] number col.z Collider's box Z position. -- @param[opt=0] number col.w Collider's box width. -- @param[opt=0] number col.h Collider's box height. -- @param[opt=0] number col.d Collider's box depth. -- @param[opt] function action Callback called when collider is triggered. -- @return l2df.manager.physix.Collider function Collision:collider(obj, col, action) local data = obj.data --local r = col.r or col.w * col.h * col.d > 0 and sqrt(col.w ^ 2 + col.h ^ 2 + col.d ^ 2) / 2 or 0 local x_1 = data.globalX + (col.x or 0) * data.facing local x_2 = x_1 + (col.w or 0) * data.facing local y_1 = (col.y or 0) - data.globalY * data.yorientation local y_2 = y_1 + (col.h or 0) local z_1 = data.globalZ + (col.z or 0) local z_2 = z_1 + (col.d or 0) local x1 = min(x_1, x_1 + data.mx, x_2, x_2 + data.mx) local x2 = max(x_1, x_1 + data.mx, x_2, x_2 + data.mx) local y1 = min(y_1, y_1 + data.my, y_2, y_2 + data.my) local y2 = max(y_1, y_1 + data.my, y_2, y_2 + data.my) local z1 = min(z_1, z_1 + data.mz, z_2, z_2 + data.mz) local z2 = max(z_1, z_1 + data.mz, z_2, z_2 + data.mz) local collider = copy(col) collider.kind = col.kind or 0 collider.owner = obj collider.data = data collider.col = col collider.action = action collider.w = x2 - x1 collider.h = y2 - y1 collider.d = z2 - z1 collider.x = x1 collider.y = y1 collider.z = z1 return collider end --- Collision update event handler. -- @param l2df.class.entity obj Entity's instance. -- @param number dt Delta-time since last game tick. function Collision:update(obj, dt) local data = obj.data for i = 1, #data.bodies do local bdy = data.bodies[i] local kind = KindsManager:get(bdy.kind) PhysixManager:add('bdy', self:collider(obj, bdy, kind)) end for i = 1, #data.itrs do local itr = data.itrs[i] local kind = KindsManager:get(itr.kind) if kind then PhysixManager:add('itr', self:collider(obj, itr, kind)) end end end return Collision
//________________________________ // // NS2 CustomEntitesMod // Made by JimWest 2012 // //________________________________ // LogicLua.lua // Base entity for LogicLua things Script.Load("lua/ExtraEntitiesMod/LogicMixin.lua") class 'LogicLua' (Entity) LogicLua.kMapName = "logic_lua" local networkVars = { luaFile = "string (128)", } AddMixinNetworkVars(LogicMixin, networkVars) function LogicLua:OnCreate() end function LogicLua:OnInitialized() if Server then InitMixin(self, LogicMixin) end if self.luaFile then Script.Load(self.luaFile) end end function LogicLua:Reset() end Shared.LinkClassToMap("LogicLua", LogicLua.kMapName, networkVars)
--[[--------------------------------------------------------- Name: Setup -----------------------------------------------------------]] TCBScoreboardSettings = TCBScoreboardSettings or {} TCBScoreboardSettings.trans = TCBScoreboardSettings.trans or {} --[[--------------------------------------------------------- Name: Settings -----------------------------------------------------------]] TCBScoreboardSettings.name = "CommunityName - Scoreboard" TCBScoreboardSettings.offlineMdl = "models/player.mdl" TCBScoreboardSettings.useWorkshop = true TCBScoreboardSettings.staffGroups = "superadmin,admin,moderator" TCBScoreboardSettings.staffReplace = {} TCBScoreboardSettings.staffReplace["superadmin"] = "Superadmin" TCBScoreboardSettings.staffReplace["admin"] = "Admin" TCBScoreboardSettings.staffReplace["moderator"] = "Moderator" --[[--------------------------------------------------------- Name: Collection -----------------------------------------------------------]] TCBScoreboardSettings.collectionID = "286538224" --[[--------------------------------------------------------- Name: Translate -----------------------------------------------------------]] TCBScoreboardSettings.trans.online = "Online" TCBScoreboardSettings.trans.friends = "Friends" TCBScoreboardSettings.trans.staff = "Staff" TCBScoreboardSettings.trans.collection = "Steam Collection" TCBScoreboardSettings.trans.refresh = "Refresh" TCBScoreboardSettings.trans.close = "Close" TCBScoreboardSettings.trans.loading = "Loading..." TCBScoreboardSettings.trans.downloading = "Downloading..." TCBScoreboardSettings.trans.mounting = "Mounting..." TCBScoreboardSettings.trans.collection = "Workshop Collection" TCBScoreboardSettings.trans.viewOnline = "View Online" TCBScoreboardSettings.trans.added = "You added % to your friends list!" TCBScoreboardSettings.trans.removed = "You removed % from your friends list!" TCBScoreboardSettings.trans.alreadySubed = "You are already subscribed to this addon!" TCBScoreboardSettings.trans.showPlayers = "Showing % players." TCBScoreboardSettings.trans.showFriends = "Showing % friends." TCBScoreboardSettings.trans.showStaff = "Showing % staff members." TCBScoreboardSettings.trans.showAddons = "Showing % addons." TCBScoreboardSettings.trans.playerOffline = "This player is offline."
--------------------------------------------- -- Dynamic Implosion -- -- Description: Deals Water damage to enemies in a fan-shaped area of effect. Additional effect: STR Down -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local power = 50 local duration = 120 MobStatusEffectMove(mob, target, tpz.effect.STR_DOWN, power, 3, duration) local dmgmod = MobBreathMove(mob, target, 0.1, 1, tpz.magic.ele.FIRE, 200) local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,tpz.attackType.BREATH,tpz.damageType.FIRE,MOBPARAM_IGNORE_SHADOWS) target:takeDamage(dmg, mob, tpz.attackType.BREATH, tpz.damageType.FIRE) return dmg end
--[[ © 2020 TERRANOVA do not share, re-distribute or modify without permission of its author. --]] PLUGIN.name = "Improved Spawnmenu"; PLUGIN.description = "Adds a new admin spawn menu with a better user interface."; PLUGIN.author = "Adolphus"; ix.util.Include("sv_plugin.lua") ix.util.Include("cl_hooks.lua") ix.util.IncludeDir(PLUGIN.folder .. "/commands", true)
local defaults = { debug = {"boolean" , false}, help = {"boolean" , false}, mainserver = {"string" , nil}, mainclient = {"string" , nil}, modules = {"dictionary" , {}}, target = {"string" , nil}, define = {"dictionary", { ErrorStackFrames = 1, EnableBridge = false, EnableModuleTracking = true, Test = false, Benchmark = false, }}, mappings = {"array", { { source = "$sd/../scripts/core", target = "ReplicatedFirst.Core", extension = ".lua", excluded = false, shared = true, }, { source = "$sd/../scripts/server", target = "ServerScriptService.Modules", excluded = true, shared = false, }, { source = "$sd/../scripts/shared", target = "ReplicatedStorage.Modules", excluded = true, shared = true, }, }}, } -- Get build options. local options = ... if type(options) == "string" then -- Load options from file. options = rbxmk.load{...} end if type(options) ~= "table" then error("expected options table") end local handle = { array = function(key, default) local t = {} for _, v in ipairs(default) do table.insert(t, v) end if type(options[key]) == "table" then for _, v in ipairs(options[key]) do table.insert(t, v) end end options[key] = t end, dictionary = function(key, default) local t = {} for k, v in pairs(default) do t[k] = v end if type(options[key]) == "table" then for k, v in pairs(options[key]) do t[k] = v end end options[key] = t end, } -- Merge default options. for name, default in pairs(defaults) do local typ = default[1] local value = default[2] if handle[typ] then handle[typ](name, value) elseif type(options[name]) ~= typ then options[name] = value end end return options
-- AStar -- -- map: -- get_neighbors(node) -- all moveable neighbors -- get_cost(from_node, to_node) -- estimate_cost(start_node, goal_node) -- -- node: -- x: -- y: -- ==: check two node is same local M = {} M.__index = M local private = {} local inf = 1 / 0 function M.new(...) local obj = setmetatable({}, M) obj:init(...) return obj end function M:init(map) self.map = map assert( map.get_neighbors and map.get_cost and map.estimate_cost, "Invalid map, must include get_neighbors, get_cost and estimate_cost functions" ) end -- start: start node -- goal: goal node function M:find(start, goal) local map = self.map local openset = { [start] = true } local closedset = {} local came_from = {} local g_score, h_score, f_score = {}, {}, {} g_score[start] = 0 h_score[start] = map:estimate_cost(start, goal) f_score[start] = h_score[start] while next(openset) do local current = private.pop_best_node(openset, f_score) openset[current] = nil if current == goal then local path = private.unwind_path({}, came_from, goal) table.insert(path, goal) return path, g_score, h_score, f_score end closedset[current] = true local from_node = came_from[current] local neighbors = map:get_neighbors(current, from_node) for _, neighbor in ipairs (neighbors) do if not closedset[neighbor] then local tentative_g_score = g_score[current] + map:get_cost(current, neighbor, from_node) local openset_idx = openset[neighbor] if not openset_idx or tentative_g_score < g_score[neighbor] then came_from[neighbor] = current g_score[neighbor] = tentative_g_score h_score[neighbor] = h_score[neighbor] or map:estimate_cost(neighbor, goal) f_score[neighbor] = tentative_g_score + h_score[neighbor] openset[neighbor] = true end end end end return nil, g_score, h_score, f_score -- no valid path end ---------------------------- -- return: node function private.pop_best_node(set, score) local best, node = inf, nil for k, v in pairs(set) do local s = score[k] if s < best then best, node = s, k end end if not node then return end set[node] = nil return node end function private.unwind_path(flat_path, map, current_node) if map[current_node] then table.insert(flat_path, 1, map [ current_node ]) return private.unwind_path(flat_path, map, map [ current_node ]) else return flat_path end end return M
local ib = require("zenburn.highlights.indent_blankline") return { FocusedSymbol = ib.IndentBlanklineContextCharStart, -- Highlight of the focused symbol -- Pmenu = {}, -- Highlight of the preview popup windows SymbolsOutlineConnector = ib.IndentBlanklineChar, -- Highlight of the table connectors -- Comment = {}, -- Highlight of the info virtual text }
--[[ .---. | | | | | | | | __ | | _ _ .:--.'. | | | ' / | / | \ | | | .' | .' | `" __ | | | | / | / | .'.''| | '---'| `'. | / / | |_ ' .'| '/\ \._,\ '/ `-' `--' `--' `" ]] -- This is a single-line comment. -- printing to console print('hi') -- naturally, prints "hi" to the console -- defining variables x = 12 print(x) -- prints "12" -- you can also declare multiple variables at once a, b, c = "1, 2, 3" -- now variables a, b, and c, are all equal to "1, 2, 3" -- and declare them similarly, but with different values for each a, b, c = 1, 2, 3 -- now a equals 1, b equals 2, and c equals 3 -- logical comparison operators -- == equal to -- ~= not equal to. THIS IS IMPORTANT BECAUSE IT IS WEIRD AND DIFFERENT. PLS PAY ATTENTION TO THIS AND DO NOT FORGET -- <, > less than, greater than -- <=, >= less than or equal to, greater than or equal to -- boolean operators -- not self-explanatory (e.g. not True is False) -- and " " (e.g. True and True is True) -- or " " (e.g. True or False is True) -- some more operators -- .. string concatenation -- # used to get the lengths of tables and strings -- note that there is nothing like, for example, x += 2. you MUST use x = x + 2 instead -- a = b = "Hi" will also not work, use a, b = "Hi" instead -- if/elseif/else cats = 3 if cats == 1 then print("Yep, there's a cat.") elseif cats == 2 then print("There are two cats!") else print("Wow! So many cats!") end -- while loop x = 0 while x < 10 do x = x + 2 print(x) end -- prints "2", then "4", then "6", "8", "10" -- repeat loop (similar to do-while in other languages) i = 5 repeat i = i - 1 print(i) until i == 1 -- NUMERIC for loop x = 1 for i = 1, 11, 2 do x = x * i print(x) end -- GENERIC for loop; see line 133 -- like in python, you can use "break" to end a loop before it normally would; however there is no "continue" -- functions function rofl() print('rolling on the floor laughing') end rofl() -- prints "rolling on the floor laughing" -- local variables must be specifically local, also, YOU CAN RETURN MORE THAN ONE VALUE omg function addThenMultiply(x, y) local addResult = 0 local multResult = 0 addResult = x + y multResult = x * y return addResult, multResult end a, b = addThenMultiply(1, 2) -- a equals 3, b equals 2 -- using default arguments function func(x, y, z) y = y or 0 z = z or 1 end -- now, when called, if no arguments are used for y or z, they will default to 0 and 1, respectively -- you can also use a varying number of arguments function sum(...) local ret = 0 for i, v in ipairs{...} do ret = ret + v end return ret end sum(3, 4, 5, 6) -- 18 -- tables: the only data structure in lua x = 5 a = {} -- empty table b = { key = x, anotherKey = 10 } -- strings as keys c = { [x] = b, ["string"] = 10, [34] = 10, [b] = x } -- variables and literals as keys -- table assignment (using same tables) a[1] = 20 a["foo"] = 50 a[x] = "bar" -- table retrieval (using same tables) print(a["foo"]) print(b["key"]) -- 5 print(c["string"]) -- 10 print(c[34]) -- 10 print(c[b]) -- 5 -- syntax for tables using dots t = { foo = 1, bar = 2 } print(t.foo) -- 1 t.bar = 3 -- you can also use tables like normal arrays lol = {"hi", "hello", "hey"} print(lol[2]) -- note that the dot syntax can not be used here; prints "hello" print(#lol) -- just showing off that # operator real quick; prints "3" -- ALSO NOTE THAT THE INDICES START AT 1, NOT 0. very important -- a very useful feature, you can put functions inside tables. there are two ways t = {} -- normal way: function t.func(self, x, y) self.x = x self.y = y end t.func(t, 1, 1) -- better way: function t:func(x, y) self.x = x self.y = y end t:func(1, 1) -- METATABLES. a table can have a "metatable" with certain items in them; these items will define special aspects of the original table t = {} -- our normal table mt = {} -- our metatable, which contains nothing right now setmetatable(t, mt) -- sets mt to be t's metatable getmetatable(t) -- this will return mt -- you can also use this instead: t = setmetatable({}, {}) -- presuambly this works because setmetatable() returns t -- GENERIC for loop (this one will loop through objects) a = {5, 4, x = 3, 2, 1} -- using pairs() which... does stuff. idk what exactly. but it's necessary for key, val in pairs(a) do print(key, val) end -- this one will print this: -- 1 5 -- 2 4 -- 4 2 -- 5 1 -- x 3 (take notice of the fact that this is last despite being third in the real table) -- using ipairs() which is only for things with indices. it will ignore keys for ind, val in ipairs(a) do print(ind, val) end -- this one prints this: -- 1 5 -- 2 4 -- 4 2 -- 5 1 (take notice of the fact that the one with the key, x, is completely ignored) -- some more detailed information about strings s = "foo\nbar" -- escaping "n" for a new line t = 'he said "hello world"' -- using double quotes inside single ones will make the double ones part of the string u = "Hello \"world\"" -- escaping the double quotes instead v = [[ <html> <body> <p>Hello world!</p> </body> </html> ]] -- this last one is for multi-line strings -- loading other lua files -- this is useful for libraries because it basically treats a lua file as a function -- it even goes as far as being able to return a value with a file! ------------------------- -- -- -- -- MODULES -- -- -- -- ------------------------- -- It's worth noting that you don't have to use any commands to include a standard library module; they're already accessible. ------------------------------ -- -- The table Module -- -- ------------------------------ -- This module adds some nice functions for use with tables. t = { 24, 25, 8, 13, 1, 40 } table.insert(t, 50) -- inserts 50 at end table.insert(t, 3, 89) -- inserts 89 at index 3 table.remove(t, 2) -- removes item at index 2 table.sort(t) -- sorts via the < operator ------------------------------- -- -- The string Module -- -- ------------------------------- -- Adds some helpful functions for strings. string.lower("HeLLO") -- hello string.upper("Hello") -- HELLO string.reverse("world") -- dlrow string.char(87) -- W string.sub("hello world", 2, 5) -- ello -- something about string patterns? the tutorial I'm using doesn't really cover this -- I probably won't need it for LÖVE, but go here, I guess: http://www.lua.org/manual/5.1/manual.html#5.4.1 string.gsub("hello 42", "(%d+)", "%1 3") -- hello 42 3 string.gsub("heLLo", "(%u)", "") -- heo -- 4 + 4 = 8 string.gsub("2 + 2 = 4", "(%d)", function(s) return s * 2 end) -- prints each word for w in string.gmatch("good morning chaps", "%w+") do print(w) end ----------------------------- -- -- The math Module -- -- ----------------------------- --[[ The math module contains many of the mathematical functions you would expect from a language such as math.sin, math.cos, math.floor, etc. There's a few things you'll want to be aware of: math.huge is the largest value a number can be. Although math.floor and math.ceil are present, there's no math.round. Not to worry though, you can easily achieve the same thing with code like math.floor(x + .5). You can use math.random to generate pseudo-random numbers. Before using it, it's a good idea to set the seed with math.randomseed. A common thing to do is math.randomseed(os.time()). ]]
-- Copyright (C) 2017 Afonso Bordado -- -- Licensed under the MIT license <http://opensource.org/licenses/MIT>, -- This file may not be copied, modified, or distributed except according -- to the terms of that license. local llvm = require "llvm" describe("Type module", function () describe("Integer type", function () it("should have constant length", function () local type = llvm.IntType.int1() assert.is_not_nil(type) assert.is.truthy(type:is_sized()) end) it("should allow arbitrary percision", function () local type = llvm.IntType.int(120) assert.is_not_nil(type) assert.is.truthy(type:is_sized()) assert.are.equal(type:get_int_width(), 120) end) it("should be able to create in context", function () local context = llvm.Context.global_context() local type = llvm.IntType.int(120, context) assert.is_not_nil(type) assert.is_not_nil(context) assert.are.equal(context, type:get_context()) local type1 = llvm.IntType.int1(context) assert.is_not_nil(type1) assert.are.equal(context, type1:get_context()) end) end) describe("Floating point type", function () it("should have constant length", function () local type = llvm.FloatType.half() assert.is_not_nil(type) assert.is.truthy(type:is_sized()) end) it("should be able to create in context", function () local context = llvm.Context.global_context() local type = llvm.FloatType.half(context) assert.is_not_nil(type) assert.is_not_nil(context) assert.are.equal(context, type:get_context()) end) end) describe("Function type", function () it("should have constant length", function () local type = llvm.FloatType.half() assert.is_not_nil(type) assert.is.truthy(type:is_sized()) end) end) end) describe("FunctionType module", function () it("should construct correctly", function () local r = llvm.IntType.int1() local v = { llvm.IntType.int8(), llvm.IntType.int16(), } local ftype = llvm.FunctionType.new(r, v, false) assert.is_false(ftype:is_vararg()) assert.are_equal(ftype:count_param_types(), 2) assert.are.same(ftype:param_types(), v) -- TODO: Assert param_types doesen't own its data end) end)
local framework = {} function framework:download() local stable = self:getRelease():getStableVersion() stable:download() end -- LuaClassGen pregenerated functions function framework.new(init) init = init or {} local self={}--vapor.class.download.new(init) self.download=framework.download self._name=init.name self.getName=framework.getName self.setName=framework.setName self._image=init.image self.getImage=framework.getImage self.setImage=framework.setImage self._author=init.author self.getAuthor=framework.getAuthor self.setAuthor=framework.setAuthor self._website=init.website self.getWebsite=framework.getWebsite self.setWebsite=framework.setWebsite self._release=vapor.class.release.new(init.release) self.getRelease=framework.getRelease self.setRelease=framework.setRelease self._exec=init.exec self.getExec=framework.getExec self.setExec=framework.setExec self._execBasedir=init.execBasedir self.getExecBasedir=framework.getExecBasedir self.setExecBasedir=framework.setExecBasedir self._autoBinary=init.autoBinary self.getAutoBinary=framework.getAutoBinary self.setAutoBinary=framework.setAutoBinary self._identifier=init.identifier self.getIdentifier=framework.getIdentifier self.setIdentifier=framework.setIdentifier return self end function framework:getName() return self._name end function framework:setName(val) self._name=val end function framework:getImage() return self._image end function framework:setImage(val) self._image=val end function framework:getAuthor() return self._author end function framework:setAuthor(val) self._author=val end function framework:getWebsite() return self._website end function framework:setWebsite(val) self._website=val end function framework:getRelease() return self._release end function framework:setRelease(val) self._release=val end function framework:getExec() return self._exec end function framework:setExec(val) self._exec=val end function framework:getExecBasedir() return self._execBasedir end function framework:setExecBasedir(val) self._execBasedir=val end function framework:getAutoBinary() return self._autoBinary end function framework:setAutoBinary(val) self._autoBinary=val end function framework:getIdentifier() return self._identifier end function framework:setIdentifier(val) self._identifier=val end return framework
describe("ChainableTemporaryCredentials", function() local AWS = require "resty.aws" local ChainableTemporaryCredentials = require "resty.aws.credentials.ChainableTemporaryCredentials" setup(function() --setup end) teardown(function() --teardown end) describe("new()", function() it("creates a new instance when providing AWS-instance", function() local aws = AWS() local params = {} local creds assert.has.no.error(function() creds = assert(ChainableTemporaryCredentials:new { params = params, aws = aws, }) end) assert.is_function(creds.sts.assumeRole) assert.are.equal(aws.config.credentials, creds.masterCredentials) assert.are.equal(params, creds.params) end) it("accepts params as a single entry array", function() local aws = AWS() local params = {} local creds assert.has.no.error(function() creds = assert(ChainableTemporaryCredentials:new { params = { params }, aws = aws, }) end) assert.is_function(creds.sts.assumeRole) assert.are.equal(aws.config.credentials, creds.masterCredentials) assert.are.equal(params, creds.params) end) it("creates a new instance when providing STS-instance", function() local sts = AWS():STS() local params = {} local creds assert.has.no.error(function() creds = assert(ChainableTemporaryCredentials:new { params = params, sts = sts, }) end) assert.is_function(creds.sts.assumeRole) assert.are.equal(sts.config.credentials, creds.masterCredentials) assert.are.equal(params, creds.params) end) it("creates chained credentials from params-array", function() local aws = AWS() local params_start, params_middle, params_final = {}, {}, {} local creds_final assert.has.no.error(function() creds_final = assert(ChainableTemporaryCredentials:new { params = { params_start, params_middle, params_final }, aws = aws, }) end) assert.are.equal(params_final, creds_final.params) local creds_middle = creds_final.masterCredentials assert.are.equal(params_middle, creds_middle.params) local creds_start = creds_middle.masterCredentials assert.are.equal(params_start, creds_start.params) assert.are.equal(aws.config.credentials, creds_start.masterCredentials) end) end) end)
-- This function set height to the value of z-axis of the water surface. This function works with sea and lake. However it does not work with shallow rivers (e.g. raton canyon will return -100000.0f) note: seems to return true when you are in water -- @module native -- @submodule water -- @see GET_WATER_HEIGHT -- @usage BOOL GET_WATER_HEIGHT(float x, float y, float z, float* height); -- @param x float -- @param y float -- @param z float -- @param height float* -- @return BOOL function GetWaterHeight(x, y, z, height) end -- @todo -- @module native -- @submodule water -- @see GET_WATER_HEIGHT_NO_WAVES -- @usage BOOL GET_WATER_HEIGHT_NO_WAVES(float x, float y, float z, float* height); -- @param x float -- @param y float -- @param z float -- @param height float* -- @return BOOL function GetWaterHeightNoWaves(x, y, z, height) end -- @todo -- @module native -- @submodule water -- @see TEST_PROBE_AGAINST_WATER -- @usage BOOL TEST_PROBE_AGAINST_WATER(float x1, float y1, float z1, float x2, float y2, float z2, Vector3* result); -- @param x1 float -- @param y1 float -- @param z1 float -- @param x2 float -- @param y2 float -- @param z2 float -- @param result Vector3* -- @return BOOL function TestProbeAgainstWater(x1, y1, z1, x2, y2, z2, result) end -- @todo -- @module native -- @submodule water -- @see TEST_PROBE_AGAINST_ALL_WATER -- @usage BOOL TEST_PROBE_AGAINST_ALL_WATER(Any p0, Any p1, Any p2, Any p3, Any p4, Any p5, Any p6, Any p7); -- @param p0 Any -- @param p1 Any -- @param p2 Any -- @param p3 Any -- @param p4 Any -- @param p5 Any -- @param p6 Any -- @param p7 Any -- @return BOOL function TestProbeAgainstAllWater(p0, p1, p2, p3, p4, p5, p6, p7) end -- @todo -- @module native -- @submodule water -- @see TEST_VERTICAL_PROBE_AGAINST_ALL_WATER -- @usage BOOL TEST_VERTICAL_PROBE_AGAINST_ALL_WATER(float x, float y, float z, Any p3, Any* p4); -- @param x float -- @param y float -- @param z float -- @param p3 Any -- @param p4 Any* -- @return BOOL function TestVerticalProbeAgainstAllWater(x, y, z, p3, p4) end -- Sets the water height for a given position and radius. -- @module native -- @submodule water -- @see MODIFY_WATER -- @usage void MODIFY_WATER(float x, float y, float radius, float height); -- @param x float -- @param y float -- @param radius float -- @param height float -- @return void function ModifyWater(x, y, radius, height) end
local t = Def.ActorFrame{} if SN3Debug and (not GAMESTATE:IsCourseMode()) then local yPositions = { PlayerNumber_P1 = SCREEN_TOP+115, PlayerNumber_P2 = SCREEN_BOTTOM-115 } for _,pn in pairs(PlayerNumber) do t[#t+1] = Def.ActorFrame{InitCommand=function(s) s:x(EditWindowPosX()):y(yPositions[pn]) end, LoadActor("edit window", pn)} end end return t
local group = Config.Group -- Check if is decorating -- local IsDecorating = false RegisterNetEvent('qb-anticheat:client:ToggleDecorate') AddEventHandler('qb-anticheat:client:ToggleDecorate', function(bool) IsDecorating = bool end) -- Few frequently used locals -- local flags = 0 local isLoggedIn = false RegisterNetEvent('QBCore:Client:OnPlayerLoaded') AddEventHandler('QBCore:Client:OnPlayerLoaded', function() QBCore.Functions.TriggerCallback('qb-anticheat:server:GetPermissions', function(UserGroup) group = UserGroup end) isLoggedIn = true end) RegisterNetEvent('QBCore:Client:OnPlayerUnload') AddEventHandler('QBCore:Client:OnPlayerUnload', function() isLoggedIn = false IsDecorating = false flags = 0 end) -- Superjump -- Citizen.CreateThread(function() while true do Citizen.Wait(500) local ped = PlayerPedId() local player = PlayerId() if group == Config.Group and isLoggedIn then if IsPedJumping(pedId) then local firstCoord = GetEntityCoords(ped) while IsPedJumping(pedId) do Citizen.Wait(0) end local secondCoord = GetEntityCoords(ped) local lengthBetweenCoords = #(firstCoord - secondCoord) if (lengthBetweenCoords > Config.SuperJumpLength) then flags = flags + 1 TriggerServerEvent("qb-log:server:CreateLog", "anticheat", "Cheat detected!", "orange", "** @everyone " ..GetPlayerName(player).. "** is flagged from anticheat! **(Flag "..flags.." /"..Config.FlagsForBan.." | Superjump)**") end end end end end) -- Speedhack -- Citizen.CreateThread(function() while true do Citizen.Wait(500) local ped = PlayerPedId() local player = PlayerId() local speed = GetEntitySpeed(ped) local inveh = IsPedInAnyVehicle(ped, false) local ragdoll = IsPedRagdoll(ped) local jumping = IsPedJumping(ped) local falling = IsPedFalling(ped) if group == Config.Group and isLoggedIn then if not inveh then if not ragdoll then if not falling then if not jumping then if speed > Config.MaxSpeed then flags = flags + 1 TriggerServerEvent("qb-log:server:CreateLog", "anticheat", "Cheat detected!", "orange", "** @everyone " ..GetPlayerName(player).. "** is flagged from anticheat! **(Flag "..flags.." /"..Config.FlagsForBan.." | Speedhack)**") end end end end end end end end) -- Invisibility -- Citizen.CreateThread(function() while true do Citizen.Wait(10000) local ped = PlayerPedId() local player = PlayerId() if group == Config.Group and isLoggedIn then if not IsDecorating then if not IsEntityVisible(ped) then SetEntityVisible(ped, 1, 0) TriggerEvent('QBCore:Notify', "QB-ANTICHEAT: You were invisible and have been made visible again!") TriggerServerEvent("qb-log:server:CreateLog", "anticheat", "Made player visible", "green", "** @everyone " ..GetPlayerName(player).. "** was invisible and has been made visible again by QB-Anticheat") end end end end end) -- Nightvision -- Citizen.CreateThread(function() while true do Citizen.Wait(2000) local ped = PlayerPedId() local player = PlayerId() if group == Config.Group and isLoggedIn then if GetUsingnightvision(true) then if not IsPedInAnyHeli(ped) then flags = flags + 1 TriggerServerEvent("qb-log:server:CreateLog", "anticheat", "Cheat detected!", "orange", "** @everyone " ..GetPlayerName(player).. "** is flagged from anticheat! **(Flag "..flags.." /"..Config.FlagsForBan.." | Nightvision)**") end end end end end) -- Thermalvision -- Citizen.CreateThread(function() while true do Citizen.Wait(2000) local ped = PlayerPedId() local player = PlayerId() if group == Config.Group and isLoggedIn then if GetUsingseethrough(true) then if not IsPedInAnyHeli(ped) then flags = flags + 1 TriggerServerEvent("qb-log:server:CreateLog", "anticheat", "Cheat detected!", "orange", "** @everyone " ..GetPlayerName(player).. "** is flagged from anticheat! **(Flag "..flags.." /"..Config.FlagsForBan.." | Thermalvision)**") end end end end end) -- Spawned car -- Citizen.CreateThread(function() while true do Citizen.Wait(0) local ped = PlayerPedId() local player = PlayerId() local veh = GetVehiclePedIsIn(ped) local DriverSeat = GetPedInVehicleSeat(veh, -1) local plate = GetVehicleNumberPlateText(veh) if isLoggedIn then if group == Config.Group then if IsPedInAnyVehicle(ped, true) then for _, BlockedPlate in pairs(Config.BlacklistedPlates) do if plate == BlockedPlate then if DriverSeat == ped then DeleteVehicle(veh) TriggerServerEvent("qb-anticheat:server:banPlayer", "Cheating") TriggerServerEvent("qb-log:server:CreateLog", "anticheat", "Cheat detected!", "red", "** @everyone " ..GetPlayerName(player).. "** has been banned for cheating (Sat as driver in spawned vehicle with license plate **"..BlockedPlate..")**") end end end end end end end end) -- Check if ped has weapon in inventory -- Citizen.CreateThread(function() while true do Citizen.Wait(5000) if isLoggedIn then local PlayerPed = PlayerPedId() local player = PlayerId() local CurrentWeapon = GetSelectedPedWeapon(PlayerPed) local WeaponInformation = QBCore.Shared.Weapons[CurrentWeapon] if WeaponInformation["name"] ~= "weapon_unarmed" then QBCore.Functions.TriggerCallback('qb-anticheat:server:HasWeaponInInventory', function(HasWeapon) if not HasWeapon then RemoveAllPedWeapons(PlayerPed, false) TriggerServerEvent("qb-log:server:CreateLog", "anticheat", "Weapon removed!", "orange", "** @everyone " ..GetPlayerName(player).. "** had a weapon on them that they did not have in his inventory. QB Anticheat has removed the weapon.") end end, WeaponInformation) end end end end) -- Max flags reached = ban, log, explosion & break -- Citizen.CreateThread(function() while true do Citizen.Wait(500) local player = PlayerId() if flags >= Config.FlagsForBan then -- TriggerServerEvent("qb-anticheat:server:banPlayer", "Cheating") -- AddExplosion(coords, EXPLOSION_GRENADE, 1000.0, true, false, false, true) TriggerServerEvent("qb-log:server:CreateLog", "anticheat", "Player banned! (Not really of course, this is a test duuuhhhh)", "red", "** @everyone " ..GetPlayerName(player).. "** Too often has been flagged by the anti-cheat and preemptively banned from the server") flags = 0 end end end) RegisterNetEvent('qb-anticheat:client:NonRegisteredEventCalled') AddEventHandler('qb-anticheat:client:NonRegisteredEventCalled', function(reason, CalledEvent) local player = PlayerId() TriggerServerEvent('qb-anticheat:server:banPlayer', reason) TriggerServerEvent("qb-log:server:CreateLog", "anticheat", "Player banned! (Not really of course, this is a test duuuhhhh)", "red", "** @everyone " ..GetPlayerName(player).. "** has event **"..CalledEvent.."tried to trigger (LUA injector!)") end)
-- scaffold geniefile for flatcc flatcc_script = path.getabsolute(path.getdirectory(_SCRIPT)) flatcc_root = path.join(flatcc_script, "flatcc") flatcc_includedirs = { path.join(flatcc_script, "config"), flatcc_root, } flatcc_libdirs = {} flatcc_links = {} flatcc_defines = {} ---- return { _add_includedirs = function() includedirs { flatcc_includedirs } end, _add_defines = function() defines { flatcc_defines } end, _add_libdirs = function() libdirs { flatcc_libdirs } end, _add_external_links = function() links { flatcc_links } end, _add_self_links = function() links { "flatcc" } end, _create_projects = function() project "flatcc" kind "StaticLib" language "C++" flags {} includedirs { flatcc_includedirs, } defines {} files { path.join(flatcc_script, "config", "**.h"), path.join(flatcc_root, "**.h"), path.join(flatcc_root, "**.cpp"), } end, -- _create_projects() } ---
--[[ --==Contributers==-- - Rami Sabbagh (RamiLego4Game) ]] --White color RAM.poke(19203,255) --RED RAM.poke(19204,255) --GREEN RAM.poke(19205,255) --BLUE --Splash Image-- local splash = fs.read("/rom/Boot/Splash.nbin") RAM.memset(0,splash) --Draw the splash Graphics.flip() --File loading functions-- function loadfile(path) if not fs.exists(path) then return error("File doesn't exists !") end if fs.isDir(path) then return error("Can't load a folder !") end local lines = fs.lines(path) local function iter() local line = lines() if line then return line.."\n" end end local ok, chunk = pcall(load,iter,path) if ok then return chunk else return false, chunk end end function dofile(path,...) if not fs.exists(path) then return error("File doesn't exists !") end if fs.isDir(path) then return error("Can't load a folder !") end local lines = fs.lines(path) local function iter() local line = lines() if line then return line.."\n" end end local ok, chunk = pcall(load,iter,path) if not ok then return error(chunk) end local ret = {pcall(chunk,...)} if not ret[1] then return error(ret[2]) end return select(2,unpack(ret)) end --Load the Package System-- dofile("/rom/Boot/package.lua") dofile("/rom/terminal.lua")
local l = require( "acid.logging" ) function test_tostr(t) t:eq( "1 nil", l.tostr( 1, nil ) ) t:eq( "{1,2} {a=3,b={x=4}} nil", l.tostr( {1,2}, {a=3,b={x=4}}, nil ) ) end
--[[-- @package textAdventure @module text.lua @version 1.0 @author Díaz Urbaneja Víctor Eduardo Diex <victor.vector008@gmail.com> @date 12.06.2020 01:14:02 -04 ]] text = {} local colors = { black = '\27[30m', red = '\27[31m', green = '\27[32m', yellow = '\27[33m', blue = '\27[34m', magenta = '\27[35m', cyan = '\27[36m', white = '\27[37m' } --- Imprime en pantalla (message) parseado para la consola -- @tparam string message cadena de texto que desee parsear -- @usage --[[ -- etiquetas disponibles: -- b - negrita -- i - cursiva -- u - subrayado -- s - tachado -- blink - parpadeante -- span - si se coloca el atributo bg='red' el color de fondo del texto será rojo -- ]]-- -- text.parser('<b>texto en negritas</b>') function text.parser(message) local str = message if str:match('<b>(.-)</b>') then message = message:gsub('<b>','\27[1m'):gsub('</b>', '\27[0m') end if str:match('<i>(.-)</i>') then message = message:gsub('<i>','\27[3m'):gsub('</i>', '\27[0m') end if str:match('<u>(.-)</u>') then message = message:gsub('<u>','\27[4m'):gsub('</u>', '\27[0m') end if str:match('<s>(.-)</s>') then message = message:gsub('<s>','\27[9m'):gsub('</s>', '\27[0m') end if str:match('<blink>(.-)</blink>') then message = message:gsub('<blink>','\27[5m'):gsub('</blink>', '\27[0m') end if str:match('<span bg="(.-)">(.-)</span>') then local color, content = str:match('<span bg="(.-)">(.-)</span>') if (color ~= '') then for k, ascii_color in pairs(colors) do if (color == k) then message = message:gsub('<span bg="'.. color ..'">', ascii_color):gsub('</span>', '\27[0m') end end else message = message:gsub('<span bg="'.. color ..'">', ''):gsub('</span>', '\27[0m') end end print(message) end return text
-- Importing modules local Index = require "elasticsearch.endpoints.Index" local parser = require "elasticsearch.parser" local MockTransport = require "lib.MockTransport" local getmetatable = getmetatable -- Setting up environment local _ENV = lunit.TEST_CASE "tests.endpoints.IndexTest" -- Declaring local variables local endpoint local mockTransport = MockTransport:new() -- Testing the constructor function constructorTest() assert_function(Index.new) local o = Index:new() assert_not_nil(o) local mt = getmetatable(o) assert_table(mt) assert_equal(mt, mt.__index) end -- The setup function function setup() endpoint = Index:new{ transport = mockTransport } end -- Testing put request function requestPUTTest() mockTransport.method = "PUT" mockTransport.uri = "/twitter/tweet/1" mockTransport.params = {} mockTransport.body = parser.jsonEncode{ user = "kimchy", post_date = "2009-11-15T14:12:12", message = "trying out Elasticsearch" } endpoint:setParams{ index = "twitter", type = "tweet", id = "1", body = { user = "kimchy", post_date = "2009-11-15T14:12:12", message = "trying out Elasticsearch" } } endpoint.endpointParams.createIfAbsent = false local _, err = endpoint:request() assert_nil(err) end -- Testing post request function requestPOSTTest() mockTransport.method = "POST" mockTransport.uri = "/twitter/tweet" mockTransport.params = {} mockTransport.body = parser.jsonEncode{ user = "kimchy", post_date = "2009-11-15T14:12:12", message = "trying out Elasticsearch" } endpoint:setParams{ index = "twitter", type = "tweet", body = { user = "kimchy", post_date = "2009-11-15T14:12:12", message = "trying out Elasticsearch" } } endpoint.endpointParams.createIfAbsent = false local _, err = endpoint:request() assert_nil(err) end -- Testing create request function requestCreateTest() mockTransport.method = "PUT" mockTransport.uri = "/twitter/tweet/1/_create" mockTransport.params = {} mockTransport.body = parser.jsonEncode{ user = "kimchy", post_date = "2009-11-15T14:12:12", message = "trying out Elasticsearch" } endpoint:setParams{ index = "twitter", type = "tweet", id = "1", body = { user = "kimchy", post_date = "2009-11-15T14:12:12", message = "trying out Elasticsearch" } } endpoint.endpointParams.createIfAbsent = true local _, err = endpoint:request() assert_nil(err) end -- Testing create request function requestCreateTest() mockTransport.method = "POST" mockTransport.uri = "/twitter/tweet" mockTransport.params = { op_type = "create" } mockTransport.body = parser.jsonEncode{ user = "kimchy", post_date = "2009-11-15T14:12:12", message = "trying out Elasticsearch" } endpoint:setParams{ index = "twitter", type = "tweet", body = { user = "kimchy", post_date = "2009-11-15T14:12:12", message = "trying out Elasticsearch" } } endpoint.endpointParams.createIfAbsent = true local _, err = endpoint:request() assert_nil(err) end
-- Editors: -- MouJiaoZi, 15.12.2017 LinkLuaModifier("modifier_imba_enigma_generic_pull","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) function CalculatePullLength(caster, target, length) if not IsServer() then return end local son = caster:FindAbilityByName("imba_enigma_demonic_conversion") iLenght = length if son then local debuff = target:FindModifierByName("modifier_imba_enigma_eidolon_attack_counter") if debuff then iLenght = iLenght * (1 + son:GetSpecialValueFor("increased_mass_pull_pct") * 0.01 * debuff:GetStackCount()) end end return iLenght end function SearchForEngimaThinker(caster, victim, length, talent) if not IsServer() then return end talent = talent or false local Black_Hole = caster:FindAbilityByName("imba_enigma_black_hole") local hThinker = caster -- enigma self if talent then -- talent local Thinkers = FindUnitsInRadius(victim:GetTeamNumber(), victim:GetAbsOrigin(), nil, 9999999, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_CLOSEST, false) for _,thinker in pairs(Thinkers) do if thinker:FindModifierByNameAndCaster("modifier_imba_enigma_malefice", caster) and thinker ~= victim then hThinker = thinker break end end end local Thinkers = FindUnitsInRadius(caster:GetTeamNumber(), victim:GetAbsOrigin(), nil, 9999999, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_ALL, DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_CLOSEST, false) for _,thinker in pairs(Thinkers) do -- midnight if thinker:GetUnitName() == "npc_dummy_unit" and thinker.midnight == true then hThinker = thinker break end end if Black_Hole.thinker and not Black_Hole.thinker:IsNull() then hThinker = Black_Hole.thinker end -- black hole iLenght = CalculatePullLength(caster, victim, length) victim:AddNewModifier(caster, nil, "modifier_imba_enigma_generic_pull", {duration = 1.0, target = hThinker:entindex(), length = iLenght}) end modifier_imba_enigma_generic_pull = modifier_imba_enigma_generic_pull or class({}) function modifier_imba_enigma_generic_pull:IsDebuff() return false end function modifier_imba_enigma_generic_pull:IsHidden() return true end function modifier_imba_enigma_generic_pull:IsPurgable() return true end function modifier_imba_enigma_generic_pull:IsStunDebuff() return false end function modifier_imba_enigma_generic_pull:IsMotionController() return true end function modifier_imba_enigma_generic_pull:GetMotionControllerPriority() return DOTA_MOTION_CONTROLLER_PRIORITY_LOWEST end function modifier_imba_enigma_generic_pull:OnCreated(keys) if not IsServer() then return end if keys.target then self.target = EntIndexToHScript(keys.target) end self.target = self.target or self:GetCaster() self.length = keys.length self:StartIntervalThink(FrameTime()) end function modifier_imba_enigma_generic_pull:OnRefresh(keys) if not IsServer() then return end self:OnCreated(keys) end function modifier_imba_enigma_generic_pull:OnIntervalThink() if not self:CheckMotionControllers() then self:Destroy() return end self:HorizontalMotion(self:GetParent(), FrameTime()) end function modifier_imba_enigma_generic_pull:HorizontalMotion(unit, time) local length = self.length / (1.0 / FrameTime()) if not self.target or self.target:IsNull() then self.target = self:GetCaster() end local pos = self:GetParent():GetAbsOrigin() local tar_pos = self.target:GetAbsOrigin() local next_pos = GetGroundPosition((pos + (tar_pos - pos):Normalized() * length), unit) unit:SetAbsOrigin(next_pos) ResolveNPCPositions(self:GetParent():GetAbsOrigin(), 128) end function modifier_imba_enigma_generic_pull:OnDestroy() if not IsServer() then return end ResolveNPCPositions(self:GetParent():GetAbsOrigin(), 128) end LinkLuaModifier("modifier_enigma_magic_immunity","components/abilities/heroes/hero_enigma",LUA_MODIFIER_MOTION_NONE) modifier_enigma_magic_immunity = class({}) function modifier_enigma_magic_immunity:IsDebuff() return false end function modifier_enigma_magic_immunity:IsHidden() return false end function modifier_enigma_magic_immunity:GetTexture() return "enigma_demonic_conversion" end function modifier_enigma_magic_immunity:CheckState() return {[MODIFIER_STATE_MAGIC_IMMUNE] = true} end function modifier_enigma_magic_immunity:GetEffectName() return "particles/hero/enigma/enigma_magic_immunity.vpcf" end function modifier_enigma_magic_immunity:GetEffectAttachType() return PATTACH_ABSORIGIN_FOLLOW end function SetTalentSpellImmunity(caster) local modifier = caster:FindModifierByName("modifier_enigma_magic_immunity") if modifier then local time = modifier:GetRemainingTime() + caster:FindTalentValue("special_bonus_imba_enigma_7") modifier:SetDuration(time,true) else caster:AddNewModifier(caster,nil,"modifier_enigma_magic_immunity",{duration = caster:FindTalentValue("special_bonus_imba_enigma_7")}) end end LinkLuaModifier("modifier_special_bonus_imba_enigma_7", "components/abilities/heroes/hero_enigma.lua", LUA_MODIFIER_MOTION_NONE) modifier_special_bonus_imba_enigma_7 = modifier_special_bonus_imba_enigma_7 or class({}) function modifier_special_bonus_imba_enigma_7:IsHidden() return false end function modifier_special_bonus_imba_enigma_7:RemoveOnDeath() return false end -- gain spell immune when casting function modifier_special_bonus_imba_enigma_7:DeclareFunctions() local funcs = { MODIFIER_EVENT_ON_ABILITY_START, } return funcs end function modifier_special_bonus_imba_enigma_7:OnAbilityStart(keys) if keys.unit == self:GetParent() then SetTalentSpellImmunity(self:GetParent()) end end --================================================================================================================= -- Enigma's Malefice --================================================================================================================= imba_enigma_malefice = imba_enigma_malefice or class({}) LinkLuaModifier("modifier_imba_enigma_malefice","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_special_bonus_imba_enigma_2","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) function imba_enigma_malefice:IsHiddenWhenStolen() return false end function imba_enigma_malefice:IsRefreshable() return true end function imba_enigma_malefice:IsStealable() return true end function imba_enigma_malefice:IsNetherWardStealable() return false end function imba_enigma_malefice:OnOwnerSpawned() if not IsServer() then return end if self:GetCaster():HasAbility("special_bonus_imba_enigma_2") and self:GetCaster():FindAbilityByName("special_bonus_imba_enigma_2"):IsTrained() and not self:GetCaster():HasModifier("modifier_special_bonus_imba_enigma_2") then self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_special_bonus_imba_enigma_2", {}) end end function imba_enigma_malefice:GetAOERadius() if self:GetCaster():HasTalent("special_bonus_imba_enigma_2") then return self:GetCaster():FindTalentValue("special_bonus_imba_enigma_2") else return 0 end end function imba_enigma_malefice:OnSpellStart() local caster = self:GetCaster() local target = self:GetCursorTarget() if target:TriggerSpellAbsorb(self) then return end local ability = self local base_duration = ability:GetSpecialValueFor("total_duration") local hp_extra_duration = ability:GetSpecialValueFor("health_bonus_duration") local pct_per_extra = ability:GetSpecialValueFor("health_bonus_duration_percent") local function CalculateDuration(unit) local hp_pct = unit:GetHealthPercent() local total_duration = base_duration total_duration = total_duration + hp_extra_duration * math.floor((100-hp_pct)/pct_per_extra) return total_duration end if not caster:HasTalent("special_bonus_imba_enigma_2") then local final_duration = CalculateDuration(target) target:AddNewModifier(caster, ability, "modifier_imba_enigma_malefice", {duration = final_duration}) else local talent_radius = caster:FindTalentValue("special_bonus_imba_enigma_2") local enemies = FindUnitsInRadius(caster:GetTeamNumber(), target:GetAbsOrigin(), nil, talent_radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false) for _, enemy in pairs(enemies) do local final_duration = CalculateDuration(enemy) enemy:AddNewModifier(caster, ability, "modifier_imba_enigma_malefice", {duration = final_duration}) end end end modifier_imba_enigma_malefice = modifier_imba_enigma_malefice or class({}) function modifier_imba_enigma_malefice:IsDebuff() return true end function modifier_imba_enigma_malefice:IsHidden() return false end function modifier_imba_enigma_malefice:IsPurgable() return true end function modifier_imba_enigma_malefice:IsStunDebuff() return false end function modifier_imba_enigma_malefice:GetEffectName() return "particles/units/heroes/hero_enigma/enigma_malefice.vpcf" end function modifier_imba_enigma_malefice:OnCreated() if not IsServer() then return end local caster = self:GetCaster() local target = self:GetParent() local ability = self:GetAbility() self.interval = ability:GetSpecialValueFor("tick_interval") self.dmg = ability:GetSpecialValueFor("tick_damage") self.stun_duration = ability:GetSpecialValueFor("stun_duration") self:StartIntervalThink(self.interval) self:OnIntervalThink() end function modifier_imba_enigma_malefice:OnIntervalThink() local caster = self:GetCaster() local target = self:GetParent() local ability = self:GetAbility() local damageTable = {victim = self:GetParent(), attacker = self:GetCaster(), damage = self.dmg, damage_type = DAMAGE_TYPE_MAGICAL, ability = ability} ApplyDamage(damageTable) target:AddNewModifier(caster, ability, "modifier_stunned", {duration = self.stun_duration}) EmitSoundOn("Hero_Enigma.MaleficeTick", target) SearchForEngimaThinker(caster, self:GetParent(), ability:GetSpecialValueFor("pull_strength")) end --================================================================================================================= -- Enigma's Demonic Conversion --================================================================================================================= imba_enigma_demonic_conversion = imba_enigma_demonic_conversion or class({}) LinkLuaModifier("modifier_imba_enigma_eidolon","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_imba_enigma_eidolon_attack_counter","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_imba_enigma_eidolon_attacks_debuff","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) function imba_enigma_demonic_conversion:CastFilterResultTarget(target) if IsServer() then local caster = self:GetCaster() -- #8 Talent: Cast Eidolons on heroes if caster:HasTalent("special_bonus_imba_enigma_8") and target:IsRealHero() then return UF_SUCCESS end local nResult = UnitFilter(target, self:GetAbilityTargetTeam(), self:GetAbilityTargetType(), self:GetAbilityTargetFlags(), self:GetCaster():GetTeamNumber()) return nResult end end function imba_enigma_demonic_conversion:OnSpellStart() local ability = self local caster = self:GetCaster() local target = self:GetCursorTarget() if target:GetTeamNumber() ~= caster:GetTeamNumber() then if target:TriggerSpellAbsorb(self) then return end end local location = target:GetAbsOrigin() EmitSoundOn("Hero_Enigma.Demonic_Conversion",target) if not target:IsHero() then target:Kill(ability, caster) target = nil end local eidolon_count = ability:GetSpecialValueFor("eidolon_count") + caster:FindTalentValue("special_bonus_imba_enigma_6") if eidolon_count > 0 then for i=1,eidolon_count do ability:CreateEidolon(target, location, 1, ability:GetSpecialValueFor("duration")) end end end function imba_enigma_demonic_conversion:CreateEidolon(hParent, vLocation, iWave, fDuration) local caster = self:GetCaster() hParent = hParent or caster local eidolon = CreateUnitByName("npc_imba_enigma_eidolon_"..math.min(4,self:GetLevel()), vLocation, true, caster, caster, caster:GetTeamNumber()) eidolon:AddNewModifier(caster, self, "modifier_kill", {duration = fDuration}) eidolon:SetOwner(caster) eidolon:SetControllableByPlayer(caster:GetPlayerID(), true) eidolon:SetUnitOnClearGround() local attacks_needed = self:GetSpecialValueFor("attacks_to_split") + self:GetSpecialValueFor("additional_attacks_split") * (iWave - 1) eidolon:AddNewModifier(caster, self, "modifier_imba_enigma_eidolon", {duration = fDuration, wave = iWave, parent = hParent:entindex(), stack = attacks_needed}) end modifier_imba_enigma_eidolon = modifier_imba_enigma_eidolon or class({}) function modifier_imba_enigma_eidolon:IsDebuff() return true end function modifier_imba_enigma_eidolon:IsHidden() return true end function modifier_imba_enigma_eidolon:IsPurgable() return false end function modifier_imba_enigma_eidolon:IsPurgeException() return false end function modifier_imba_enigma_eidolon:IsStunDebuff() return false end function modifier_imba_enigma_eidolon:RemoveOnDeath() return true end function modifier_imba_enigma_eidolon:DeclareFunctions() local funcs = { MODIFIER_EVENT_ON_ATTACK_LANDED, MODIFIER_PROPERTY_EXTRA_HEALTH_BONUS, MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS, MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE, MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT, MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT, } return funcs end function modifier_imba_enigma_eidolon:OnCreated( keys ) self.attacks = keys.stack self.last_target = self:GetParent() local ability = self:GetAbility() if keys.parent then self.parent = EntIndexToHScript(keys.parent) end self.parent = self.parent or self:GetCaster() self.trans_pct = ability:GetSpecialValueFor("shard_percentage") self.wave = keys.wave end function modifier_imba_enigma_eidolon:GetModifierExtraHealthBonus() if IsServer() then return self.parent:GetMaxHealth() * self.trans_pct * 0.01 end end function modifier_imba_enigma_eidolon:GetModifierPhysicalArmorBonus() return self.parent:GetPhysicalArmorValue() * self.trans_pct * 0.01 end function modifier_imba_enigma_eidolon:GetModifierMoveSpeedBonus_Constant() return self.parent:GetIdealSpeed() * self.trans_pct * 0.01 end function modifier_imba_enigma_eidolon:GetModifierAttackSpeedBonus_Constant() if self.parent:HasModifier("modifier_imba_echo_rapier_haste") and IsServer() then local echo_buf = self.parent:FindModifierByName("modifier_imba_echo_rapier_haste") return (self.parent:GetAttackSpeed() - echo_buf.attack_speed_buff) * self.trans_pct * 0.01 end return self.parent:GetAttackSpeed() * self.trans_pct * 0.01 end function modifier_imba_enigma_eidolon:GetModifierPreAttack_BonusDamage() if IsServer() then local attack = self.trans_pct * self.parent:GetAverageTrueAttackDamage(self.parent) self:SetStackCount(attack) end local number = self:GetStackCount() * 0.01 return number end function modifier_imba_enigma_eidolon:OnAttackLanded(keys) if not IsServer() then return end if keys.attacker == self:GetParent() and not keys.target:IsBuilding() then if self:GetParent():GetTeamNumber() ~= keys.target:GetTeamNumber() then local target = keys.target if not target:HasModifier("modifier_imba_enigma_eidolon_attack_counter") then target:AddNewModifier(self:GetParent(), self:GetAbility(), "modifier_imba_enigma_eidolon_attack_counter", {}) end if not self:GetParent():IsNull() and not self.last_target:IsNull() and self.last_target:FindModifierByNameAndCaster("modifier_imba_enigma_eidolon_attacks_debuff", self:GetParent()) then self.last_target:FindModifierByNameAndCaster("modifier_imba_enigma_eidolon_attacks_debuff", self:GetParent()):Destroy() end self.last_target = target target:AddNewModifier(self:GetParent(), self:GetAbility(), "modifier_imba_enigma_eidolon_attacks_debuff", {duration = self:GetAbility():GetSpecialValueFor("increased_mass_duration")}) end if self.attacks > 1 then self.attacks = self.attacks - 1 else self:GetAbility():CreateEidolon(self.parent, self:GetParent():GetAbsOrigin(), self.wave + 1, self:GetRemainingTime() + self:GetAbility():GetSpecialValueFor("child_duration")) self:GetAbility():CreateEidolon(self.parent, self:GetParent():GetAbsOrigin(), self.wave + 1, self:GetRemainingTime() + self:GetAbility():GetSpecialValueFor("child_duration")) self:GetParent():ForceKill(false) end end end modifier_imba_enigma_eidolon_attack_counter = modifier_imba_enigma_eidolon_attack_counter or class({}) modifier_imba_enigma_eidolon_attacks_debuff = modifier_imba_enigma_eidolon_attacks_debuff or class({}) function modifier_imba_enigma_eidolon_attack_counter:IsDebuff() return true end function modifier_imba_enigma_eidolon_attack_counter:IsHidden() return false end function modifier_imba_enigma_eidolon_attack_counter:IsPurgable() return true end function modifier_imba_enigma_eidolon_attack_counter:IsPurgeException() return true end function modifier_imba_enigma_eidolon_attack_counter:IsStunDebuff() return false end function modifier_imba_enigma_eidolon_attack_counter:RemoveOnDeath() return true end function modifier_imba_enigma_eidolon_attack_counter:OnCreated() if not IsServer() then return end self:StartIntervalThink(0.1) end function modifier_imba_enigma_eidolon_attack_counter:OnIntervalThink() local debuffs = self:GetParent():FindAllModifiersByName("modifier_imba_enigma_eidolon_attacks_debuff") if #debuffs > 0 then self:SetStackCount(#debuffs) else self:Destroy() end end function modifier_imba_enigma_eidolon_attacks_debuff:IsDebuff() return true end function modifier_imba_enigma_eidolon_attacks_debuff:IsHidden() return true end function modifier_imba_enigma_eidolon_attacks_debuff:IsPurgable() return true end function modifier_imba_enigma_eidolon_attacks_debuff:IsPurgeException() return true end function modifier_imba_enigma_eidolon_attacks_debuff:IsStunDebuff() return false end function modifier_imba_enigma_eidolon_attacks_debuff:RemoveOnDeath() return true end function modifier_imba_enigma_eidolon_attacks_debuff:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end --================================================================================================================= -- Enigma's Midnight Pulse --================================================================================================================= imba_enigma_midnight_pulse = imba_enigma_midnight_pulse or class({}) LinkLuaModifier("modifier_imba_enigma_midnight_pulse_thinker","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_imba_enigma_midnight_pulse_aura","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) function imba_enigma_midnight_pulse:GetAOERadius() return self:GetSpecialValueFor("radius") end function imba_enigma_midnight_pulse:OnSpellStart() local caster = self:GetCaster() local point = self:GetCursorPosition() local duration = self:GetSpecialValueFor("duration") local damage_per_tick = self:GetSpecialValueFor("damage_per_tick") local radius = self:GetSpecialValueFor("radius") EmitSoundOnLocationWithCaster(point,"Hero_Enigma.Midnight_Pulse",caster) GridNav:DestroyTreesAroundPoint(point, radius, false) CreateModifierThinker(caster, self, "modifier_imba_enigma_midnight_pulse_thinker", {duration = duration}, point, caster:GetTeamNumber(), false) end modifier_imba_enigma_midnight_pulse_thinker = modifier_imba_enigma_midnight_pulse_thinker or class({}) function modifier_imba_enigma_midnight_pulse_thinker:IsAura() return true end function modifier_imba_enigma_midnight_pulse_thinker:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_ENEMY end function modifier_imba_enigma_midnight_pulse_thinker:GetAuraSearchFlags() return DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES end function modifier_imba_enigma_midnight_pulse_thinker:GetAuraSearchType() return DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO end function modifier_imba_enigma_midnight_pulse_thinker:GetAuraRadius() return self.radius end function modifier_imba_enigma_midnight_pulse_thinker:GetModifierAura() return "modifier_imba_enigma_midnight_pulse_aura" end function modifier_imba_enigma_midnight_pulse_thinker:OnCreated(keys) if not IsServer() then return end local caster = self:GetCaster() local findDummy = CreateUnitByName("npc_dummy_unit", self:GetParent():GetAbsOrigin(), false, caster, caster, caster:GetTeamNumber()) findDummy.midnight = true findDummy:AddNewModifier(caster, nil, "modifier_kill", {duration = self:GetDuration()}) self.radius = self:GetAbility():GetSpecialValueFor("radius") self.pull_length = self:GetAbility():GetSpecialValueFor("pull_strength") self:StartIntervalThink(1.0) self.particle = ParticleManager:CreateParticle("particles/units/heroes/hero_enigma/enigma_midnight_pulse.vpcf",PATTACH_ABSORIGIN_FOLLOW,self:GetParent()) ParticleManager:SetParticleControl(self.particle,0,self:GetParent():GetAbsOrigin()) ParticleManager:SetParticleControl(self.particle,1,Vector(self.radius,0,0)) end function modifier_imba_enigma_midnight_pulse_thinker:OnIntervalThink() local caster = self:GetCaster() local parent = self:GetParent() local ability = self:GetAbility() GridNav:DestroyTreesAroundPoint(parent:GetAbsOrigin(), self.radius, false) local dmg_pct = ability:GetSpecialValueFor("damage_per_tick") * 0.01 local enemies = FindUnitsInRadius(caster:GetTeamNumber(), parent:GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_ANY_ORDER, false) for _, enemy in pairs(enemies) do local dmg = enemy:GetMaxHealth() * dmg_pct local damageTable = {victim = enemy, attacker = caster, damage = dmg, damage_type = DAMAGE_TYPE_PURE, damage_flags = DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION, ability = ability} ApplyDamage(damageTable) SearchForEngimaThinker(caster, enemy, self.pull_length) end local eidolons = FindUnitsInRadius(caster:GetTeamNumber(), parent:GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_FRIENDLY, DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false) for _, eidolon in pairs(eidolons) do if eidolon:HasModifier("modifier_imba_enigma_eidolon") then eidolon:Heal(ability:GetSpecialValueFor("eidolon_hp_regen"), nil) SendOverheadEventMessage(nil, OVERHEAD_ALERT_HEAL, eidolon, ability:GetSpecialValueFor("eidolon_hp_regen"), nil) end end -- growable radius talent if caster:HasTalent("special_bonus_imba_enigma_3") then self.radius = self.radius + ability:GetSpecialValueFor("radius") / ability:GetSpecialValueFor("duration") ParticleManager:SetParticleControl(self.particle,1,Vector(self.radius,0,0)) end end function modifier_imba_enigma_midnight_pulse_thinker:OnDestroy() if not IsServer() then return end ParticleManager:DestroyParticle(self.particle,false) ParticleManager:ReleaseParticleIndex(self.particle) end modifier_imba_enigma_midnight_pulse_aura = modifier_imba_enigma_midnight_pulse_aura or class({}) function modifier_imba_enigma_midnight_pulse_aura:IsDebuff() return true end function modifier_imba_enigma_midnight_pulse_aura:IsHidden() return false end function modifier_imba_enigma_midnight_pulse_aura:IsPurgable() return false end function modifier_imba_enigma_midnight_pulse_aura:IsPurgeException() return false end function modifier_imba_enigma_midnight_pulse_aura:GetTexture() return "enigma_midnight_pulse" end --================================================================================================================= -- Enigma's Black Hole --================================================================================================================= imba_enigma_black_hole = imba_enigma_black_hole or class({}) LinkLuaModifier("modifier_imba_enigma_black_hole_thinker","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_imba_enigma_black_hole","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) --Auctually enemies' buff LinkLuaModifier("modifier_imba_enigma_black_hole_pull","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_imba_singularity","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_special_bonus_imba_enigma_1","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_special_bonus_imba_enigma_5","components/abilities/heroes/hero_enigma", LUA_MODIFIER_MOTION_NONE) function imba_enigma_black_hole:IsHiddenWhenStolen() return false end function imba_enigma_black_hole:IsRefreshable() return true end function imba_enigma_black_hole:IsStealable() return true end function imba_enigma_black_hole:IsNetherWardStealable() return true end function imba_enigma_black_hole:OnOwnerSpawned() if not IsServer() then return end if self:GetCaster():HasAbility("special_bonus_imba_enigma_1") and self:GetCaster():FindAbilityByName("special_bonus_imba_enigma_1"):IsTrained() and not self:GetCaster():HasModifier("modifier_special_bonus_imba_enigma_1") then self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_special_bonus_imba_enigma_1", {}) end if self:GetCaster():HasAbility("special_bonus_imba_enigma_5") and self:GetCaster():FindAbilityByName("special_bonus_imba_enigma_5"):IsTrained() and not self:GetCaster():HasModifier("modifier_special_bonus_imba_enigma_5") then self:GetCaster():AddNewModifier(self:GetCaster(), self, "modifier_special_bonus_imba_enigma_5", {}) end end function imba_enigma_black_hole:GetCastRange(vLocation, hTarget) return self:GetSpecialValueFor("cast_range") + self:GetCaster():FindTalentValue("special_bonus_imba_enigma_5") end function imba_enigma_black_hole:GetCooldown(nLevel) local charges = self:GetCaster():GetModifierStackCount("modifier_imba_singularity", self:GetCaster()) return math.max(30, self.BaseClass.GetCooldown( self, nLevel ) - charges * self:GetCaster():FindTalentValue("special_bonus_imba_enigma_1")) end function imba_enigma_black_hole:GetIntrinsicModifierName() return "modifier_imba_singularity" end function imba_enigma_black_hole:GetAOERadius() return self:GetSpecialValueFor("radius") + self:GetCaster():GetModifierStackCount("modifier_imba_singularity", self:GetCaster()) * self:GetSpecialValueFor("singularity_stun_radius_increment_per_stack") end function imba_enigma_black_hole:OnSpellStart() local caster = self:GetCaster() local pos = self:GetCursorPosition() local ability = self local base_radius = self:GetSpecialValueFor("radius") local extar_radius = self:GetSpecialValueFor("singularity_stun_radius_increment_per_stack") local base_pull_radius = self:GetSpecialValueFor("pull_radius") local extra_pull_radius = self:GetSpecialValueFor("singularity_pull_radius_increment_per_stack") self.radius = base_radius + extar_radius * caster:FindModifierByName("modifier_imba_singularity"):GetStackCount() self.pull_radius = base_pull_radius + extra_pull_radius * caster:FindModifierByName("modifier_imba_singularity"):GetStackCount() local duration = self:GetSpecialValueFor("duration") self.thinker = CreateModifierThinker(caster, self, "modifier_imba_enigma_black_hole_thinker", {duration = duration}, pos, caster:GetTeamNumber(), false) end function imba_enigma_black_hole:OnChannelFinish( bInterrupted ) StopSoundOn("Hero_Enigma.Black_Hole", self.thinker) StopSoundOn("Imba.EnigmaBlackHoleTi5", self.thinker) if bInterrupted then self.thinker:FindModifierByName("modifier_imba_enigma_black_hole_thinker"):Destroy() self:GetCaster():FindModifierByName("modifier_imba_singularity"):SetStackCount(0) end end modifier_imba_enigma_black_hole_thinker = modifier_imba_enigma_black_hole_thinker or class({}) modifier_imba_enigma_black_hole = modifier_imba_enigma_black_hole or class({}) modifier_imba_enigma_black_hole_pull = modifier_imba_enigma_black_hole_pull or class({}) function modifier_imba_enigma_black_hole_thinker:IsAura() return true end function modifier_imba_enigma_black_hole_thinker:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_ENEMY end function modifier_imba_enigma_black_hole_thinker:GetAuraSearchType() return DOTA_UNIT_TARGET_BASIC + DOTA_UNIT_TARGET_HERO end function modifier_imba_enigma_black_hole_thinker:GetAuraSearchFlags() return DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES end function modifier_imba_enigma_black_hole_thinker:GetAuraRadius() return self.radius end function modifier_imba_enigma_black_hole_thinker:GetModifierAura() return "modifier_imba_enigma_black_hole" end function modifier_imba_enigma_black_hole_thinker:OnCreated(keys) self.singularity_cap = self:GetAbility():GetSpecialValueFor("singularity_cap") self.radius = self:GetAbility().radius self.pull_radius = self:GetAbility().pull_radius if not IsServer() then return end local pfx_name = "particles/hero/enigma/enigma_blackhole_scaleable.vpcf" self.sound = "Hero_Enigma.Black_Hole" local total = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, 999999, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_DEAD + DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_ANY_ORDER, false) local enemies = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_NOT_ILLUSIONS, FIND_ANY_ORDER, false) if #enemies >= #total/2 then pfx_name = "particles/hero/enigma/enigma_blackhole_ti5_scaleable.vpcf" self.sound = "Imba.EnigmaBlackHoleTi5" EmitSoundOn("Imba.EnigmaBlackHoleTobi0"..math.random(1,5), self:GetParent()) self.pfx_ulti = ParticleManager:CreateParticle("particles/econ/items/slark/slark_ti6_blade/slark_ti6_pounce_leash_gold_body_energy_pull.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetCaster()) ParticleManager:SetParticleControlEnt(self.pfx_ulti, 0, self:GetCaster(), PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", self:GetCaster():GetAbsOrigin(), false) ParticleManager:SetParticleControlEnt(self.pfx_ulti, 1, self:GetCaster(), PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", self:GetCaster():GetAbsOrigin(), false) ParticleManager:SetParticleControl(self.pfx_ulti, 3, self:GetParent():GetAbsOrigin()) end local buff = self:GetCaster():FindModifierByName("modifier_imba_singularity") local stacks = buff:GetStackCount() --Add singularity stacks (capped to a certain value) if not keys.talent then if stacks + #enemies < self.singularity_cap then buff:SetStackCount(stacks + #enemies) else buff:SetStackCount(self.singularity_cap) end end EmitSoundOn(self.sound, self:GetParent()) local dummy = self:GetParent() self:GetParent():SetContextThink("StopBHsound", function() StopSoundOn("Hero_Enigma.Black_Hole", dummy) StopSoundOn("Imba.EnigmaBlackHoleTi5", dummy) return nil end, 4.0) -- Break trees. Because fuck trees. GridNav:DestroyTreesAroundPoint(self:GetParent():GetAbsOrigin(), self.pull_radius, false) -- Create an FoW viewer for all teams so everyone sees it for i = DOTA_TEAM_FIRST, DOTA_TEAM_CUSTOM_MAX do if i == self:GetParent():GetTeamNumber() then AddFOWViewer(i, self:GetParent():GetAbsOrigin(), self.pull_radius, FrameTime()*2, false) else AddFOWViewer(i, self:GetParent():GetAbsOrigin(), 10, FrameTime()*2, false) end end self.particle = ParticleManager:CreateParticle(pfx_name, PATTACH_WORLDORIGIN, nil) ParticleManager:SetParticleControl(self.particle, 0, Vector(self:GetParent():GetAbsOrigin().x,self:GetParent():GetAbsOrigin().y,self:GetParent():GetAbsOrigin().z+64)) ParticleManager:SetParticleControl(self.particle, 10, Vector(self.radius, self.pull_radius, 0)) self.think_time = 0 self.dmg = self:GetAbility():GetSpecialValueFor("damage_per_tick") self:StartIntervalThink(FrameTime()) --Scepter stuff if self:GetCaster():HasScepter() then self.scepter = true end end function modifier_imba_enigma_black_hole_thinker:OnIntervalThink() if not IsServer() then return end self.think_time = self.think_time + FrameTime() -- Create an FoW viewer for all teams so everyone sees it for i = DOTA_TEAM_FIRST, DOTA_TEAM_CUSTOM_MAX do if i == self:GetParent():GetTeamNumber() then AddFOWViewer(i, self:GetParent():GetAbsOrigin(), self.pull_radius, FrameTime()*2, false) else AddFOWViewer(i, self:GetParent():GetAbsOrigin(), 10, FrameTime()*2, false) end end -- Pull effect local enemies = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, self.pull_radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false) for _,enemy in pairs(enemies) do if not enemy:IsRoshan() then enemy:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_imba_enigma_black_hole_pull", {}) end end -- Damage if self.think_time >= 1.0 then -- Break trees. Because fuck trees. GridNav:DestroyTreesAroundPoint(self:GetParent():GetAbsOrigin(), self.pull_radius, false) self.think_time = self.think_time - 1.0 local midnightDamagePcnt = 0 if self.scepter then local midnight = self:GetCaster():FindAbilityByName("imba_enigma_midnight_pulse") if midnight and midnight:GetLevel() > 0 then midnightDamagePcnt = midnight:GetSpecialValueFor("damage_per_tick") * 0.01 end end local enemies = FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetParent():GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_ANY_ORDER, false) for _, enemy in pairs(enemies) do if not enemy:IsRoshan() then ApplyDamage({victim = enemy, attacker = self:GetCaster(), damage = self.dmg, damage_type = DAMAGE_TYPE_PURE, ability = self:GetAbility()}) if self.scepter then ApplyDamage({victim = enemy, attacker = self:GetCaster(), damage = enemy:GetMaxHealth() * midnightDamagePcnt, damage_type = DAMAGE_TYPE_PURE, ability = self:GetAbility()}) end end end end end function modifier_imba_enigma_black_hole_thinker:OnDestroy() if not IsServer() then return end StopSoundOn(self.sound, self:GetParent()) EmitSoundOn("Hero_Enigma.Black_Hole.Stop", self:GetParent()) ParticleManager:DestroyParticle(self.particle, false) ParticleManager:ReleaseParticleIndex(self.particle) if self.pfx_ulti then ParticleManager:DestroyParticle(self.pfx_ulti, false) ParticleManager:ReleaseParticleIndex(self.pfx_ulti) end self:GetParent():ForceKill(false) end function modifier_imba_enigma_black_hole:IsDebuff() return true end function modifier_imba_enigma_black_hole:IsHidden() return false end function modifier_imba_enigma_black_hole:IsPurgable() return false end function modifier_imba_enigma_black_hole:IsPurgeException() return false end function modifier_imba_enigma_black_hole:RemoveOnDeath() return false end function modifier_imba_enigma_black_hole:IsStunDebuff() return true end function modifier_imba_enigma_black_hole:IsMotionController() return true end function modifier_imba_enigma_black_hole:GetMotionControllerPriority() return DOTA_MOTION_CONTROLLER_PRIORITY_HIGHEST end function modifier_imba_enigma_black_hole:CheckState() if not IsServer() then return end local state = {} --Does not affect Roshan if not self:GetParent():IsRoshan() then state = { [MODIFIER_STATE_DISARMED] = true, [MODIFIER_STATE_ROOTED] = true, [MODIFIER_STATE_MUTED] = true, [MODIFIER_STATE_STUNNED] = true, } end return state end function modifier_imba_enigma_black_hole:OnCreated() if not IsServer() then return end if self:GetParent() and self:GetParent():IsRoshan() then self:Destroy() end --Roshan is immune to Black Hole self:StartIntervalThink(FrameTime()) local ability = self:GetAbility() self.radius = self:GetAbility().radius self:GetParent():StartGesture(ACT_DOTA_FLAIL) end function modifier_imba_enigma_black_hole:OnIntervalThink() local enigma = self:GetCaster() local ability = self:GetAbility() if not ability:IsChanneling() then self:Destroy() end if ability.thinker then local distance = CalcDistanceBetweenEntityOBB(ability.thinker, self:GetParent()) if distance > self.radius then self:Destroy() end end self:HorizontalMotion(self:GetParent(), FrameTime()) end function modifier_imba_enigma_black_hole:HorizontalMotion(unit, time) local thinker = self:GetAbility().thinker local pos = unit:GetAbsOrigin() if thinker and not thinker:IsNull() and self:GetAbility():IsChanneling() then local thinker_pos = thinker:GetAbsOrigin() local next_pos = GetGroundPosition(RotatePosition(thinker_pos, QAngle(0,0.5,0), pos), unit) local distance = CalcDistanceBetweenEntityOBB(unit, thinker) if distance > 20 then next_pos = GetGroundPosition((next_pos + (thinker_pos - next_pos):Normalized() * 1), unit) end unit:SetAbsOrigin(next_pos) end end function modifier_imba_enigma_black_hole:OnDestroy() if not IsServer() then return end self:GetParent():FadeGesture(ACT_DOTA_FLAIL) ResolveNPCPositions(self:GetParent():GetAbsOrigin(), 128) end function modifier_imba_enigma_black_hole_pull:IsDebuff() return true end function modifier_imba_enigma_black_hole_pull:IsHidden() return true end function modifier_imba_enigma_black_hole_pull:IsPurgable() return false end function modifier_imba_enigma_black_hole_pull:IsPurgeException() return false end function modifier_imba_enigma_black_hole_pull:RemoveOnDeath() return false end function modifier_imba_enigma_black_hole_pull:IsStunDebuff() return true end function modifier_imba_enigma_black_hole_pull:IsMotionController() return true end function modifier_imba_enigma_black_hole_pull:GetMotionControllerPriority() return DOTA_MOTION_CONTROLLER_PRIORITY_LOWEST end function modifier_imba_enigma_black_hole_pull:OnCreated() if not IsServer() then return end if self:GetParent():IsRoshan() then self:Destroy() end --Roshan is immune to Black Hole self:StartIntervalThink(FrameTime()) local ability = self:GetAbility() self.pull_radius = self:GetAbility().pull_radius self.base_pull_distance = ability:GetSpecialValueFor("pull_strength") end function modifier_imba_enigma_black_hole_pull:OnIntervalThink() local enigma = self:GetCaster() local ability = self:GetAbility() if not ability:IsChanneling() then self:Destroy() end if ability.thinker then local distance = CalcDistanceBetweenEntityOBB(ability.thinker, self:GetParent()) if distance > self.pull_radius then self:Destroy() end end self:HorizontalMotion(self:GetParent(), FrameTime()) end function modifier_imba_enigma_black_hole_pull:HorizontalMotion(unit, time) self.pull_distance = CalculatePullLength(self:GetCaster(), self:GetParent(), self.base_pull_distance) / (1.0 / FrameTime()) local thinker = self:GetAbility().thinker local pos = unit:GetAbsOrigin() if thinker and not thinker:IsNull() and self:GetAbility():IsChanneling() and not self:GetParent():HasModifier("modifier_imba_enigma_black_hole") then local thinker_pos = thinker:GetAbsOrigin() local next_pos = GetGroundPosition((pos + (thinker_pos - pos):Normalized() * self.pull_distance), unit) unit:SetAbsOrigin(next_pos) end end function modifier_imba_enigma_black_hole:OnDestroy() if not IsServer() then return end self:GetParent():FadeGesture(ACT_DOTA_FLAIL) ResolveNPCPositions(self:GetParent():GetAbsOrigin(), 128) end modifier_imba_singularity = modifier_imba_singularity or class({}) function modifier_imba_singularity:IsDebuff() return false end function modifier_imba_singularity:IsHidden() return false end function modifier_imba_singularity:IsPurgable() return false end function modifier_imba_singularity:IsPurgeException() return false end function modifier_imba_singularity:RemoveOnDeath() return false end function modifier_imba_singularity:DeclareFunctions() return {MODIFIER_EVENT_ON_DEATH} end function modifier_imba_singularity:OnDeath(keys) if IsServer() and keys.unit == self:GetParent() and self:GetParent():HasTalent("special_bonus_imba_enigma_4") and self:GetParent():IsRealHero() then local ability = self:GetAbility() local duration = ability:GetSpecialValueFor("duration") / self:GetParent():FindTalentValue("special_bonus_imba_enigma_4") local base_radius = ability:GetSpecialValueFor("radius") local extar_radius = ability:GetSpecialValueFor("singularity_stun_radius_increment_per_stack") local base_pull_radius = ability:GetSpecialValueFor("pull_radius") local extra_pull_radius = ability:GetSpecialValueFor("singularity_pull_radius_increment_per_stack") ability.radius = base_radius + extar_radius * keys.unit:FindModifierByName("modifier_imba_singularity"):GetStackCount() ability.pull_radius = base_pull_radius + extra_pull_radius * keys.unit:FindModifierByName("modifier_imba_singularity"):GetStackCount() ability.thinker = CreateModifierThinker(keys.unit, ability, "modifier_imba_enigma_black_hole_thinker", {duration = duration, talent = 1}, keys.unit:GetAbsOrigin(), keys.unit:GetTeamNumber(), false) end end --------------------------------------------------------------------------------------------------------- -- Adding separate modifier initializations here for talents that need client-side interaction as well -- --------------------------------------------------------------------------------------------------------- modifier_special_bonus_imba_enigma_1 = class ({}) function modifier_special_bonus_imba_enigma_1:IsHidden() return true end function modifier_special_bonus_imba_enigma_1:IsPurgable() return false end function modifier_special_bonus_imba_enigma_1:RemoveOnDeath() return false end modifier_special_bonus_imba_enigma_2 = class ({}) function modifier_special_bonus_imba_enigma_2:IsHidden() return true end function modifier_special_bonus_imba_enigma_2:IsPurgable() return false end function modifier_special_bonus_imba_enigma_2:RemoveOnDeath() return false end modifier_special_bonus_imba_enigma_5 = class ({}) function modifier_special_bonus_imba_enigma_5:IsHidden() return true end function modifier_special_bonus_imba_enigma_5:IsPurgable() return false end function modifier_special_bonus_imba_enigma_5:RemoveOnDeath() return false end
--!nocheck --// created by bhristt (november 23 2021) --// updated (january 10 2022) --// creates a catmull rom spline given a parameter tau (τ) and 4 points p_(i-1), p_i, p_(i+1), p_(i+2) --// see more information on the dev-forum: --// https://devforum.roblox.com/t/catmull-rom-spline-module-smooth-curve-that-goes-through-control-points/1568205?u=bhristt --// services local TweenService = game:GetService("TweenService") --// catmull-rom spline local CatmullRomSpline = {} local CatmullRomSplineFunctions = {} --// constructor --// returns a new catmull-rom spline with the given tension and the given control points --// if not given tension or control points, will default to tension = 0.5 and control points = {} function CatmullRomSpline.new(controlPoints: {number} | {Vector2} | {Vector3 | BasePart} | {BasePart}?, tension: number?): CatmullRomSplineObject local self = {} --// main properties self.Tension = tension or 0.5 self.Points = {} --// length properties self.LengthIterations = 1000 self.LengthIndices = {} self.Length = 0 --// connected splines self.ConnectedSplines = {} --// holds the connections from the baseparts self._connections = {} --// add points if controlPoints ~= nil then for _, point in pairs(controlPoints) do CatmullRomSplineFunctions.AddPoint(self, point) end end --// set metatable setmetatable(self, { __index = CatmullRomSplineFunctions, __newindex = function(tbl, index, value) error("Cannot add new indices to CatmullRomSplineObject!") end, }) return self end --// changes the tension of the CatmullRomSpline object --// calling this method is the correct way to change the tension of the catmull-rom spline --// without calling this function, the length won't change unless you manually call --// CatmullRomSpline:UpdateLength() after changing the tension by indexing --// this only changes the tension of the given CatmullRomSpline object, not the connected splines function CatmullRomSplineFunctions:ChangeTension(tension: number) --// check if given input is a number if type(tension) ~= "number" then error("CatmullRomSpline:ChangeTension() expected a number as an input, got " .. tostring(tension) .. "!") end self.Tension = tension CatmullRomSplineFunctions.UpdateLength(self) end --// changes the tension of the CatmullRomSpline object and its connected splines --// does the same thing as CatmullRomSpline:ChangeTension(), but calls this function for all connected splines function CatmullRomSplineFunctions:ChangeAllSplineTensions(tension: number) --// check if input is a number if type(tension) ~= "number" then error("CatmullRomSpline:ChangeAllSplineTensions() expected a number as an input, got " .. tostring(tension) .. "!") end --// iterate through associated splines and change tension local allSplines = CatmullRomSplineFunctions.GetSplines(self) for _, spline in pairs(allSplines) do spline:ChangeTension(tension) end end --// adds a point to the CatmullRomSpline object --// will error if not given a number, vector3 or basepart --// optional index parameter for including the index where the point will be added in the catmull-rom spline function CatmullRomSplineFunctions:AddPoint(p: number | Vector2 | Vector3 | BasePart, index: number?) local points = self.Points --// checks to see if the type of point is the same as the other points in the CatmullRomSplineObject local function checkIfPointsMatch(point) local allPoints = CatmullRomSplineFunctions.GetPoints(self) for _, v in pairs(allPoints) do if typeof(v) ~= typeof(point) then return false end end return true end --// check if there are already 4 points in the spline if #points == 4 then if typeof(p) == "number" or typeof(p) == "Vector2" or typeof(p) == "Vector3" then if checkIfPointsMatch(p) then local allSplines = CatmullRomSplineFunctions.GetSplines(self) local lastSpline = allSplines[#allSplines] local newSpline = CatmullRomSpline.new({lastSpline.Points[2], lastSpline.Points[3], lastSpline.Points[4], p}, lastSpline.Tension) CatmullRomSplineFunctions.ConnectSpline(self, newSpline) end elseif p:IsA("BasePart") then if checkIfPointsMatch(p.Position) then local allSplines = CatmullRomSplineFunctions.GetSplines(self) local lastSpline = allSplines[#allSplines] local newSpline = CatmullRomSpline.new({lastSpline.Points[2], lastSpline.Points[3], lastSpline.Points[4], p}, lastSpline.Tension) CatmullRomSplineFunctions.ConnectSpline(self, newSpline) end end else if typeof(p) == "number" then if checkIfPointsMatch(p) then table.insert(points, index or #points + 1, p) end elseif typeof(p) == "Vector2" then if checkIfPointsMatch(p) then table.insert(points, index or #points + 1, p) end elseif typeof(p) == "Vector3" then if checkIfPointsMatch(p) then table.insert(points, index or #points + 1, p) end elseif p:IsA("BasePart") then if checkIfPointsMatch(p.Position) then table.insert(points, index or #points + 1, p) self._connections[p] = p.Changed:Connect(function(prop) if prop == "Position" then CatmullRomSplineFunctions.UpdateLength(self) end end) end else error("Invalid input received for CatmullRomSpline:AddPoint(), expected Vector3 or BasePart, got " .. tostring(p) .. "!") end end --// check if there are enough points to calculate the length of the catmull rom spline if #points == 4 then CatmullRomSplineFunctions.UpdateLength(self) end end --// removes a point from the CatmullRomSpline object at the given index --// if index is not given, this will error function CatmullRomSplineFunctions:RemovePoint(index: number) --// check if input is valid if type(p) ~= "number" then error("CatmullRomSpline:RemovePoint() expected a number as the input, got " .. tostring(index) .. "!") end --// remove point local points = self.Points local point = table.remove(points, index) if point ~= nil and typeof(point) == "Instance" and point:IsA("BasePart") then if self._connections[point] then self._connections[point]:Disconnect() self._connections[point] = nil end end end --// returns the points of the catmull-rom spline in number or vector3 form --// important to use because points given to the CatmullRomSpline object can be --// numbers, baseparts or Vector3s function CatmullRomSplineFunctions:GetPoints(): {number} | {Vector2} | {Vector3} local points = {} --// iterate through points for i = 1, #self.Points do points[i] = typeof(self.Points[i]) == "Instance" and self.Points[i].Position or self.Points[i] end --// return points return points end --// connects a CatmullRomSpline object to the current CatmullRomSpline object --// if the given spline does not match the type of points in the main spline object, --// the splines cannot be connected --// can only connect splines that are connected to eachother via 3 control points --// example of connected splines: --// spline1: {p1, p2, p3, p4} spline2: {p2, p3, p4, p5} function CatmullRomSplineFunctions:ConnectSpline(spline: CatmullRomSplineObject) --// the points of the given spline local points = spline.Points --// check if spline shares two beginning control points or two end control points with one of the associated splines local allSplines = CatmullRomSplineFunctions.GetSplines(self) local associatedSpline = allSplines[#allSplines] local associatedPoints = associatedSpline.Points --// checks to see if the type of point is the same as the other points in the CatmullRomSplineObject local function checkIfPointsMatch(point) local allPoints = CatmullRomSplineFunctions.GetPoints(self) for _, v in pairs(allPoints) do if typeof(v) ~= typeof(point) then return false end end return true end if not checkIfPointsMatch((typeof(associatedPoints[1]) == "number" or typeof(associatedPoints[1]) == "Vector3") and associatedPoints[1] or associatedPoints[1].Position) then error("Cannot connect the spline because the splines do not have the same types of points!") end if associatedPoints[2] == points[1] and associatedPoints[3] == points[2] and associatedPoints[4] == points[3] then table.insert(self.ConnectedSplines, spline) CatmullRomSplineFunctions.UpdateLength(self) else error("Cannot connect the spline because the splines do not share 3 common points!") end end --// returns a table with all the splines associated with the current CatmullRomSpline object --// this table is returned in order function CatmullRomSplineFunctions:GetSplines(): {CatmullRomSplineObject} local allSplines = {self} for i = 1, #self.ConnectedSplines do table.insert(allSplines, self.ConnectedSplines[i]) end return allSplines end --// returns the spline associated with the t value --// when connecting splines, the t value still ranges from 0 to 1, but the splines remain separated --// this function must return the spline associated with the t value, and a transformed t value associated with the position t in the entire curve function CatmullRomSplineFunctions:GetSplineAt(t: number): (CatmullRomSplineObject, number) local allSplines = CatmullRomSplineFunctions.GetSplines(self) --// given a number x in between a and b, returns a number between 0 and 1 that represents --// the percentage location of x in between a and b --// (the inverse of linear interpolation) local function percentage(x: number, a: number, b: number) local s = 1 / (b - a); return s * x - s * b + 1; end --// check to make sure t is a number if type(t) ~= "number" then error("CatmullRomSpline:GetSplineAt() expected a number as an input, got " .. tostring(t) .. "!") end --// if the number of splines is 1, return the spline and t if #allSplines == 1 then return self, t end --// if the number of splines if more than 1, return a transformed parameter t local recip = 1 / #allSplines if t <= 0 then return self, t * recip elseif t >= 1 then return allSplines[#allSplines], 1 + (t - 1) * recip else local splineIndex = math.ceil(t * #allSplines) local spline = allSplines[splineIndex] return spline, percentage(t, (splineIndex - 1) * recip, (splineIndex) * recip) end end --// updates the length and length indices of the CatmullRomSpline object --// only works if there are enough points in the CatmullRomSpline object to calculate position and derivative --// this function does not need to be called, this will be called automatically as the curve --// is updated function CatmullRomSplineFunctions:UpdateLength() --// stores the total length of the catmull-rom spline local l = 0 --// important values local points = {} do local allSplines = CatmullRomSplineFunctions.GetSplines(self) for i, spline in pairs(allSplines) do local localPoints = CatmullRomSplineFunctions.GetPoints(spline) if #localPoints ~= 4 then error("Cannot get the length of the CatmullRomSpline object, expected 4 control points for all splines, got " .. tostring(#points) .. " points for spline " .. tostring(i) .. "!") end for _, localPoint in pairs(localPoints) do table.insert(points, localPoint) end end end local iterations = self.LengthIterations --// start iteration local sums = {} for i = 1, iterations do local dldt = CatmullRomSplineFunctions.CalculateDerivativeAt(self, (i - 1) / (iterations - 1)) if typeof(dldt) == "number" then l += dldt * (1 / iterations) else l += dldt.Magnitude * (1 / iterations) end table.insert(sums, {((i - 1) / (iterations - 1)), l, dldt}) end --// return length and sum table self.Length, self.LengthIndices = l, sums end --// catmull-rom spline functions --// this function returns a point inside the catmull-rom spline as long as t is a number --// for expected results, try to keep t withing the interval [0, 1] function CatmullRomSplineFunctions:CalculatePositionAt(t: number): Vector2 | Vector3 | number --// check if t is between 0 and 1 if type(t) ~= "number" then error("The given t value in CatmullRomSpline:CalculatePositionAt() was not between 0 and 1, got " .. tostring(t) .. "!") end --// make sure the correct the position is being calculated from the correct spline self, t = CatmullRomSplineFunctions.GetSplineAt(self, t) --// check if the catmull-rom has enough points to calculate a point local points = CatmullRomSplineFunctions.GetPoints(self) if #points ~= 4 then error("The CatmullRomSpline object has an invalid number of points (" .. tostring(#points) .. "), expected 4 points!") end --// calculate cubic function constants local tension = self.Tension local c0 = points[2] local c1 = tension * (points[3] - points[1]) local c2 = 3 * (points[3] - points[2]) - tension * (points[4] - points[2]) - 2 * tension * (points[3] - points[1]) local c3 = -2 * (points[3] - points[2]) + tension * (points[4] - points[2]) + tension * (points[3] - points[1]) --// calculate point local pointV3 = c0 + c1 * t + c2 * t^2 + c3 * t^3 --// return point return pointV3 end --// this function returns a point inside the catmull-rom spline as long as t is in between 0 and 1 --// unlike CatmullRomSpline:CalculatePositionAt(), this function is relative to the length of the spline --// and t acts as the percentage of the length of the spline --// if t is not between 0 and 1, this function will error function CatmullRomSplineFunctions:CalculatePositionRelativeToLength(t: number): Vector2 | Vector3 | number --// check if t is a number between 0 and 1 if type(t) ~= "number" then error("CatmullRomSpline:CalculatePositionRelativeToLength() only accepts a number, got " .. tostring(t) .. "!") end --// start algorithm to calculate position in catmull-rom spline local points = self.Points local numPoints = #points --// check if there are enough points if numPoints == 4 then --// important values local length = self.Length local lengthIndices = self.LengthIndices local iterations = self.LengthIterations local points = CatmullRomSplineFunctions.GetPoints(self) --// get length of section local targetLength = length * t --// iterate through sum table local nearestParameterIndex, nearestParameter for i, orderedPair in ipairs(lengthIndices) do if targetLength - orderedPair[2] <= 0 then nearestParameterIndex = i nearestParameter = orderedPair break elseif i == #lengthIndices then nearestParameterIndex = i nearestParameter = orderedPair break end end --// calculate percent error local p0, p1 if lengthIndices[nearestParameterIndex - 1] then p0 = CatmullRomSplineFunctions.CalculatePositionAt(self, lengthIndices[nearestParameterIndex - 1][1]) p1 = CatmullRomSplineFunctions.CalculatePositionAt(self, nearestParameter[1]) else p0 = CatmullRomSplineFunctions.CalculatePositionAt(self, nearestParameter[1]) p1 = CatmullRomSplineFunctions.CalculatePositionAt(self, lengthIndices[nearestParameterIndex + 1][1]) end local percentError = (nearestParameter[2] - targetLength) / (p1 - p0).Magnitude --// return the position at the nearestParameter return p0 + (p1 - p0) * (1 - percentError) else --// not enough points to get a position error("The CatmullRomSpline object has an invalid number of points (" .. tostring(#points) .. "), expected 4 points!") end end --// this function returns the tangent vector of the catmull-rom spline at the point where t is the given number --// if t is not between 0 and 1, this function will error function CatmullRomSplineFunctions:CalculateDerivativeAt(t: number): Vector2 | Vector3 | number --// check if t is between 0 and 1 if type(t) ~= "number" then error("The given t value in CatmullRomSpline:CalculateDerivativeAt() was not between 0 and 1, got " .. tostring(t) .. "!") end --// make sure the correct the derivative is being calculated from the correct spline self, t = CatmullRomSplineFunctions.GetSplineAt(self, t) --// check if the catmull-rom has enough points to calculate a point local points = CatmullRomSplineFunctions.GetPoints(self) if #points ~= 4 then error("The CatmullRomSpline object has an invalid number of points (" .. tostring(#points) .. "), expected 4 points!") end --// calculate cubic function constants local tension = self.Tension local c1 = tension * (points[3] - points[1]) local c2 = 3 * (points[3] - points[2]) - tension * (points[4] - points[2]) - 2 * tension * (points[3] - points[1]) local c3 = -2 * (points[3] - points[2]) + tension * (points[4] - points[2]) + tension * (points[3] - points[1]) --// calculate tangent vector local lineV3 = c1 + 2 * c2 * t + 3 * c3 * t^2 --// return tangent vector return lineV3 end --// this function returns a tangent vector at the given t the catmull-rom spline as long as t is in between 0 and 1 --// unlike CatmullRomSpline:CalculateDerivativeAt(), this function is relative to the length of the spline --// and t acts as the percentage of the length of the spline --// if t is not between 0 and 1, this function will error function CatmullRomSplineFunctions:CalculateDerivativeRelativeToLength(t: number): Vector2 | Vector3 | number --// check if t is a number between 0 and 1 if type(t) ~= "number" then error("CatmullRomSpline:CalculateDerivativeRelativeToLength() only accepts a number, got " .. tostring(t) .. "!") end --// start algorithm to calculate derivative in catmull-rom spline relative to length local points = self.Points local numPoints = #points --// check if there are enough points if numPoints == 4 then --// important values local length = self.Length local lengthIndices = self.LengthIndices local iterations = self.LengthIterations local points = CatmullRomSplineFunctions.GetPoints(self) --// get length of section local targetLength = length * t --// iterate through sum table local nearestParameterIndex, nearestParameter for i, orderedPair in ipairs(lengthIndices) do if targetLength - orderedPair[2] <= 0 then nearestParameterIndex = i nearestParameter = orderedPair break elseif i == #lengthIndices then nearestParameterIndex = i nearestParameter = orderedPair break end end --// calculate percent error local d0, d1 if lengthIndices[nearestParameterIndex - 1] then d0 = CatmullRomSplineFunctions.CalculateDerivativeAt(self, lengthIndices[nearestParameterIndex - 1][1]) d1 = CatmullRomSplineFunctions.CalculateDerivativeAt(self, nearestParameter[1]) else d0 = CatmullRomSplineFunctions.CalculateDerivativeAt(self, nearestParameter[1]) d1 = CatmullRomSplineFunctions.CalculateDerivativeAt(self, lengthIndices[nearestParameterIndex + 1][1]) end local percentError = (nearestParameter[2] - targetLength) / (d1 - d0).Magnitude --// return the position at the nearestParameter return d0 + (d1 - d0) * (1 - percentError) else --// not enough points to get a tangent vector error("The CatmullRomSpline object has an invalid number of points (" .. tostring(#points) .. "), expected 4 points!") end end --// creates a tween for the given instance in the given property --// this function will error if the given property is not a numerical value of some sort that can be tweened --// this function has an optional relativeToSplineLength argument that judges whether the tween --// should tween relative to the Catmull-Rom spline's length, or just as t goes from 0 to 1. --// the propertyTable should be a table containing strings --// for example: {"CFrame"} or {"Position"} function CatmullRomSplineFunctions:CreateTween(instance: Instance, tweenInfo: TweenInfo, propertyTable: {string}, relativeToSplineLength: boolean?): Tween --// check if the given instance is really an instance if typeof(instance) == "Instance" then else error("CatmullRomSplineObject:CreateTween() expected an instance as the first input, got " .. tostring(instance) .. "!") end --// check if the given tween info is really a tween info if typeof(tweenInfo) == "TweenInfo" then else error("CatmullRomSplineObject:CreateTween() expected a TweenInfo object as the second input, got " .. tostring(tweenInfo) .. "!") end --// check that the properties in the property table are properties of the instance given local propertiesFound = true for _, propName in pairs(propertyTable) do local success, result = pcall(function() return instance[propName] end) if not success or result == nil then propertiesFound = false end end if not propertiesFound then error("CatmullRomSplineObject:CreateTween() was given properties in the property table that do not belong to the instance!") end --// start tween local numValue = Instance.new("NumberValue") local newTween = TweenService:Create(numValue, tweenInfo, {Value = 1}) local numValueChangedConnection = nil --// tween connection newTween.Changed:Connect(function(prop) if prop == "PlaybackState" then local playbackState = newTween.PlaybackState if playbackState == Enum.PlaybackState.Playing then numValueChangedConnection = numValue.Changed:Connect(function(t) for _, propName in pairs(propertyTable) do local pos = relativeToSplineLength and CatmullRomSplineFunctions.CalculatePositionRelativeToLength(self, t) or CatmullRomSplineFunctions.CalculatePositionAt(self, t) local derivative = relativeToSplineLength and CatmullRomSplineFunctions.CalculateDerivativeRelativeToLength(self, t) or CatmullRomSplineFunctions.CalculateDerivativeAt(self, t) local val = (typeof(pos) == "Vector3" and typeof(derivative) == "Vector3") and CFrame.new(pos, pos + derivative) or pos if typeof(instance[propName]) == "number" or typeof(instance[propName] == "Vector2") or typeof(instance[propName]) == "CFrame" then instance[propName] = val elseif typeof(instance[propName] == "Vector3") then instance[propName] = val.Position else error("CatmullRomSplineObject:CreateTween() could not set the value of the instance property " .. tostring(propName) .. ", not a numerical value!") end end end) else if numValueChangedConnection ~= nil then numValueChangedConnection:Disconnect() numValueChangedConnection = nil end end end end) --// return tween return newTween end --// return class export type CatmullRomSplineClass = typeof(CatmullRomSpline) export type CatmullRomSplineObject = typeof(CatmullRomSpline.new()) return CatmullRomSpline
local CATEGORY_NAME = "TTT Admin" local gamemode_error = "The current gamemode is not trouble in terrorist town" --[Ulx Completes]------------------------------------------------------------------------------ ulx.target_role = {} function updateRoles() table.Empty( ulx.target_role ) table.insert(ulx.target_role,"traitor") table.insert(ulx.target_role,"detective") table.insert(ulx.target_role,"innocent") end hook.Add( ULib.HOOK_UCLCHANGED, "ULXRoleNamesUpdate", updateRoles ) updateRoles() --[End]---------------------------------------------------------------------------------------- --[Global Helper Functions][Used by more than one command.]------------------------------------ --[[send_messages][Sends messages to player(s)] @param {[PlayerObject]} v [The player(s) to send the message to.] @param {[String]} message [The message that will be sent.] --]] function send_messages(v, message) if type(v) == "Players" then v:ChatPrint(message) elseif type(v) == "table" then for i=1, #v do v[i]:ChatPrint(message) end end end --[[corpse_find][Finds the corpse of a given player.] @param {[PlayerObject]} v [The player that to find the corpse for.] --]] function corpse_find(v) for _, ent in pairs( ents.FindByClass( "prop_ragdoll" )) do if ent.uqid == v:UniqueID() and IsValid(ent) then return ent or false end end end --[[corpse_remove][removes the corpse given.] @param {[Ragdoll]} corpse [The corpse to be removed.] --]] function corpse_remove(corpse) CORPSE.SetFound(corpse, false) if string.find(corpse:GetModel(), "zm_", 6, true) then corpse:Remove() elseif corpse.player_ragdoll then corpse:Remove() end end --[[corpse_identify][identifies the given corpse.] @param {[Ragdoll]} corpse [The corpse to be identified.] --]] function corpse_identify(corpse) if corpse then local ply = player.GetByUniqueID(corpse.uqid) ply:SetNWBool("body_found", true) CORPSE.SetFound(corpse, true) end end --[End]---------------------------------------------------------------------------------------- --[Force role]--------------------------------------------------------------------------------- --[[ulx.force][Forces <target(s)> to become a specified role.] @param {[PlayerObject]} calling_ply [The player who used the command.] @param {[PlayerObject]} target_plys [The player(s) who will have the effects of the command applied to them.] @param {[Number]} target_role [The role that target player(s) will have there role set to.] @param {[Boolean]} should_silent [Hidden, determines weather the output will be silent or not.] --]] function ulx.slaynr( calling_ply, target_ply, num_slay, should_slaynr ) if not GetConVarString("gamemode") == "terrortown" then ULib.tsayError( calling_ply, gamemode_error, true ) else local affected_plys = {} local slays_left = tonumber(target_ply:GetPData("slaynr_slays")) or 0 local current_slay local new_slay if ulx.getExclusive( target_ply, calling_ply ) then ULib.tsayError( calling_ply, ulx.getExclusive( target_ply, calling_ply ), true ) elseif num_slay < 0 then ULib.tsayError( calling_ply, "Invalid integer:\"" .. num_slay .. "\" specified.", true ) else current_slay = tonumber(target_ply:GetPData("slaynr_slays")) or 0 if not should_slaynr then new_slay = current_slay + num_slay else new_slay = current_slay - num_slay end --local slay_reason = reason --if slay_reason == "reason" then -- slay_reason = false --end if new_slay > 0 then target_ply:SetPData("slaynr_slays", new_slay) --target_ply:SetPData("slaynr_reason", slay_reason) else target_ply:RemovePData("slaynr_slays") --target_ply:RemovePData("slaynr_reason") end local slays_left = tonumber(target_ply:GetPData("slaynr_slays")) or 0 local slays_removed = ( current_slay - slays_left ) or 0 if slays_removed==0 then chat_message = ("#T will not be slain next round.") elseif slays_removed > 0 then chat_message = ("#A removed ".. slays_removed .." round(s) of slaying from #T.") elseif slays_left == 1 then chat_message = ("#A will slay #T next round.") elseif slays_left > 1 then chat_message = ("#A will slay #T for the next ".. tostring(slays_left) .." rounds.") end ulx.fancyLogAdmin( calling_ply, chat_message, target_ply, reason ) end end end local slaynr = ulx.command( CATEGORY_NAME, "ulx slaynr", ulx.slaynr, "!slaynr" ) slaynr:addParam{ type=ULib.cmds.PlayerArg } slaynr:addParam{ type=ULib.cmds.NumArg, default=1, hint="rounds", ULib.cmds.optional, ULib.cmds.round } --slaynr:addParam{ type=ULib.cmds.StringArg, hint="reason", ULib.cmds.optional} slaynr:addParam{ type=ULib.cmds.BoolArg, invisible=true } slaynr:defaultAccess( ULib.ACCESS_ADMIN ) slaynr:help( "Slays target(s) for a number of rounds" ) slaynr:setOpposite( "ulx rslaynr", {_, _, _, true}, "!rslaynr" ) --[Helper Functions]--------------------------------------------------------------------------- hook.Add("TTTBeginRound", "SlayPlayersNextRound", function() local affected_plys = {} for _,v in pairs(player.GetAll()) do local slays_left = tonumber(v:GetPData("slaynr_slays")) or 0 if v:Alive() and slays_left > 0 then local slays_left=slays_left -1 if slays_left == 0 then v:RemovePData("slaynr_slays") v:RemovePData("slaynr_reason") else v:SetPData("slaynr_slays", slays_left) end v:Kill() table.insert( affected_plys, v ) local corpse = corpse_find(v) if corpse then corpse_identify(corpse) corpse_remove(corpse) end end end local slay_message for i=1, #affected_plys do local v = affected_plys[ i ] local string_inbetween if i > 1 and #affected_plys == i then string_inbetween=" and " elseif i > 1 then string_inbetween=", " end string_inbetween = string_inbetween or "" slay_message = ( ( slay_message or "") .. string_inbetween ) slay_message = ( ( slay_message or "") .. v:Nick() ) end local slay_message_context if #affected_plys == 1 then slay_message_context ="was" else slay_message_context ="were" end if #affected_plys ~= 0 then ULib.tsay(_, slay_message .. " ".. slay_message_context .." slain.") end end) hook.Add("PlayerSpawn", "Inform" , function(ply) local slays_left = tonumber(ply:GetPData("slaynr_slays")) or 0 local slay_reason = false if ply:Alive() and slays_left > 0 then local chat_message = "" if slays_left > 0 then chat_message = (chat_message .. "You will be slain this round") end if slays_left > 1 then chat_message = (chat_message .. " and ".. (slays_left - 1) .." round(s) after the current round") end if slay_reason then chat_message = (chat_message .. " for \"".. slays_reason .."\".") else chat_message = (chat_message .. ".") end ply:ChatPrint(chat_message) end end) --[End]---------------------------------------------------------------------------------------- --[Force role]--------------------------------------------------------------------------------- --[[ulx.force][Forces <target(s)> to become a specified role.] @param {[PlayerObject]} calling_ply [The player who used the command.] @param {[PlayerObject]} target_plys [The player(s) who will have the effects of the command applied to them.] @param {[Number]} target_role [The role that target player(s) will have there role set to.] @param {[Boolean]} should_silent [Hidden, determines weather the output will be silent or not.] --]] function ulx.force( calling_ply, target_plys, target_role, should_silent ) if not GetConVarString("gamemode") == "terrortown" then ULib.tsayError( calling_ply, gamemode_error, true ) else local affected_plys = {} local starting_credits=GetConVarNumber("ttt_credits_starting") local role local role_grammar local role_string local role_credits if target_role == "traitor" or target_role == "t" then role, role_grammar, role_string, role_credits = ROLE_TRAITOR, "a ", "traitor", starting_credits end if target_role == "detective" or target_role == "d" then role, role_grammar, role_string, role_credits = ROLE_DETECTIVE, "a ", "detective", starting_credits end if target_role == "innocent" or target_role == "i" then role, role_grammar, role_string, role_credits = ROLE_INNOCENT, "an ", "innocent", 0 end for i=1, #target_plys do local v = target_plys[ i ] local current_role = v:GetRole() if ulx.getExclusive( v, calling_ply ) then ULib.tsayError( calling_ply, ulx.getExclusive( v, calling_ply ), true ) elseif GetRoundState() == 1 or GetRoundState() == 2 then ULib.tsayError( calling_ply, "The round has not begun!", true ) elseif role == nil then ULib.tsayError( calling_ply, "Invalid role :\"" .. target_role .. "\" specified", true ) elseif not v:Alive() then ULib.tsayError( calling_ply, v:Nick() .. " is dead!", true ) elseif current_role == role then ULib.tsayError( calling_ply, v:Nick() .. " is already " .. role_string, true ) else v:ResetEquipment() RemoveLoadoutWeapons(v) RemoveBoughtWeapons(v) v:SetRole(role) v:SetCredits(role_credits) SendFullStateUpdate() GiveLoadoutItems(v) GiveLoadoutWeapons(v) table.insert( affected_plys, v ) end end ulx.fancyLogAdmin( calling_ply, should_silent, "#A forced #T to become the role of " .. role_grammar .."#s.", affected_plys, role_string ) send_messages(affected_plys, "Your role has been set to " .. role_string .. "." ) end end local force = ulx.command( CATEGORY_NAME, "ulx force", ulx.force, "!force" ) force:addParam{ type=ULib.cmds.PlayersArg } force:addParam{ type=ULib.cmds.StringArg, completes=ulx.target_role, hint="Role" } force:addParam{ type=ULib.cmds.BoolArg, invisible=true } force:defaultAccess( ULib.ACCESS_SUPERADMIN ) force:setOpposite( "ulx sforce", {_, _, _, true}, "!sforce", true ) force:help( "Force <target(s)> to become a specified role." ) --[Helper Functions]--------------------------------------------------------------------------- --[[GetLoadoutWeapons][Returns the loadout weapons ] @param {[Number]} r [The role of the loadout weapons to be returned] @return {[table]} [A table of loadout weapons for the given role.] --]] function GetLoadoutWeapons(r) local tbl = { [ROLE_INNOCENT] = {}, [ROLE_TRAITOR] = {}, [ROLE_DETECTIVE]= {} }; for k, w in pairs(weapons.GetList()) do if w and type(w.InLoadoutFor) == "table" then for _, wrole in pairs(w.InLoadoutFor) do table.insert(tbl[wrole], WEPS.GetClass(w)) end end end return tbl[r] end --[[RemoveBoughtWeapons][Removes previously bought weapons from the shop.] @param {[PlayerObject]} ply [The player who will have their bought weapons removed.] --]] function RemoveBoughtWeapons(ply) for _, wep in pairs(weapons.GetList()) do local wep_class = WEPS.GetClass(wep) if wep and type(wep.CanBuy) == "table" then for _, weprole in pairs(wep.CanBuy) do if weprole == ply:GetRole() and ply:HasWeapon(wep_class) then ply:StripWeapon(wep_class) end end end end end --[[RemoveLoadoutWeapons][Removes all loadout weapons for the given player.] @param {[PlayerObject]} ply [The player who will have their loadout weapons removed.] --]] function RemoveLoadoutWeapons(ply) local weps = GetLoadoutWeapons( GetRoundState() == ROUND_PREP and ROLE_INNOCENT or ply:GetRole() ) for _, cls in pairs(weps) do if ply:HasWeapon(cls) then ply:StripWeapon(cls) end end end --[[GiveLoadoutWeapons][Gives the loadout weapons for that player.] @param {[PlayerObject]} ply [The player who will have their loadout weapons given.] --]] function GiveLoadoutWeapons(ply) local r = GetRoundState() == ROUND_PREP and ROLE_INNOCENT or ply:GetRole() local weps = GetLoadoutWeapons(r) if not weps then return end for _, cls in pairs(weps) do if not ply:HasWeapon(cls) then ply:Give(cls) end end end --[[GiveLoadoutItems][Gives the default loadout items for that role.] @param {[PlayerObject]} ply [The player who the equipment will be given to.] --]] function GiveLoadoutItems(ply) local items = EquipmentItems[ply:GetRole()] if items then for _, item in pairs(items) do if item.loadout and item.id then ply:GiveEquipmentItem(item.id) end end end end --[End]---------------------------------------------------------------------------------------- --[Respawn]------------------------------------------------------------------------------------ --[[ulx.respawn][Respawns <target(s)>] @param {[PlayerObject]} calling_ply [The player who used the command.] @param {[PlayerObject]} target_plys [The player(s) who will have the effects of the command applied to them.] @param {[Boolean]} should_silent [Hidden, determines weather the output will be silent or not.] --]] function ulx.respawn( calling_ply, target_plys, should_silent ) if not GetConVarString("gamemode") == "terrortown" then ULib.tsayError( calling_ply, gamemode_error, true ) else local affected_plys = {} for i=1, #target_plys do local v = target_plys[ i ] if ulx.getExclusive( v, calling_ply ) then ULib.tsayError( calling_ply, ulx.getExclusive( v, calling_ply ), true ) elseif GetRoundState() == 1 then ULib.tsayError( calling_ply, "Waiting for players!", true ) elseif v:Alive() then ULib.tsayError( calling_ply, v:Nick() .. " is already alive!", true ) else local corpse = corpse_find(v) if corpse then corpse_remove(corpse) end v:SpawnForRound( true ) v:SetCredits( ( (v:GetRole() == ROLE_INNOCENT) and 0 ) or GetConVarNumber("ttt_credits_starting") ) table.insert( affected_plys, v ) end end ulx.fancyLogAdmin( calling_ply, should_silent ,"#A respawned #T!", affected_plys ) send_messages(affected_plys, "You have been respawned.") end end local respawn = ulx.command( CATEGORY_NAME, "ulx respawn", ulx.respawn, "!respawn") respawn:addParam{ type=ULib.cmds.PlayersArg } respawn:addParam{ type=ULib.cmds.BoolArg, invisible=true } respawn:defaultAccess( ULib.ACCESS_SUPERADMIN ) respawn:setOpposite( "ulx srespawn", {_, _, true}, "!srespawn", true ) respawn:help( "Respawns <target(s)>." ) --[End]---------------------------------------------------------------------------------------- --[Respawn teleport]--------------------------------------------------------------------------- --[[ulx.respawntp][Respawns <target(s)>] @param {[PlayerObject]} calling_ply [The player who used the command.] @param {[PlayerObject]} target_ply [The player who will have the effects of the command applied to them.] @param {[Boolean]} should_silent [Hidden, determines weather the output will be silent or not.] --]] function ulx.respawntp( calling_ply, target_ply, should_silent ) if not GetConVarString("gamemode") == "terrortown" then ULib.tsayError( calling_ply, gamemode_error, true ) else local affected_ply = {} if not calling_ply:IsValid() then Msg( "You are the console, you can't teleport or teleport others since you can't see the world!\n" ) return elseif ulx.getExclusive( target_ply, calling_ply ) then ULib.tsayError( calling_ply, ulx.getExclusive( target_ply, calling_ply ), true ) elseif GetRoundState() == 1 then ULib.tsayError( calling_ply, "Waiting for players!", true ) elseif target_ply:Alive() then ULib.tsayError( calling_ply, target_ply:Nick() .. " is already alive!", true ) else local t = {} t.start = calling_ply:GetPos() + Vector( 0, 0, 32 ) -- Move them up a bit so they can travel across the ground t.endpos = calling_ply:GetPos() + calling_ply:EyeAngles():Forward() * 16384 t.filter = target_ply if target_ply ~= calling_ply then t.filter = { target_ply, calling_ply } end local tr = util.TraceEntity( t, target_ply ) local pos = tr.HitPos local corpse = corpse_find(target_ply) if corpse then corpse_remove(corpse) end target_ply:SpawnForRound( true ) target_ply:SetCredits( ((target_ply:GetRole() == ROLE_INNOCENT) and 0) or GetConVarNumber("ttt_credits_starting") ) target_ply:SetPos( pos ) table.insert( affected_ply, target_ply ) end ulx.fancyLogAdmin( calling_ply, should_silent ,"#A respawned and teleported #T!", affected_ply ) send_messages(affected_plys, "You have been respawned and teleported.") end end local respawntp = ulx.command( CATEGORY_NAME, "ulx respawntp", ulx.respawntp, "!respawntp") respawntp:addParam{ type=ULib.cmds.PlayerArg } respawntp:addParam{ type=ULib.cmds.BoolArg, invisible=true } respawntp:defaultAccess( ULib.ACCESS_SUPERADMIN ) respawntp:setOpposite( "ulx srespawntp", {_, _, true}, "!srespawntp", true ) respawntp:help( "Respawns <target> to a specific location." ) --[End]---------------------------------------------------------------------------------------- --[Karma]-------------------------------------------------------------------------------------- --[[ulx.karma][Sets the <target(s)> karma to a given amount.] @param {[PlayerObject]} calling_ply [The player who used the command.] @param {[PlayerObject]} target_plys [The player(s) who will have the effects of the command applied to them.] @param {[Number]} amount [The number the target's karma will be set to.] --]] function ulx.karma( calling_ply, target_plys, amount ) if not GetConVarString("gamemode") == "terrortown" then ULib.tsayError( calling_ply, gamemode_error, true ) else for i=1, #target_plys do target_plys[ i ]:SetBaseKarma( amount ) target_plys[ i ]:SetLiveKarma( amount ) end end ulx.fancyLogAdmin( calling_ply, "#A set the karma for #T to #i", target_plys, amount ) end local karma = ulx.command( CATEGORY_NAME, "ulx karma", ulx.karma, "!karma" ) karma:addParam{ type=ULib.cmds.PlayersArg } karma:addParam{ type=ULib.cmds.NumArg, min=0, max=10000, default=1000, hint="Karma", ULib.cmds.optional, ULib.cmds.round } karma:defaultAccess( ULib.ACCESS_ADMIN ) karma:help( "Changes the <target(s)> Karma." ) --[End]---------------------------------------------------------------------------------------- --[Toggle spectator]--------------------------------------------------------------------------- --[[ulx.spec][Forces <target(s)> to and from spectator.] @param {[PlayerObject]} calling_ply [The player who used the command.] @param {[PlayerObject]} target_plys [The player(s) who will have the effects of the command applied to them.] --]] function ulx.tttspec( calling_ply, target_plys, should_unspec ) if not GetConVarString("gamemode") == "terrortown" then ULib.tsayError( calling_ply, gamemode_error, true ) else for i=1, #target_plys do local v = target_plys[ i ] if should_unspec then v:ConCommand("ttt_spectator_mode 0") else v:ConCommand("ttt_spectator_mode 1") v:ConCommand("ttt_cl_idlepopup") end end if should_unspec then ulx.fancyLogAdmin( calling_ply, "#A has forced #T to join the world of the living.", target_plys ) else ulx.fancyLogAdmin( calling_ply, "#A has forced #T to spectate.", target_plys ) end end end local tttspec = ulx.command( CATEGORY_NAME, "ulx fspec", ulx.tttspec, "!fspec" ) tttspec:addParam{ type=ULib.cmds.PlayersArg } tttspec:addParam{ type=ULib.cmds.BoolArg, invisible=true } tttspec:defaultAccess( ULib.ACCESS_ADMIN ) tttspec:setOpposite( "ulx unspec", {_, _, true}, "!unspec" ) tttspec:help( "Forces the <target(s)> to/from spectator." ) --[End]---------------------------------------------------------------------------------------- ------------------------------ Next Round ------------------------------ ulx.next_round = {} local function updateNextround() table.Empty( ulx.next_round ) -- Don't reassign so we don't lose our refs table.insert(ulx.next_round,"traitor") -- Add "traitor" to the table. table.insert(ulx.next_round,"detective") -- Add "detective" to the table. table.insert(ulx.next_round,"unmark") -- Add "unmark" to the table. end hook.Add( ULib.HOOK_UCLCHANGED, "ULXNextRoundUpdate", updateNextround ) updateNextround() -- Init local PlysMarkedForTraitor = {} local PlysMarkedForDetective = {} function ulx.nextround( calling_ply, target_plys, next_round ) local affected_plys = {} local unaffected_plys = {} for i=1, #target_plys do local v = target_plys[ i ] local ID = v:UniqueID() if next_round == "traitor" then if PlysMarkedForTraitor[ID] == true or PlysMarkedForDetective[ID] == true then ULib.tsayError( calling_ply, "that player is already marked for the next round", true ) else PlysMarkedForTraitor[ID] = true table.insert( affected_plys, v ) end end if next_round == "detective" then if PlysMarkedForTraitor[ID] == true or PlysMarkedForDetective[ID] == true then ULib.tsayError( calling_ply, "that player is already marked for the next round!", true ) else PlysMarkedForDetective[ID] = true table.insert( affected_plys, v ) end end if next_round == "unmark" then if PlysMarkedForTraitor[ID] == true then PlysMarkedForTraitor[ID] = false table.insert( affected_plys, v ) end if PlysMarkedForDetective[ID] == true then PlysMarkedForDetective[ID] = false table.insert( affected_plys, v ) end end end if next_round == "unmark" then ulx.fancyLogAdmin( calling_ply, true, "#A has unmarked #T ", affected_plys ) else ulx.fancyLogAdmin( calling_ply, true, "#A marked #T to be #s next round.", affected_plys, next_round ) end end local nxtr= ulx.command( CATEGORY_NAME, "ulx forcenr", ulx.nextround, "!nr" ) nxtr:addParam{ type=ULib.cmds.PlayersArg } nxtr:addParam{ type=ULib.cmds.StringArg, completes=ulx.next_round, hint="Next Round", error="invalid role \"%s\" specified", ULib.cmds.restrictToCompletes } nxtr:defaultAccess( ULib.ACCESS_SUPERADMIN ) nxtr:help( "Forces the target to be a detective/traitor in the following round." ) local function TraitorMarkedPlayers() for k, v in pairs(PlysMarkedForTraitor) do if v then ply = player.GetByUniqueID(k) ply:SetRole(ROLE_TRAITOR) ply:AddCredits(GetConVarNumber("ttt_credits_starting")) ply:ChatPrint("You have been made a traitor by an admin this round.") PlysMarkedForTraitor[k] = false end end end hook.Add("TTTBeginRound", "Admin_Round_Traitor", TraitorMarkedPlayers) local function DetectiveMarkedPlayers() for k, v in pairs(PlysMarkedForDetective) do if v then ply = player.GetByUniqueID(k) ply:SetRole(ROLE_DETECTIVE) ply:AddCredits(GetConVarNumber("ttt_credits_starting")) ply:Give("weapon_ttt_wtester") ply:ChatPrint("You have been made a detective by an admin this round.") PlysMarkedForDetective[k] = false end end end hook.Add("TTTBeginRound", "Admin_Round_Detective", DetectiveMarkedPlayers)
local socket = require 'socket' local udp = socket.udp() udp:settimeout(0) udp:setpeername('localhost', 3000) udp:send("connect") local id while true do data, msg = udp:receive() if data then if data:match("id:") then id = data:match("id:(%d+)") else love.thread.getChannel("incoming"):push(data) end end if id then local msg = love.thread.getChannel("outgoing"):pop() while msg do udp:send(id .. ':'.. msg) msg = love.thread.getChannel("outgoing"):pop() end end end
DEFINE_BASECLASS("base_scalable") -- Required to get the local BaseClass AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") include("shared.lua") function CreateScalableMultiConvex(Player, Pos, Angle, Size) local Ent = ents.Create("base_scalable_mconvex") if not IsValid(Ent) then return end Ent:SetModel("models/props_interiors/pot01a.mdl") Ent:SetPlayer(Player) Ent:SetAngles(Angle) Ent:SetPos(Pos) Ent:Spawn() Ent:SetSize(Size or VectorRand(3, 96)) Ent.Owner = Player return Ent end duplicator.RegisterEntityClass("base_scalable_mconvex", CreateScalableMultiConvex, "Pos", "Angle", "Size") function ENT:GetOriginalSize() local Size, Changed = BaseClass.GetOriginalSize(self) if Changed or not self.Mesh then self.Mesh = ACF.GetModelMesh(self.LastModel) end return Size, Changed end function ENT:ApplyNewSize(NewSize) local Size = self:GetSize() or self:GetOriginalSize() local Factor = Vector(1 / Size.x, 1 / Size.y, 1 / Size.z) * NewSize local Mesh = self.Mesh for I, Hull in ipairs(Mesh) do for J, Vertex in ipairs(Hull) do Mesh[I][J] = (Vertex.pos or Vertex) * Factor end end self:PhysicsInitMultiConvex(Mesh) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:EnableCustomCollisions(true) self:DrawShadow(false) local PhysObj = self:GetPhysicsObject() if IsValid(PhysObj) then PhysObj:EnableMotion(false) end end function ENT:GetExtraInfo() return { Mesh = ACF.GetModelMesh(self.LastModel) } end
function createParticle( keys ) local particle = ParticleManager:CreateParticle("particles/units/heroes/neji/neji_forgot_a.vpcf", PATTACH_ABSORIGIN_FOLLOW, keys.caster) ParticleManager:SetParticleControl(particle, 1, keys.caster:GetAbsOrigin()) -- Origin ParticleManager:SetParticleControlEnt(particle, 0, keys.caster, PATTACH_POINT_FOLLOW, "attach_hitloc", keys.caster:GetAbsOrigin(), true) keys.ability.ultiParticle = particle end function removeParticle( keys ) keys.caster:Stop() ParticleManager:DestroyParticle( keys.ability.ultiParticle, true ) end function applyStun( keys ) local ability = keys.ability local caster = keys.caster local radius = ability:GetLevelSpecialValueFor("aoe_target", ability:GetLevel() - 1) local duration = ability:GetLevelSpecialValueFor("stun_duration",ability:GetLevel() - 1) local ability1 = caster:FindAbilityByName("special_bonus_neji_1") if ability1 ~= nil then if ability1:IsTrained() then duration = duration + 0.25 end end local targets = FindUnitsInRadius( caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, 0, false ) for _, unit in pairs(targets) do unit:AddNewModifier(unit, ability, "modifier_stunned", {duration = duration}) end end function knockBack( keys ) local ability = keys.ability local caster = keys.caster local radius = ability:GetLevelSpecialValueFor("aoe_target", ability:GetLevel() - 1) local ability1 = keys.caster:FindAbilityByName("special_bonus_neji_5") if ability1 ~= nil then if ability1:IsTrained() then radius = radius + 200 end end local stun_duration = ability:GetLevelSpecialValueFor("stun_duration", ability:GetLevel() - 1) local push_back_length = ability:GetLevelSpecialValueFor("push_back_length",ability:GetLevel() - 1) local targets = FindUnitsInRadius( caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, 0, false ) for _, unit in pairs(targets) do if unit:GetUnitName() == "npc_dota_tailed_beast_1" or unit:GetUnitName() == "npc_dota_tailed_beast_2" or unit:GetUnitName() == "npc_dota_tailed_beast_3" or unit:GetUnitName() == "npc_dota_tailed_beast_4" or unit:GetUnitName() == "npc_dota_tailed_beast_5" or unit:GetUnitName() == "npc_dota_tailed_beast_6" or unit:GetUnitName() == "npc_dota_tailed_beast_7" or unit:GetUnitName() == "npc_dota_tailed_beast_8" or unit:GetUnitName() == "npc_dota_tailed_beast_9" then return end local casterabs = caster:GetAbsOrigin() local unitabs = unit:GetAbsOrigin() -- get direction the push back should go local len = ( unitabs - casterabs ):Length2D() len = push_back_length - push_back_length * ( len / push_back_length ) local knockback = { center_x = caster:GetAbsOrigin().x, center_y = caster:GetAbsOrigin().y, center_z = caster:GetAbsOrigin().z, duration = 1.0, knockback_distance = push_back_length, knockback_height = 0, knockback_duration = 1.0 * 0.67, } unit:AddNewModifier(caster, ability, "modifier_knockback", knockback) end end function fireEffect(keys) local aoe_target = keys.ability:GetSpecialValueFor("aoe_target") local ability1 = keys.caster:FindAbilityByName("special_bonus_neji_5") if ability1 ~= nil then if ability1:IsTrained() then aoe_target = aoe_target + 200 end end local pidx = ParticleManager:CreateParticle("particles/units/heroes/neji/neji_kaiten_main.vpcf", PATTACH_ABSORIGIN_FOLLOW, keys.caster) ParticleManager:SetParticleControl(pidx, 1, Vector(aoe_target, 100,100)) end function dealDamage(keys) local aoe_target = keys.ability:GetSpecialValueFor("aoe_target") local damage = keys.ability:GetSpecialValueFor("damage") local ability1 = keys.caster:FindAbilityByName("special_bonus_neji_5") if ability1 ~= nil then if ability1:IsTrained() then aoe_target = aoe_target + 200 end end local full_enemies = FindUnitsInRadius( keys.caster:GetTeamNumber(), keys.caster:GetAbsOrigin(), nil, aoe_target, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false ) for key,oneTarget in pairs(full_enemies) do ApplyDamage({ victim = oneTarget, attacker = keys.caster, damage = damage, damage_type =DAMAGE_TYPE_MAGICAL, }) end end
--- OnSelectNumber --- -- -- Called when AI has to declare a number. -- Example card(s): Reasoning -- -- Parameters: -- choices = table containing the valid choices -- -- Return: index of the selected choice function OnSelectNumber(choices) local result = nil ------------------------------------------- -- The AI should always try to mill as many -- cards as possible with Card Trooper. ------------------------------------------- if GlobalActivatedCardID == 85087012 -- Card Trooper then GlobalActivatedCardID = nil if #AIDeck()>10 then return 1 else return 3 end end if GlobalActivatedCardID == 83531441 -- Dante then GlobalActivatedCardID = nil if #AIDeck()>10 and ((OPTCheck(57143342) or OPTCheck(20758643)) or BattlePhaseCheck()) then return 1 else return 3 end end local e,c,id = EffectCheck(1-player_ai) if e and id == 58577036 then result = ReasoningNumber() for i,choice in pairs(choices) do if choice == result then return i end end end local d = DeckCheck() if d and d.Number then result = d.Number(id,available) end if result~=nil then return result end ------------------------------------------- -- Reset this variable if it gets this far. ------------------------------------------- GlobalActivatedCardID = nil -- Example implementation: pick one of the available choices randomly return math.random(#choices) end
local FactoredOr = require(script.Parent.FactoredOr) local FactoredNor, Members, Super = FactoredOr.Extend() local Metatable = {__index = Members} function Members:Iterate() return next, self.Wrapped end function Members:Iterator() return next, self.Wrapped end function Members:Pairs() return next, self.Wrapped end function Members:ResolveState() return not Super.ResolveState(self) end FactoredNor.SerialType = "FactoredNorReplicant" function FactoredNor.new(...) local self = setmetatable({}, Metatable) FactoredNor.Constructor(self, ...) return self end function FactoredNor:__tostring() return "FactoredNor" end return FactoredNor
require 'cutorch' require 'cunn' require 'cudnn' function getModel(numClasses) -- Load ResNet-50 pre-trained on ImageNet local model = torch.load('resnet-50.t7') model:remove(11) model:add(nn.Linear(2048,numClasses)) -- Add classification loss layer local criterion = nn.CrossEntropyCriterion() return model,criterion end
local RNG_SEED = 69420731 local WORLD_SIZE = 10 local OBJECT_COUNT = 10 local MOVEMENT_GENERATIONS = 250 local MOVE_RANGE = 1 local TEST_COUNT = 10 local function clamp(lower, val, upper) if lower > upper then lower, upper = upper, lower end return math.max(lower, math.min(upper, val)) end local function doTest(world, moveFn) -- seed RNG math.randomseed(RNG_SEED) -- create OBJECT_COUNT random entities local entities = {} for i = 1, OBJECT_COUNT do local x = math.random() * WORLD_SIZE local y = math.random() * WORLD_SIZE local w = (math.random() * 1.5) + 0.5 local h = (math.random() * 1.5) + 0.5 local entity = {name = i} table.insert(entities, entity) world:add(entity, x, y, w, h) end -- Collect garbage and stop GC. collectgarbage('collect') collectgarbage('stop') -- move all entities for MOVEMENT_GENERATIONS generations. local collisions = 0 for _ = 1, MOVEMENT_GENERATIONS do for _, entity in ipairs(entities) do local x, y = world:getRect(entity) local goalX = clamp(0, x - MOVE_RANGE + (math.random() * MOVE_RANGE * 2), WORLD_SIZE) local goalY = clamp(0, y - MOVE_RANGE + (math.random() * MOVE_RANGE * 2), WORLD_SIZE) local len = moveFn(world, entity, goalX, goalY) collisions = collisions + len end if world.debug then world.debug() end end -- restart GC and measure memory difference before and after. local kbBefore = collectgarbage('count') collectgarbage('restart') collectgarbage('collect') local kbAfter = collectgarbage('count') local kbGarbage = kbBefore - kbAfter -- -- Print stats. -- print(("Collisions: %d"):format(collisions)) -- print(("Garbage: %.2fkB"):format(kbGarbage)) return kbGarbage end local function doTests(label, bump, moveFn) print(("============= %s ============="):format(label)) local totalGarbage = 0 for _ = 1, TEST_COUNT do local world = bump.newWorld(1) world.debug = bump.debug local garbage = doTest(world, moveFn) totalGarbage = totalGarbage + garbage end local averageGarbage = totalGarbage / TEST_COUNT print(("Garbage: %.2f kB"):format(averageGarbage)) print(("(Average after %d tests.)\n"):format(TEST_COUNT)) end local function moveOriginalFn(world, entity, goalX, goalY, goalZ) return select(4, world:move(entity, goalX, goalY, goalZ)) end doTests('Original', require 'bump-original', moveOriginalFn) local function moveModdedFn(world, entity, goalX, goalY, goalZ) local _, _, cols, len = world:move(entity, goalX, goalY, goalZ) world.freeCollisions(cols) return len end doTests('Modded', require 'bump-niji', moveModdedFn)
local app = require("app") app.response("Get User")
-- Copyright 2006-2016 Mitchell mitchell.att.foicica.com. See LICENSE. -- Batch LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'batch'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local rem = (P('REM') + 'rem') * l.space local comment = token(l.COMMENT, (rem + '::') * l.nonnewline^0) -- Strings. local string = token(l.STRING, l.delimited_range('"', true)) -- Keywords. local keyword = token(l.KEYWORD, word_match({ 'cd', 'chdir', 'md', 'mkdir', 'cls', 'for', 'if', 'echo', 'echo.', 'move', 'copy', 'ren', 'del', 'set', 'call', 'exit', 'setlocal', 'shift', 'endlocal', 'pause', 'defined', 'exist', 'errorlevel', 'else', 'in', 'do', 'NUL', 'AUX', 'PRN', 'not', 'goto', 'pushd', 'popd' }, nil, true)) -- Functions. local func = token(l.FUNCTION, word_match({ 'APPEND', 'ATTRIB', 'CHKDSK', 'CHOICE', 'DEBUG', 'DEFRAG', 'DELTREE', 'DISKCOMP', 'DISKCOPY', 'DOSKEY', 'DRVSPACE', 'EMM386', 'EXPAND', 'FASTOPEN', 'FC', 'FDISK', 'FIND', 'FORMAT', 'GRAPHICS', 'KEYB', 'LABEL', 'LOADFIX', 'MEM', 'MODE', 'MORE', 'MOVE', 'MSCDEX', 'NLSFUNC', 'POWER', 'PRINT', 'RD', 'REPLACE', 'RESTORE', 'SETVER', 'SHARE', 'SORT', 'SUBST', 'SYS', 'TREE', 'UNDELETE', 'UNFORMAT', 'VSAFE', 'XCOPY' }, nil, true)) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Variables. local variable = token(l.VARIABLE, '%' * (l.digit + '%' * l.alpha) + l.delimited_range('%', true, true)) -- Operators. local operator = token(l.OPERATOR, S('+|&!<>=')) -- Labels. local label = token(l.LABEL, ':' * l.word) M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'function', func}, {'comment', comment}, {'identifier', identifier}, {'string', string}, {'variable', variable}, {'label', label}, {'operator', operator}, } M._LEXBYLINE = true M._foldsymbols = { _patterns = {'[A-Za-z]+'}, [l.KEYWORD] = {setlocal = 1, endlocal = -1, SETLOCAL = 1, ENDLOCAL = -1} } return M
-- config: (lint (only format:string-quote) (quote single)) print("foo", 'foo', [[foo]]) print("'\n\"\'", '"\n\"\'', [[ "']])
return { no_consumer = true, fields = { request_token_data = { required = true, type = "table" }, customer_id = { required = true, type = "string" }, } }
ENT.Base = "sent_sakarias_scar_base" ENT.Type = "anim" ENT.PrintName = "carv3" ENT.Author = "Prof.Heavy" ENT.Category = "Call of Duty 4" ENT.Information = "" ENT.AdminOnly = false ENT.Spawnable = false ENT.AdminSpawnable = false ENT.AddSpawnHeight = 50 ENT.ViewDist = 200 ENT.ViewDistUp = 10 ENT.NrOfSeats = 3 ENT.NrOfWheels = 4 ENT.NrOfExhausts = 1 ENT.NrOfFrontLights = 2 ENT.NrOfRearLights = 2 ENT.SeatPos = {} ENT.WheelInfo = {} ENT.ExhaustPos = {} ENT.FrontLightsPos = {} ENT.RearLightsPos = {} ENT.effectPos = NULL ENT.DefaultSoftnesFront =15 ENT.DefaultSoftnesRear =15 ENT.CarMass =350 ENT.StabiliserOffset = NULL ENT.StabilisationMultiplier = 70 ENT.DefaultSound = "vehicles/diesel_loop2.wav" ENT.EngineEffectName = "Default" ENT.HornSound = "scarhorns/horn 1.wav" ENT.CarModel = "models/car1_body.mdl" ENT.TireModel = "models/car1_wheel.mdl" ENT.AnimType = 1 ENT.FrontLightColor = "220 220 160" ------------------------------------VARIABLES END for i = 1, ENT.NrOfWheels do ENT.WheelInfo[i] = {} end local xPos = 0 local yPos = 0 local zPos = 0 //SEAT POSITIONS --Seat Position 1 xPos = -4.1999998092651 yPos = -12.300000190735 zPos = 3.5999999046326 ENT.SeatPos[1] = Vector(xPos, yPos, zPos) --Seat Position 2 xPos = -2.5999999046326 yPos = 14.199999809265 zPos = 3.5999999046326 ENT.SeatPos[2] = Vector(xPos, yPos, zPos) --Seat Position 3 xPos = -31.200000762939 yPos = -10.60000038147 zPos = 3 ENT.SeatPos[3] = Vector(xPos, yPos, zPos) //WHEEL POSITIONS --Wheel Position 1 xPos = 41.200000762939 yPos = -18.89999961853 zPos = 3.7000000476837 ENT.WheelInfo[1].Pos = Vector(xPos, yPos, zPos) ENT.WheelInfo[1].Side = false ENT.WheelInfo[1].Torq = true ENT.WheelInfo[1].Steer = 1 --Wheel Position 2 xPos = -46.599998474121 yPos = -22.799999237061 zPos = 3.7000000476837 ENT.WheelInfo[2].Pos = Vector(xPos, yPos, zPos) ENT.WheelInfo[2].Side = false ENT.WheelInfo[2].Torq = true ENT.WheelInfo[2].Steer = 0 --Wheel Position 3 xPos = 41.5 yPos = 23.5 zPos = 3.7000000476837 ENT.WheelInfo[3].Pos = Vector(xPos, yPos, zPos) ENT.WheelInfo[3].Side = true ENT.WheelInfo[3].Torq = true ENT.WheelInfo[3].Steer = 1 --Wheel Position 4 xPos = -44.900001525879 yPos = 26.89999961853 zPos = 3.7000000476837 ENT.WheelInfo[4].Pos = Vector(xPos, yPos, zPos) ENT.WheelInfo[4].Side = true ENT.WheelInfo[4].Torq = true ENT.WheelInfo[4].Steer = 0 //FRONT LIGHT POSITIONS --Front light 1 xPos = 69.900001525879 yPos = -21.700000762939 zPos = 18.5 ENT.FrontLightsPos[1] = Vector(xPos, yPos, zPos) --Front light 2 xPos = 70.099998474121 yPos = 21.89999961853 zPos = 16.39999961853 ENT.FrontLightsPos[2] = Vector(xPos, yPos, zPos) //REAR LIGHT POSITIONS --Rear light 1 xPos = -75.5 yPos = 19.60000038147 zPos = 19 ENT.RearLightsPos[1] = Vector(xPos, yPos, zPos) --Rear light 2 xPos = -75.599998474121 yPos = -15.10000038147 zPos = 19.39999961853 ENT.RearLightsPos[2] = Vector(xPos, yPos, zPos) //EXHAUST POSITIONS --Exhaust 1 xPos = -66.900001525879 yPos = -10.199999809265 zPos = 4.8000001907349 ENT.ExhaustPos[1] = Vector(xPos, yPos, zPos) //EFFECT POSITION xPos = 49.099998474121 yPos = -1.6000000238419 zPos = 23.299999237061 ENT.effectPos = Vector(xPos, yPos, zPos) //CAR CHARACTERISTICS ENT.DefaultAcceleration = 1080.6999511719 ENT.DefaultMaxSpeed = 1188 ENT.DefaultTurboEffect = 2 ENT.DefaultTurboDuration = 4 ENT.DefaultTurboDelay = 10 ENT.DefaultReverseForce = 1000 ENT.DefaultReverseMaxSpeed = 200 ENT.DefaultBreakForce = 2000 ENT.DefaultSteerForce = 5 ENT.DefautlSteerResponse = 0.30000001192093 ENT.DefaultStabilisation = 2000 ENT.DefaultNrOfGears = 5 ENT.DefaultAntiSlide = 10 ENT.DefaultAutoStraighten = 5 ENT.DeafultSuspensionAddHeight = 10 ENT.DefaultHydraulicActive = 0 list.Set( "SCarsList", ENT.PrintName, ENT ) function ENT:Initialize() self:Setup() if (SERVER) then --Setting up the car characteristics self:SetAcceleration( self.DefaultAcceleration ) self:SetMaxSpeed( self.DefaultMaxSpeed ) self:SetTurboEffect( self.DefaultTurboEffect ) self:SetTurboDuration( self.DefaultTurboDuration ) self:SetTurboDelay( self.DefaultTurboDelay ) self:SetReverseForce( self.DefaultReverseForce ) self:SetReverseMaxSpeed( self.DefaultReverseMaxSpeed ) self:SetBreakForce( self.DefaultBreakForce ) self:SetSteerForce( self.DefaultSteerForce ) self:SetSteerResponse( self.DefautlSteerResponse ) self:SetStabilisation( self.DefaultStabilisation ) self:SetNrOfGears( self.DefaultNrOfGears ) self:SetAntiSlide( self.DefaultAntiSlide ) self:SetAutoStraighten( self.DefaultAutoStraighten ) self:SetSuspensionAddHeight( self.DeafultSuspensionAddHeight ) self:SetHydraulicActive( self.DefaultHydraulicActive ) end end function ENT:SpecialThink() end function ENT:SpecialRemove() end function ENT:SpecialReposition() end
pick = {} local pick = pick --队列顶部 pick.top = 0 pick.top_max = 100 --预设单位组 pick.groups = {} for i = 1, pick.top_max do pick.groups[i] = jass.CreateGroup() end --预设 pick.tables = {} --预设condition pick.range_condition_1 = jass.Condition( function() local u = unit.j_unit(jass.GetFilterUnit()) local top = pick.top local this = pick.tables[top] local from = this.from if this.range + from.collision + u.collision >= this.point:distanceUnit(u) then if (not this.filter or this.filter(from, u)) and (not this.func or not this.func(u)) then table.insert(this.table, u) end end end ) pick.range_condition_2 = jass.Condition( function() local u = unit.j_unit(jass.GetFilterUnit()) local top = pick.top local this = pick.tables[top] local from = this.from print(u) if (not this.filter or this.filter(from, u)) and (not this.func or not this.func(u)) then table.insert(this.table, u) end end ) --筛选器 function pick.filter(str, filter) local fi = table.key(str:split ',') return function(this, u) --检查敌对性 if fi['敌人'] and not u:isEnemy(this:owner()) then return end --检查英雄 if fi['英雄'] and u.type ~= 'hero' then return end --检查可见度 if fi['可见'] and not u:isVisible(this:owner()) then return end --是否包含死亡单位 if u.dead and not fi['死亡'] then return end --检查自定义条件 if filter then return filter(this, u) end return true end end --选取圆形范围内的单位 function pick.range(this) --[[结构 point = 选取位置 from = 选取来源 range = 选取半径 collision = 是否计算碰撞 filter = 筛选器 table = 添加组 func = 执行函数 --]] --增加顶部技术 local top = pick.top + 1 pick.top = top --debug if top > pick.top_max then print('create pick.group !! ' .. top) pick.groups[top] = jass.CreateGroup() end --开始选取 local x, y = this.point:get() this.table = this.table or {} pick.tables[top] = this if this.collision then --计算碰撞 jass.GroupEnumUnitsInRange(pick.groups[top], x, y, this.range + 100, pick.range_condition_1) else --不计算碰撞 jass.GroupEnumUnitsInRange(pick.groups[top], x, y, this.range, pick.range_condition_2) end pick.top = top - 1 return this.table end
player_manager.AddValidModel( "PMC6_03", "models/player/PMC_6/PMC__03.mdl" ) list.Set( "PlayerOptionsModel", "PMC6_03", "models/player/PMC_6/PMC__03.mdl" )
TV_SMOOTHER = TV_SMOOTHER or {} TV_SMOOTHER.INTERP_LINEAR = 0 function TV_SMOOTHER:create( smoothingduration, samples_per_duration, startamount ) startamount = startamount or 0.0 local instance = {} setmetatable(instance,self) self.__index = self instance.smoothingduration = smoothingduration instance.samples_per_duration = samples_per_duration instance.prev_average = startamount instance.next_average = startamount instance.time_of_next_sample = RealTime() + smoothingduration/samples_per_duration instance.new_sample_flag = false instance.samples = {} instance.sample_index_offset = 0 for i = 0, samples_per_duration do table.insert( instance.samples, startamount ) end return instance end function TV_SMOOTHER:Update( val ) --print( self, "update" ) --PrintTable( self.samples ) local t = RealTime() if t >= self.time_of_next_sample then --print( self, "SAMPLE" ) self.new_sample_flag = true self.time_of_next_sample = t + self.smoothingduration/self.samples_per_duration self.sample_index_offset = (self.sample_index_offset + 1) % #self.samples self.samples[self.sample_index_offset+1] = val self.prev_average = 1.0*self.next_average self.next_average = 0.0 for i = 1, #self.samples do self.next_average = self.next_average + self.samples[i] end self.next_average = self.next_average / #self.samples end end function TV_SMOOTHER:GetValue() local t = RealTime() local time_before_next_sample = self.time_of_next_sample - t local p = 1 - (time_before_next_sample*self.samples_per_duration/self.smoothingduration) --[[ local buffer = {} for i = 1, #self.samples do buffer[i] = self.samples[(i-self.sample_index_offset)%#self.samples+1] end for i = #buffer, 1, -1 do for j = 1, i-1 do buffer[j] = Lerp(p, buffer[j], buffer[j+1]) end end return buffer[1] ]] return Lerp( p, self.prev_average, self.next_average ) end
-- Inline 4 engines -- Petrol ACF_DefineEngine( "1.5-I4", { name = "1.5L I4 Petrol", desc = "Small car engine, not a whole lot of git", model = "models/engines/inline4s.mdl", sound = "acf_base/engines/i4_petrolsmall2.wav", category = "I4", fuel = "Petrol", enginetype = "GenericPetrol", weight = 50, torque = 112, flywheelmass = 0.06, idlerpm = 900, peakminrpm = 4000, peakmaxrpm = 6500, limitrpm = 7500 } ) ACF_DefineEngine( "3.7-I4", { name = "3.7L I4 Petrol", desc = "Large inline 4, sees most use in light trucks", model = "models/engines/inline4m.mdl", sound = "acf_base/engines/i4_petrolmedium2.wav", category = "I4", fuel = "Petrol", enginetype = "GenericPetrol", weight = 200, torque = 300, flywheelmass = 0.2, idlerpm = 900, peakminrpm = 3700, peakmaxrpm = 6000, limitrpm = 6500 } ) ACF_DefineEngine( "16.0-I4", { name = "16.0L I4 Petrol", desc = "Giant, thirsty I4 petrol, most commonly used in boats", model = "models/engines/inline4l.mdl", sound = "acf_base/engines/i4_petrollarge.wav", category = "I4", fuel = "Petrol", enginetype = "GenericPetrol", weight = 600, torque = 1062, flywheelmass = 4, idlerpm = 500, peakminrpm = 1750, peakmaxrpm = 3250, limitrpm = 3500 } ) -- Diesel ACF_DefineEngine( "1.6-I4", { name = "1.6L I4 Diesel", desc = "Small and light diesel, for low power applications requiring a wide powerband", model = "models/engines/inline4s.mdl", sound = "acf_base/engines/i4_diesel2.wav", category = "I4", fuel = "Diesel", enginetype = "GenericDiesel", weight = 90, torque = 187, flywheelmass = 0.2, idlerpm = 650, peakminrpm = 1000, peakmaxrpm = 3000, limitrpm = 5000 } ) ACF_DefineEngine( "3.1-I4", { name = "3.1L I4 Diesel", desc = "Light truck duty diesel, good overall grunt", model = "models/engines/inline4m.mdl", sound = "acf_base/engines/i4_dieselmedium.wav", category = "I4", fuel = "Diesel", enginetype = "GenericDiesel", weight = 250, torque = 400, flywheelmass = 1, idlerpm = 500, peakminrpm = 1150, peakmaxrpm = 3500, limitrpm = 4000 } ) ACF_DefineEngine( "15.0-I4", { name = "15.0L I4 Diesel", desc = "Small boat sized diesel, with large amounts of torque", model = "models/engines/inline4l.mdl", sound = "acf_base/engines/i4_diesellarge.wav", category = "I4", fuel = "Diesel", enginetype = "GenericDiesel", weight = 800, torque = 1750, flywheelmass = 5, idlerpm = 450, peakminrpm = 500, peakmaxrpm = 1800, limitrpm = 2100 } )
local assign = require(script.Parent.assign) local None = require(script.Parent.None) local Ref = require(script.Parent.PropMarkers.Ref) local config = require(script.Parent.GlobalConfig).get() local excludeRef = { [Ref] = None, } --[[ Allows forwarding of refs to underlying host components. Accepts a render callback which accepts props and a ref, and returns an element. ]] local function forwardRef(render) if config.typeChecks then assert(typeof(render) == "function", "Expected arg #1 to be a function") end return function(props) local ref = props[Ref] local propsWithoutRef = assign({}, props, excludeRef) return render(propsWithoutRef, ref) end end return forwardRef
-->> recusive_func :: integer >> integer local function recusive_func(v) return recusive_func(v) end print(recusive_func(3))
local displayTime = true local displayDate = true local timeAndDateString = nil function CalculateDayOfWeekToDisplay() if dayOfWeek == 1 then dayOfWeek = "Sunday" elseif dayOfWeek == 2 then dayOfWeek = "Monday" elseif dayOfWeek == 3 then dayOfWeek = "Tuesday" elseif dayOfWeek == 4 then dayOfWeek = "Wednesday" elseif dayOfWeek == 5 then dayOfWeek = "Thursday" elseif dayOfWeek == 6 then dayOfWeek = "Friday" elseif dayOfWeek == 7 then dayOfWeek = "Saturday" end end function CalculateDateToDisplay() if month == 1 then month = "January" elseif month == 2 then month = "February" elseif month == 3 then month = "March" elseif month == 4 then month = "April" elseif month == 5 then month = "May" elseif month == 6 then month = "June" elseif month == 7 then month = "July" elseif month == 8 then month = "August" elseif month == 9 then month = "September" elseif month == 10 then month = "October" elseif month == 11 then month = "November" elseif month == 12 then month = "December" end end function CalculateTimeToDisplay() if hour <= 9 then hour = tonumber("0" .. hour) end if minute <= 9 then minute = tonumber("0" .. minute) end end AddEventHandler("playerSpawned", function() Citizen.CreateThread(function() while true do Wait(1) year, month, dayOfWeek, hour, minute = GetLocalTime() timeAndDateString = "|" CalculateTimeToDisplay() if displayTime == true then timeAndDateString = " " .. hour .. ":" .. minute .. " |" end if displayDate == true then CalculateDateToDisplay() timeAndDateString = timeAndDateString .. " " .. dayOfWeek .. " " .. month .. " " .. year .. "" end SetTextFont(0) SetTextProportional(1) SetTextScale(0.30, 0.30) SetTextColour(255, 255, 255, 255) SetTextDropshadow(0, 0, 0, 0, 255) SetTextEdge(1, 0, 0, 0, 255) SetTextDropShadow() SetTextOutline() SetTextRightJustify(true) SetTextWrap(0,0.95) SetTextEntry("STRING") AddTextComponentString(timeAndDateString) DrawText(0.5, 0.01) end end) end)
require 'nn' require 'graph' nngraph = {} require('nngraph.nest') require('nngraph.node') require('nngraph.gmodule') require('nngraph.graphinspecting') require('nngraph.JustElement') require('nngraph.JustTable') require('nngraph.ModuleFromCriterion') -- handy functions local utils = require('nngraph.utils') local istensor = torch.isTensor local istable = utils.istable local istorchclass = utils.istorchclass -- simpler todot functions nngraph.simple_print = require('nngraph.simple_print') -- Modify the __call function to hack into nn.Module local Module = torch.getmetatable('nn.Module') function Module:__call__(...) local nArgs = select("#", ...) assert(nArgs <= 1, 'Use {input1, input2} to pass multiple inputs.') local input = ... if nArgs == 1 and input == nil then error(utils.expectingNodeErrorMessage(input, 'inputs', 1)) end -- Disallow passing empty table, in case someone passes a table with some -- typo'd variable name in. if type(input) == 'table' and next(input) == nil then error('cannot pass an empty table of inputs. To indicate no incoming ' .. 'connections, leave the second set of parens blank.') end if not istable(input) then input = {input} end local mnode = nngraph.Node({module=self}) local dnode for i = 1, utils.tableMaxN(input) do dnode = input[i] if torch.typename(dnode) ~= 'nngraph.Node' then error(utils.expectingNodeErrorMessage(dnode, 'inputs', i)) end mnode:add(dnode,true) end return mnode end local Criterion = torch.getmetatable('nn.Criterion') function Criterion:__call__(...) return nn.ModuleFromCriterion(self)(...) end Module.__unm__ = function( obj ) return obj() end Module.__sub__ = function( prev, next ) return next(prev) end do local Node = torch.getmetatable('nngraph.Node') Node.__sub__ = function( prev, next ) return next(prev) end end return nngraph
package("qt5core") set_base("qt5lib") on_load(function (package) package:data_set("libname", "Core") if package:is_plat("android") then package:data_set("syslinks", "z") elseif package:is_plat("iphoneos") then package:data_set("frameworks", {"UIKit", "CoreText", "CoreGraphics", "CoreServices", "CoreFoundation"}) package:data_set("syslinks", {"qtpcre2", "z"}) end package:base():script("load")(package) package:set("kind", "library") end) on_test(function (package) local cxflags if not package:is_plat("windows") then cxflags = "-fPIC" end assert(package:check_cxxsnippets({test = [[ int test(int argc, char** argv) { QCoreApplication app (argc, argv); return app.exec(); } ]]}, {configs = {languages = "c++14", cxflags = cxflags}, includes = {"QCoreApplication"}})) end)
function check(enum, search) for id, v in ipairs(df[enum]) do if v:lower():find(search) then print(enum .. ' ' .. v) end end end search = ({...})[1]:lower() check('building_type', search) check('item_type', search)
--[[ File: cw_interface.lua Author: toneo Realm: Server cw_interface allows the map and the gamemode to communicate. ]]-- -- Point entities have no model and are extremely cheap. ENT.Type = "point" --[[ Name: ENT:AcceptInput( inputName, activator, caller, data ) Desc: Called when an input is triggered. ]] function ENT:AcceptInput( inputName, activator, caller, data ) if inputName == "StartRound" then if not GAMEMODE:IsRoundInProgress() then GAMEMODE:StartRound() self:TriggerOutput( "OnRoundStarted", self ) end end end --[[ Name: ENT:KeyValue( key, value ) Desc: Called when this entity has an input triggered, usually by something in the map. ]] function ENT:KeyValue( key, value ) -- All of our outputs start with 'On' if string.Left( key, 2 ) == "On" then -- Store so they can be triggered later self:StoreOutput( key, value ) end end
add_rules("mode.debug", "mode.release") add_requires("zig 0.9.x") target("test") set_kind("binary") add_files("src/*.cpp") set_toolchains("@zig")
includeFile("talus/aakuan_anarchist.lua") includeFile("talus/aakuan_champion.lua") includeFile("talus/aakuan_defender.lua") includeFile("talus/aakuan_follower.lua") includeFile("talus/aakuan_guardian.lua") includeFile("talus/aakuan_keeper.lua") includeFile("talus/aakuan_sentinel.lua") includeFile("talus/aakuan_spice_guard.lua") includeFile("talus/aakuan_steward.lua") includeFile("talus/aakuan_warder.lua") includeFile("talus/aakuan_assassin.lua") includeFile("talus/berserk_kahmurra.lua") includeFile("talus/binayre_chief.lua") includeFile("talus/binayre_hooligan.lua") includeFile("talus/binayre_pirate.lua") includeFile("talus/binayre_ruffian.lua") includeFile("talus/binayre_scalawag.lua") includeFile("talus/binayre_smuggler.lua") includeFile("talus/binayre_swindler.lua") includeFile("talus/blister_rot_mite_queen.lua") includeFile("talus/bothan_diplomat.lua") includeFile("talus/bothan_information_broker.lua") includeFile("talus/chunker_braggart.lua") includeFile("talus/chunker_bruiser.lua") includeFile("talus/chunker_bully.lua") includeFile("talus/chunker_creep.lua") includeFile("talus/chunker_goon.lua") includeFile("talus/chunker_mooch.lua") includeFile("talus/chunker_nitwit.lua") includeFile("talus/chunker_pest.lua") includeFile("talus/chunker_punk.lua") includeFile("talus/chunker_swindler.lua") includeFile("talus/clipped_fynock.lua") includeFile("talus/crazed_roba.lua") includeFile("talus/cyst_covered_rot_mite_guard.lua") includeFile("talus/decay_mite.lua") includeFile("talus/doak_sif.lua") includeFile("talus/docile_kahmurra.lua") includeFile("talus/dung_mite.lua") includeFile("talus/dung_mite_worker.lua") includeFile("talus/erran_sif.lua") includeFile("talus/famished_sludge_panther.lua") includeFile("talus/feared_fynock_youth.lua") includeFile("talus/fearful_fynock_youth.lua") includeFile("talus/fed_dub_captain.lua") includeFile("talus/fed_dub_commander.lua") includeFile("talus/fed_dub_constable.lua") includeFile("talus/fed_dub_investigator.lua") includeFile("talus/fed_dub_patrolman.lua") includeFile("talus/fed_dub_supporter.lua") includeFile("talus/feeble_kima.lua") includeFile("talus/female_roba.lua") includeFile("talus/ferine_razorfang.lua") includeFile("talus/festering_dung_mite_queen.lua") includeFile("talus/flite_rasp.lua") includeFile("talus/foaming_vynock.lua") includeFile("talus/frenzied_fynock_guardian.lua") includeFile("talus/frenzied_kahmurra.lua") includeFile("talus/fynock.lua") includeFile("talus/genetically_enchanced_kahmurra.lua") includeFile("talus/giant_decay_mite_guardian.lua") includeFile("talus/giant_decay_mite_harvester.lua") includeFile("talus/giant_decay_mite_hatchling.lua") includeFile("talus/giant_decay_mite_protector.lua") includeFile("talus/giant_decay_mite_queen.lua") includeFile("talus/giant_decay_mite_sentry.lua") includeFile("talus/giant_decay_mite_soldier.lua") includeFile("talus/giant_fynock.lua") includeFile("talus/giga_flite_rasp.lua") includeFile("talus/glutted_fynock_queen.lua") includeFile("talus/greater_sludge_panther.lua") includeFile("talus/guf_drolg_female.lua") includeFile("talus/guf_drolg.lua") includeFile("talus/hilltop_kima.lua") includeFile("talus/hirsch_sif.lua") includeFile("talus/huf_dun_bull.lua") includeFile("talus/huf_dun.lua") includeFile("talus/jungle_fynock.lua") includeFile("talus/kahmurra.lua") includeFile("talus/kima.lua") includeFile("talus/lost_aqualish_bomber.lua") includeFile("talus/lost_aqualish_captain.lua") includeFile("talus/lost_aqualish_commando.lua") includeFile("talus/lost_aqualish_infiltrator.lua") includeFile("talus/lost_aqualish_lookout.lua") includeFile("talus/lost_aqualish_marksman.lua") includeFile("talus/lost_aqualish_marshall.lua") includeFile("talus/lost_aqualish_outrider.lua") includeFile("talus/lost_aqualish_scout.lua") includeFile("talus/lost_aqualish_soldier.lua") includeFile("talus/lost_aqualish_warchief.lua") includeFile("talus/lost_aqualish_warrior.lua") includeFile("talus/male_roba.lua") includeFile("talus/meager_tortur.lua") includeFile("talus/minor_guf_drolg.lua") includeFile("talus/minor_sludge_panther.lua") includeFile("talus/mire_marauder.lua") includeFile("talus/mutated_kahmurra.lua") includeFile("talus/oozing_dung_mite_guardian.lua") includeFile("talus/percussive_rasp.lua") includeFile("talus/poacher.lua") includeFile("talus/puss_covered_decay_mite_soldier.lua") includeFile("talus/putrid_decay_mite_hatchling.lua") includeFile("talus/rabid_mutant_kahmurra.lua") includeFile("talus/ravenous_rasp.lua") includeFile("talus/repugnant_dung_mite_crawler.lua") includeFile("talus/rodian_sif_02.lua") includeFile("talus/rodian_sif.lua") includeFile("talus/rot_mite.lua") includeFile("talus/rotting_decay_mite_guard.lua") includeFile("talus/savage_guf_drolg.lua") includeFile("talus/sickly_decay_mite_queen.lua") includeFile("talus/sif_mercenary.lua") includeFile("talus/sleemo_delinquent.lua") includeFile("talus/sleemo_hoodlum.lua") includeFile("talus/sleemo_punk.lua") includeFile("talus/sleemo_scamp.lua") includeFile("talus/sleemo_vandal.lua") includeFile("talus/sludge_panther.lua") includeFile("talus/song_rasp.lua") includeFile("talus/stunted_huf_dun.lua") includeFile("talus/talus_liberation_party_activist.lua") includeFile("talus/talus_liberation_party_fanatic.lua") includeFile("talus/talus_liberation_party_loyalist.lua") includeFile("talus/talus_liberation_party_partisan.lua") includeFile("talus/talus_liberation_party_patriot.lua") includeFile("talus/talus_liberation_party_reactionist.lua") includeFile("talus/talus_liberation_party_volunteer.lua") includeFile("talus/tortur_bull.lua") includeFile("talus/tortur.lua") includeFile("talus/trandoshan_sif_02.lua") includeFile("talus/vicious_huf_dun.lua") includeFile("talus/voracious_rasp.lua") includeFile("talus/wolf_kima.lua") includeFile("talus/woodland_kima.lua")
-- **WARNING** This lib is *only* for Lua 5.4+, which has dropped bit32 -- this is a lib which allows Lua 5.4 to run scripts written for LuaJIT, -- luau, and other implmentations based on some variant of Lua 5.1 + bit32 -- -- This file should be loaded as follows: -- -- if not bit32 and tonumber((string.gsub(_VERSION,'^[^ ]+',''))) > 5.3 then -- require("bit32") -- end -- -- Pure Lua implementation of bit32 for Lua 5.4+ -- This is only for Lua 5.4+; Lua 5.3 and Lua 5.2 have bit32, and -- there are various workarounds for Lua 5.1 (LuaJIT uses bit, which -- is similar; Roblox luau uses bit32; my own lunacy uses a subset of -- bit32; etc.) bit32 = {} bit32.band = function(a,...) for _,v in pairs({...}) do a = a & v end return a & 0xffffffff end bit32.bor = function(a,...) for _,v in pairs({...}) do a = a | v end return a & 0xffffffff end bit32.bxor = function(a,...) for _,v in pairs({...}) do a = a ~ v end return a & 0xffffffff end bit32.bnot = function(a) return ~a & 0xffffffff end bit32.lshift = function(a,r) return (a << r) & 0xffffffff end bit32.rshift = function(a,r) return (a & 0xffffffff) >> r end bit32.rrotate = function(a,r) r = r % 32 a = a & 0xffffffff if r == 0 then return a end return ((a >> r) | (a << (32 - r))) & 0xffffffff end bit32.arshift = function(a,r) if (a & 0x80000000) == 0 then return (a & 0xffffffff) >> r end a = a & 0xffffffff for i=1,r do a = a >> 1 a = a | 0x80000000 end return a end
-- Gives starting items -- Taken from bb template if StartingItems == nil then Debug.EnabledModules['startingitems:*'] = true DebugPrint ( 'creating new StartingItems object' ) StartingItems = class({}) end function StartingItems:Init () --StartingItems.itemList = {"item_farming_core"} --GameEvents:OnHeroInGame(StartingItems.GiveStartingItems) end function StartingItems.GiveStartingItems (hero) if hero:GetTeamNumber() == DOTA_TEAM_NEUTRALS then return end if #StartingItems.itemList <= 0 then return end -- We have a timer here so that the courier stuff doesn't interfere Timers:CreateTimer(1.54, function () DebugPrint("Giving starting items to " .. hero:GetUnitName()) -- Create couriers and then cast them straight away for _, itemName in pairs(StartingItems.itemList) do local item = hero:AddItemByName(itemName) -- no idea if this stuff is gonna be used for anything other than farming cores -- but if it is, let's emulate dota random bonuses ( aka can't be sold ) -- item:SetSellable(false) -- this removes the right-click menu that's a terrible idea end end) end
local IOAlertEmitter = require "IOAlertEmitter" local EventLoop = { MaxEvents = 16, } local EventLoop_mt = { __index = EventLoop, } EventLoop.new = function(timeout, maxevents) maxevents = maxevents or EventLoop.MaxEvents local obj = { Observers = {}, Emitter = IOAlertEmitter.new(timeout, maxevents), Running = false; } setmetatable(obj, EventLoop_mt); return obj; end EventLoop.AddObservable = function(self, observable, observer) observer = observer or observable self.Observers[observable.AlertHandle:getfd()] = observer; return self.Emitter:AddAlertable(observable.AlertHandle, observer.OnAlert, observable.WhichAlerts); end EventLoop.Halt = function(self) self.Running = false; end EventLoop.OnPollEnd = function(self, alerts, count) if alerts and count > 0 then for i=0,count-1 do --print("Event: ", alerts[i].data.fd, alerts[i].events); -- get the appropriate observer local observer = self.Observers[alerts[i].data.fd]; if observer and observer.OnAlert then observer:OnAlert(self, alerts[i].data.fd, alerts[i].events) end end end end EventLoop.Run = function(self, timeout) timeout = timeout or 0 self.Running = true; while self.Running do if self.OnPollBegin then self.OnPollBegin(self) end local alerts, count = self.Emitter:EPollWait() if self.OnPollEnd then self.OnPollEnd(self, alerts, count) end -- Allow some idle work to occur if self.OnIdle then self.OnIdle(self) end end end return EventLoop;
include("AddSFML.lua") project "Bomberman" kind "ConsoleApp" language "C++" cppdialect "C++11" -- "workspaceFolder" is defined in premake5.lua -- Place build files in workspaceFolder/build/projectName location ( path.join( workspaceFolder, "build/%{prj.name}") ) -- Place binary files in workspaceFolder/bin/platformName/configurationName targetdir ( path.join( workspaceFolder, "bin/%{cfg.platform}/%{cfg.buildcfg}") ) includedirs { "../include" } local sfmlOptions = { modules = { graphics = true, window = true, audio = true, network = true, system = true }, root = userConfig.deps.sfml.root, linkDynamic = userConfig.deps.sfml.dynamic, pre250Version = userConfig.deps.sfml.pre250Version or false } sfmlOptions.libDir = path.join(sfmlOptions.root, "lib/%{cfg.platform}/%{cfg.buildcfg}") -- Add SFML (debug version) filter "configurations:Debug" defines { "BOMBERMAN_DEBUG "} addSFML( sfmlOptions.root, sfmlOptions.libDir, sfmlOptions.modules, sfmlOptions.linkDynamic, true, sfmlOptions.pre250Version) -- Add SFML (release version) filter "configurations:Release" addSFML( sfmlOptions.root, sfmlOptions.libDir, sfmlOptions.modules, sfmlOptions.linkDynamic, false, sfmlOptions.pre250Version) filter {"system:windows"} defines { "BOMBERMAN_WINDOWS" } -- Clear filter filter {} files { "../include/Bomberman/**.hpp", "../src/**.cpp" }
--- handles the tally settings file, reads it and provides an interface for --- the other components to get validated, type-safe parameters from. local fileName = "/FLASH/tally-settings.ini" _G.LightTypes = { COMMON_ANODE = "grb+", COMMON_CATHODE = "grb-", } _G.Ws2812Types = { RGB = "rgb", GRB = "grb", } -- defaults local staSsid = nil local staPw = nil local hubIp = nil local hubPort = 7411 local name = string.format("%x", node.chipid()) local operatorType = LightTypes.COMMON_ANODE local operatorWs2812Type = Ws2812Types.GRB local operatorWs2812Lights = 5 local stageType = LightTypes.COMMON_ANODE local stageWs2812Type = Ws2812Types.GRB local stageWs2812Lights = 0 local trim = function(s) return s:match("^%s*(.-)%s*$") end local isValueInTable = function(value, table) for _, val in pairs(table) do if value == val then return true end end return false end local makeHostName = function(s) return "Tally-" .. s:gsub("[^%w]+", "-"):gsub("^\-+", ""):gsub("\-+$", "") end _G.MySettings = { staSsid = function() return staSsid end, staPw = function() return staPw end, hubIp = function() return hubIp end, hubPort = function() return hubPort end, name = function() return name end, hostName = function() return makeHostName(name) end, operatorType = function() return operatorType end, operatorNumberOfWs2812Lights = function() return operatorWs2812Lights end, operatorWs2812Type = function() return operatorWs2812Type end, stageType = function() return stageType end, stageNumberOfWs2812Lights = function() return stageWs2812Lights end, stageWs2812Type = function() return stageWs2812Type end, isValid = function() return staSsid ~= nil and hubIp ~= nil end, } -- -- PARSE SETTINGS FILE -- if file.exists(fileName) then local f = file.open(fileName, "r") if not f then MyLog.error("Could not open settings file " .. fileName .. " to read configuration") else while true do local line = f:readline() if line then local k, v = line:match("^%s*([^=]+)%s*=%s*([^=]+)%s*$") if k ~= nil and v ~= nil and line:sub(1,1) ~= ";" then k = trim(k) -- trim v = trim(v) -- trim if k == "station.ssid" then staSsid = v elseif k == "station.password" then staPw = v elseif k == "hub.ip" then hubIp = v elseif k == "hub.port" then hubPort = tonumber(v) elseif k == "tally.name" then name = v:sub(0, 26) elseif k == "operator.type" then local value = v:lower() if isValueInTable(value, LightTypes) then operatorType = value else MyLog.warning("Invalid operator.type \"" .. v .. "\"") end elseif k == "operator.ws2812" then local value, type local idx = v:find(" ", 1, true) if idx ~= nil then value = v:sub(1, idx-1) type = v:sub(idx+1) else value = v type = nil end value = tonumber(value) if value ~= nil and value >= 0 and value <= 10 then operatorWs2812Lights = value else MyLog.warning("operator.ws2812 needs to be number between 0 and 10, but got \"" .. v .. "\"") end if type ~= nil then if isValueInTable(type, Ws2812Types) then operatorWs2812Type = type else MyLog.warning("operator.ws2812 should have a supported light type, but got \"" .. type .. "\"") end end elseif k == "stage.type" then local value = v:lower() if isValueInTable(value, LightTypes) then stageType = value else MyLog.warning("Invalid stage.type \"" .. v .. "\"") end elseif k == "stage.ws2812" then local value, type local idx = v:find(" ", 1, true) if idx ~= nil then value = v:sub(1, idx-1) type = v:sub(idx+1) else value = v type = nil end value = tonumber(value) if value ~= nil and value >= 0 and value <= 10 then stageWs2812Lights = value else MyLog.warning("stage.ws2812 needs to be number between 0 and 10, but got \"" .. v .. "\"") end if type ~= nil then if isValueInTable(type, Ws2812Types) then stageWs2812Type = type else MyLog.warning("stage.ws2812 should have a supported light type, but got \"" .. type .. "\"") end end else MyLog.warning("Unknown key " .. k .. " in configuration file. Did you mistype it?") end end else break end end f:close() end else MyLog.warning("Configuration file " .. fileName .. " does not exist. Using defaults.") end
local error, pairs, setmetatable, tonumber, tostring, type = error, pairs, setmetatable, tonumber, tostring, type local mtype = math.type or function(n) return 'float' end local find, format = string.find, string.format local concat = table.concat _ENV = nil local huge = 1/0 local tiny = -1/0 local function dump(v) local builder = {} local i = 1 local depth = 0 local depth8 = 0 local view = 1 local usestack local vars = {'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v1'} local vars2 = {'v1[', 'v2[', 'v3[', 'v4[', 'v5[', 'v6[', 'v7[', 'v8['} local var = 'v1' local nextvar = 'v1' local var2 = 'v1[' local nextvar2 = 'v1[' local function incdepth() depth = depth+1 depth8 = depth8+1 if depth8 > 8 then depth8 = 1 end var = nextvar nextvar = vars[depth8+1] var2 = vars2[depth8] if depth >= view+8 then usestack = true view = view+1 builder[i] = 'stack[' builder[i+1] = depth-8 builder[i+2] = ']=' builder[i+3] = var builder[i+4] = '\n' i = i+5 end end local function decdepth() depth = depth-1 depth8 = depth8-1 if depth8 < 1 then depth8 = 8 end nextvar = var var = vars[depth8] nextvar2 = var2 var2 = vars2[depth8] if depth < view and depth > 0 then view = view-1 builder[i] = var builder[i+1] = '=stack[' builder[i+2] = depth builder[i+3] = ']\n' i = i+4 end end local visited = {} local tablefun, tbl local function tableelem(k, v) local vt = type(v) if vt ~= 'table' then local e = tbl[vt](v) builder[i] = var2 builder[i+1] = k builder[i+2] = ']=' builder[i+3] = e builder[i+4] = '\n' i = i+5 return end local olddepth = visited[v] if olddepth then builder[i] = var2 builder[i+1] = k builder[i+2] = ']=' if olddepth >= view then builder[i+3] = vars[(olddepth-1)%8+1] else builder[i+3] = 'stack['..olddepth..']' end builder[i+4] = '\n' i = i+5 return end local oldvar2 = var2 incdepth() visited[v] = depth builder[i] = var builder[i+1] = '={}\n' builder[i+2] = oldvar2 builder[i+3] = k builder[i+4] = ']=' builder[i+5] = var builder[i+6] = '\n' i = i+7 tablefun(v) visited[v] = nil decdepth() end function tablefun(o) for k, v in pairs(o) do k = tbl[type(k)](k) tableelem(k, v) end end tbl = { boolean = tostring, table = function(o) do local olddepth = visited[o] if olddepth then if olddepth >= view then return vars[(olddepth-1)%8+1] else return 'stack['..olddepth..']' end end end incdepth() visited[o] = depth builder[i] = var builder[i+1] = '={}\n' i = i+2 tablefun(o) visited[o] = nil decdepth() return nextvar end, string = function(s) return format('%q', s) end, number = function(n) if tiny < n and n < huge then if mtype(n) == 'float' then n = format('%.17g', n) if not find(n, '[^-0-9]') then n = n .. '.0' end return n else return tonumber(n) end elseif n == huge then return '1/0' elseif n == tiny then return '-1/0' else return '0/0' end end, __index = function(_) error("illegal val") end } setmetatable(tbl, tbl) builder[i] = 'local ' i = i+1 for j = 1, 8 do builder[i] = vars[j] if j < 8 then builder[i+1] = ',' else builder[i+1] = '\n' end i = i+2 end local stackdecl = i builder[i] = "" i = i+1 local e = tbl[type(v)](v) builder[i] = 'return ' builder[i+1] = e i = i+2 if usestack then builder[stackdecl] = 'local stack={}\n' end return concat(builder) end return dump
-- a noun is an atom or a cell -- an atom is a natural number -- a cell is an ordered pair of nouns -- -- a lua noun is a number (direct atom), string (indirect atom), or table (cell) -- a number (atom) is a natural number that fits in 32 bits --TODO 32? -- a string (atom) is a natural number represented as a bytestring, LSB first -- a table (cell) contains two lua nouns: { h, t } -- lua atoms should maintain the following invariants: -- - numbers should be no bigger than mit bits -- - strings should be no smaller than mit+1 bits -- - strings should have no leading zero bytes -- some of the logic here is rather... optimistic. keep in mind: -- - if you must pass lua numbers > 2^mit, use the atom() constructor! -- - string atoms must not contain leading zero bytes (\0 at tail of string)! -- - cue produces deduplicated cells. do not modify them directly! -- lessons learned: -- - traditional lua wisdom says to avoid repeated string concatenation, -- instead building a table and doing table.concat at the end. -- turns out that, in luajit, in our context, this is actually a bit slower! --TODO -- - ot() should be structured like the other functions so it can nest. -- also, needing to pass a table for inserting is awkward for simple cases... -- - stay aware of perf gotchas... --NOTE provided by luajit local bit = require("bit"); -- mit: max direct atom bit-width -- myt: max direct atom byte-width -- man: max direct atom -- local mit = 32; local myt = math.floor( mit / 8 ); local man = math.pow(2, mit) - 1; -- show: noun to string representation -- function show(n) if type(n) == 'table' then return '[' .. show(head(n)) .. ' ' .. show(tail(n)) .. ']'; elseif type(n) == 'string' then local o = ''; local i = #n; while i > 0 do o = o .. string.format('%02x', string.byte(n, i)); --TODO bit.tohex? i = i - 1; if i > 0 and i % 2 == 0 then o = o .. '.' end end return '0x' .. o; elseif type(n) == 'number' then return tostring(n); else assert(false, 'show: not noun'); end end -- atom: make an atom from a lua number or string -- function atom(a) if type(a) == 'string' then return a; elseif type(a) == 'nil' then return 0; elseif type(a) == 'number' then return grow(a); else assert(false, 'atom: not'); end end -- wtpt: return true iff n is an atom -- function wtpt(n) return type(n) == 'number' or type(n) == 'string'; end -- cons: make a cell from lua nouns -- function cons(h, t, ...) if select('#', ...) > 0 then t = cons(t, ...); end return { h = h, t = t }; --TODO metatables? tostring, concat, head, tail... end -- head: get the head from a cell -- function head(n) assert(type(n) == 'table', 'head: not cell'); return n.h; end -- tail: get the tail from a cell -- function tail(n) assert(type(n) == 'table', 'tail: not cell'); return n.t; end -- eq: test noun equality, unifying if equal -- function eq(a, b) if type(a) ~= type(b) then return false; end if type(a) ~= 'table' then return a == b; else local res = eq(head(a), head(b)) and eq(tail(a), tail(b)); if res then b = a; end return res; end end -- curl: string atom to number atom, if it fits -- function curl(a) if type(a) == 'number' then return a; end assert(type(a) == 'string', 'curl: not string atom'); --TODO check last byte, met(0, a) if #a <= myt then return coil(a); else return a; end end -- coil: string atom to number atom -- function coil(a) if type(a) == 'number' then return a; end assert(type(a) == 'string', 'coil: not string atom'); --TODO check last byte, met(0, a) assert(#a <= myt, 'coil: atom too big'); local b = 0; for i=1,#a do b = b + ( string.byte(a, i) * math.pow(256, i-1) ); end return b; end -- grow: number atom to string atom -- function grow(a) if type(a) == 'string' then return a; end --TODO trim leading zeroes? assert(type(a) == 'number', 'grow: not number atom'); local b = ''; while a > 0 do b = b .. string.char(a % 256); a = math.floor(a / 256); end return b; end -- add: integer addition -- function add(a, b) a = grow(a); b = grow(b); local i = 1; local c = 0; local o = ''; while i <= #a or i <= #b or c > 0 do c = c + (string.byte(a, i) or 0) + (string.byte(b, i) or 0); o = o .. string.char(c % 256); if c < 256 then c = 0; else c = 1; end i = i + 1; end return curl(o); end -- sub: integer subtraction -- function sub(a, b) if type(a) == 'number' and type(b) == 'number' then assert(a >= b, 'sub: underflow'); return a - b; else a = grow(a); b = grow(b); local i = 1; local c = 0; local o = ''; while i <= #a or i <= #b or c > 0 do c = ( c + (string.byte(a, i) or 0) ) - (string.byte(b, i) or 0); if c >= 0 then o = o .. string.char(c); c = 0; else o = o .. string.char( 256 + c ); c = -1; end i = i + 1; end assert(c >= 0, 'sub: underflow'); return curl(o); end end -- div: integer division -- function div(a, b) assert(b ~= 0, 'div: by zero'); if b == 1 then return a; end if type(a) == 'number' and type(b) == 'number' then return math.floor(a / b); else a = grow(a); b = grow(b); if mod(b, 2) == 0 then return rsh(cons(0, rsh(0, b)), a); else --TODO lol local c = 0; while lte(b, a) do a = sub(a, b); c = add(c, 1); end return c; end end end -- mod: modulus -- function mod(a, b) if type(b) == 'number' then if type(a) == 'number' then return a % b; elseif type(a) == 'string' then return coil( ned(cons(3, met(3, b)), a) ) % b; else assert(false, 'mod: a not atom'); end elseif type(b) == 'string' then if type(a) == 'number' then return a; --NOTE relies on string atom hygeine elseif type(a) == 'string' then assert(false, 'mod: todo'); --TODO coil else assert(false, 'mod: a not atom'); end else assert(false, 'mod: b not atom'); end end -- mul: multiply -- function mul(a, b) local o = 0; --TODO lol if lte(a, b) then if a == 2 then return lsh(0, b); end while a ~= 0 do o = add(o, b); a = sub(a, 1); end else if b == 2 then return lsh(0, a); end while b ~= 0 do o = add(o, a); b = sub(b, 1); end end return o; end function lte(a, b) if type(a) == 'number' and type(b) == 'number' then return a <= b; else a = grow(a); b = grow(b); if #a ~= #b then return #a < #b; else local i = #a; while i > 0 do local c = string.byte(a, i); local d = string.byte(b, i); if c ~= d then return c <= d; end i = i - 1; end return true; -- equal end end end -- bex: binary exponent -- function bex(a) if a == 0 then return 1; end --TODO assumes hygeine return mul(2, bex(sub(a, 1))); --TODO dec? end -- bix: bits in bite -- function bix(b) if type(b) ~= 'table' then return curl(bex(b)); else return curl(mul(bex(head(b)), tail(b))); end end -- rsh: right-shift bite-wise -- function rsh(b, a) local z = bix(b); if type(a) == 'number' then if type(z) == 'number' then return bit.rshift(a, z); else --NOTE rshifting a number < 2^mit by > 2^mit bits will definitely give 0 return 0; end elseif type(a) == 'string' then local s = div(z, 8); assert(type(s) == 'number', 'rsh: s not direct'); --NOTE see comment in ned() local r = mod(z, 8); assert(type(r) == 'number', 'rsh: r not direct'); if r == 0 then return string.sub(a, s+1); else local o = ''; while s < #a do local b = string.byte(a, s+1); local n = string.byte(a, s+2) or 0; local p = bit.rshift(b, r) + ( bit.lshift(n, 8 - r) % 0x100 ); o = o .. string.char(p); s = s + 1; end return curl(o); end else assert(false, 'rsh: not atom'); end end -- lsh: left-shift an atom -- function lsh(b, a) local z = bix(b); if type(a) == 'number' then if (met(0, a) + z) > mit then return lsh(b, grow(a)); else return bit.lshift(a, z); end elseif type(a) == 'string' then local s = div(z, 8); assert(type(s) == 'number', 'rsh: s not direct'); --NOTE see comment in ned() local r = mod(z, 8); assert(type(r) == 'number', 'rsh: r not direct'); if r == 0 then return string.rep('\0', s) .. a; else local o = string.rep('\0', s); local i = 0; while i <= #a do local b = string.byte(a, i+1) or 0; local l = string.byte(a, i) or 0; local p = ( bit.lshift(b, r) % 0x100 ) + ( bit.rshift( l, 8 - r ) ); i = i + 1; o = o .. string.char(p); end --TODO above produces leading zero bytes (for exmple, 0^9 'abc') -- feels like an off-by-one... while string.byte(o, #o) == 0 do o = string.sub(o, 1, #o-1); end return curl(o); end else assert(false, 'lsh: not atom'); end end -- ned: tail bites (end) -- function ned(b, a) if type(b) ~= 'table' then b = cons(b, 1); end if type(a) == 'number' then local o = mod(a, bex( bix(b) )); return o; elseif type(a) == 'string' then if head(b) == 3 and type(tail(b)) == 'number' then return curl(string.sub(a, 1, tail(b))); else local s = bix(b); local f = div(s, 8); --TODO this implies an atom limit! but how else can we string.byte w/ f? -- would be a 2^32 bytes = 4.2 GB bigatom limit... -- we might be able to do 2^53 if context allows, -- by having a forceCoil() that asserts it's commutative. assert(type(f) == 'number', 'ned: bounds!'); if f >= #a then return a; end local o = string.sub(a, 1, f); local r = mod(s, 8); if r ~= 0 then o = o .. string.char(ned(cons(0, r), string.byte(a, f+1))); end return curl(o); end else assert(false, 'ned: not atom'); end end -- cut: slice bites -- function cut(b, c, d, a) return ned(cons(b, d), rsh(cons(b, c), a)); end -- cat: concatenate -- function cat(b, a, c) local s = met(b, a); return add(a, lsh(cons(b, s), c)); end -- mix: binary xor -- function mix(a, b) if type(a) == 'number' and type(b) == 'number' then return bit.bxor(a, b); else a = grow(a); b = grow(b); local i = 1; local o = ''; while i <= #a or i <= #b do local c = string.byte(a, i) or 0; local d = string.byte(b, i) or 0; o = o .. string.char(bit.bxor(c, d)); i = i + 1; end return curl(o); end end -- met: measure blocwidth -- function met(b, a) if type(a) == 'number' then local c = 0; while a ~= 0 do a = rsh(b, a); c = c + 1; end return c; elseif type(a) == 'string' then local w8 = #a; if b == 3 then return w8; --NOTE relies on string atom hygeine! else local lead = met(0, string.byte(a, w8)); --NOTE larger blocsizes don't need if b > 3 then local bits = ((w8-1) * 8) + lead; return math.ceil( bits / bex(b) ); else local bits = add(mul(sub(w8, 1), 8), lead); --TODO dec? return div(bits, bex(b)); end end else assert(false, 'met: not atom'); end end -- mat: length-encode (result, bitlength) -- function mat(a) assert(wtpt(a), 'mat: not atom'); if a == 0 then return 1, 1; end local b = met(0, a); local c = met(0, b); local d = cons(0, c-1); return cat(0, bex(c), mix( ned(d, b), lsh(d, a) )), add(add(c, c), b); end -- rub: length-decode (value, bitlength) -- function rub(a, b) assert(wtpt(a), 'rub: a not atom'); assert(wtpt(b), 'rub: b not atom'); local c = 0; local m = met(0, b); assert(lte(c, m), 'rub: invalid?'); while 0 == cut(0, add(a, c), 1, b) do assert(lte(c, m), 'rub: invalid?'); c = add(c, 1); end if c == 0 then return 0, 1; end local d = add(a, add(c, 1)); --TODO inc local e = add(bex(sub(c, 1)), cut(0, d, sub(c, 1), b)); --TODO dec return cut(0, add(d, sub(c, 1)), e, b), add(add(c, c), e); end -- jam: pack a lua noun into a lua atom -- function jam(n, i, m) i = i or 0; m = m or {}; if m[n] then if type(n) ~= 'table' and lte(met(0, n), met(0, m[n])) then local p, q = mat(n); return lsh(0, p), add(1, q), m; else local p, q = mat(m[n]); return mix(3, lsh(cons(0, 2), p)), add(2, q), m; end elseif wtpt(n) then m[n] = i; local p, q = mat(n); return lsh(0, p), add(1, q), m; elseif type(n) == 'table' then --TODO figure out how to use cells as keys so we can deduplicate them -- perhaps just use the jam value? -- but then we'd have to do that for atoms too, which is a bit sad... -- m[n] = i; i = add(i, 2); local jh, ih, m = jam(head(n), i, m); local jt, it, m = jam(tail(n), add(i, ih), m); return mix(1, lsh(cons(0, 2), cat(0, jh, jt))), add(2, add(ih, it)), m; else assert(false, 'jam: not noun'); end end -- cue: unpack a lua atom into a lua noun -- function cue(a, i, m) assert(wtpt(a), 'cue: not atom'); i = i or 0; m = m or {}; if 0 == cut(0, i, 1, a) then local p, q = rub(add(i, 1), a); m[i] = p; return p, add(q, 1), m; end local c = add(2, i); if 0 == cut(0, add(i, 1), 1, a) then local dh, ih, m = cue(a, c, m); local dt, it, m = cue(a, add(ih, c), m); local n = cons(dh, dt); m[i] = n; return n, add(2, add(ih, it)), m; else local p, q = rub(c, a); assert(m[p], 'cue: nil ref'); return m[p], add(2, q), m; end end -- ot: takes any number of f(n, t) (that insert n into t), -- produces a function which parses a noun into a table. -- function ot(n, ...) local t = {}; local i = 1; while i <= select('#', ...) do local f = select(i, ...); assert(n ~= 'nil', 'ot: noun too small ' .. i); if wtpt(n) then f(n, t); n = nil; else f(head(n), t); n = tail(n); end i = i + 1; end return t; end -- ar: list noun to array table -- function ar(i, f) return function(n, t) local l = {}; local j = 1; while not wtpt(n) do f(j)(head(n), l); j = j + 1; n = tail(n); end t[i] = l; return t; end end -- no: atom, number or string -- function no(i) return function(n, t) assert(wtpt(n), 'no: not atom'); t[i] = n; return t; end end -- ni: atom, number -- function ni(i) return function(n, t) assert(type(n) == 'number', 'no: not number'); t[i] = n; return t; end end -- ni: atom, as string -- function so(i) return function(n, t) assert(wtpt(n), 'so: not number'); t[i] = grow(n); return t; end end -- nop: no-op -- function nop() end --TMP function pt(t, l) l = l or 0; local d = string.rep(' ', l*2); print(d .. 'table: {', t); for k,v in pairs(t) do if type(v) == 'table' then print(d .. ' ' .. k .. ' ='); pt(v, l+1); else print(d .. ' ' .. k .. ' = ' .. tostring(v)); end end print(d .. '}'); end local n = cons(0, 'nick', cons('blu', 'red', 0), 3, 456, 7, 8); -- [~zod 'nick' ['blu' 'red' ~] 3 456 7 8] local t = ot(n, no('p'), so('name'), ar('colors', so), nop, ni('life')); -- { p = 0, name = 'nick', colors = { 'blu', 'red' }, life = 456 } print(show(n)); pt(t); local testnouns = { { n = 0, j = '2' }, { n = 5, j = '184' }, { n = cons(5, 5), j = '151265' }, { n = cons(cons(5, 5), cons(5, 6)), j = '0x36.2e1b.8b85' }, { n = cons(atom(0xffffffffff), atom(0xffffffffff)), j = '0x49ff.ffff.ffff.a201' } } for _,t in pairs(testnouns) do local j = jam(t.n); local c = cue(j); print(show(j) == t.j, eq(t.n, c), show(t.n)); end local s = os.time(); for i = 1, 100 do for _,t in pairs(testnouns) do local j = jam(t.n); local c = cue(j); end end print(os.time() - s); return 0;
local _M = {} _M._NAME = "bitfield" _M._TYPE = 'module' local _MT = {} local nan = 1%0 local inf = 1/0 _M.width = 16 -- checks if a is a bitfield table, or not. local function isbf(a) return (type(a)=='table' and a._TYPE=='bitfield') and true or false end -- I really shouldn't need this local function bin(n) assert(type(n) == 'number', "dub requires a number") return 2^(n-1) end -- Creates and returns a new bitfield. If opt_num is provided, the initial -- value of the bitfield will be the binary representation of that number, -- otherwise it will be zero. If opt_width is provided t will be used as -- the effective bitwidth of the bitfield, otherwise it will default to -- 16 bits. -- -- Returns: bitfield function _M:new(n, opt_width) n = (type(n)=='number' and n) or 0 local b = {value = n, _TYPE = 'bitfield', width = opt_width or _M.width} setmetatable(b, _MT) return b end -- returns true if the nth bit is set, otherwise returns false. if a bit -- outside the range of the bitfield's width is requested, it returns nil -- instead (which is also logically false) -- -- Returns: bit function _M.GET(self, n) if type(n) ~= 'number' then return _M[n] end if n < 0 then return nil end return self.value % (2*bin(n)) >= bin(n) end _MT.__index = _M.GET --(self, idx) -- Sets the nth bit of bf to the truth value of v -- -- Returns: (nothing) function _M.SET(b, n, v) if not isbf(b) then b = _M:new(b) end assert(n > 0, "Cannot set imaginary bits.") n = bin(n) -- should I simply use the normal lua rules of truth? if type(v) == 'number' then v = ({[true]=1, [false]=0})[v~=0] -- false = 0, true = !false end if v then if b.value % (2*n) < n then b.value = b.value + n end else -- false/clear if b.value % (2*n) >= n then b.value = b.value - n end end return b.value end _MT.__newindex = _M.SET --(self, idx, val) -- Returns a string representing the value contained in the bitfield in -- binary. -- -- Returns: string function _MT.__tostring(self) local s ={} for i=self.width,1,-1 do s[#s+1]=({[true]='1', [false]='0'})[self[i]] end s[#s+1]="b" return table.concat(s) end -- XORs the value of bf with b. Additionally returns the resulting value. -- -- 0 XOR 0 -> 0 -- 0 XOR 1 -> 1 -- 1 XOR 0 -> 1 -- 1 XOR 1 -> 0 -- -- returns: num function _M.XOR(a, b) a = (isbf(a) and a) or _M:new(a) b = (isbf(b) and b) or _M:new(b) for i = 1, a.width do a[i] = a[i] ~= b[i] end a.value = a.value % bin(a.width+1) return a.value end -- Negates the value of a. Additionally returns the resulting value -- -- NOT 1 -> 0 -- NOT 0 -> 1 -- -- returns: num function _M.NOT(n) n = (isbf(n) and n) or _M:new(n) local r = (2^n.width - 1) - n.value n.value = r % bin(n.width+1) return n.value end -- ORs the value of a with b. Additionally returns the resulting value. -- -- 0 OR 0 -> 0 -- 0 OR 1 -> 1 -- 1 OR 0 -> 1 -- 1 OR 1 -> 1 -- -- Returns: num function _M.OR(a,b) a = (isbf(a) and a) or _M:new(a) b = (isbf(b) and b) or _M:new(b) local max = (2^a.width - 1) local r = max - _M.AND(max - a.value, max - b.value) a.value = r % bin(a.width+1) return a.value end -- ANDs the value of a with b. Additionally returns the resulting value. -- -- 0 AND 0 -> 0 -- 0 AND 1 -> 0 -- 1 AND 0 -> 0 -- 1 AND 1 -> 1 -- -- Returns: num function _M.AND(a,b) a = (isbf(a) and a) or _M:new(a) b = (isbf(b) and b) or _M:new(b) local r = ((a.value+b.value) - _M.XOR(a, b))/2 a.value = r % bin(a.width+1) return a.value end -- NANDs the value of a with b. Additionally returns the resulting value. -- -- 0 NAND 0 -> 1 -- 0 NAND 1 -> 1 -- 1 NAND 0 -> 1 -- 1 NAND 1 -> 0 -- -- Returns: num function _M.NAND(a,b) a = (isbf(a) and a) or _M:new(a) b = (isbf(b) and b) or _M:new(b) local r = _M.NOT(_M.AND(a, b)) a.value = r % bin(a.width+1) return a.value end -- NORs the value of a with b. Additionally returns the resulting value. -- -- 0 NOR 0 -> 1 -- 0 NOR 1 -> 0 -- 1 NOR 0 -> 0 -- 1 NOR 1 -> 0 -- -- Returns: num function _M.NOR(a,b) a = (isbf(a) and a) or _M:new(a) b = (isbf(b) and b) or _M:new(b) local r = _M.NOT(_M.OR(a, b)) a.value = r % bin(a.width+1) return a.value end -- XNORs the value of a with b. Additionally returns the resulting value. -- -- 0 XNOR 0 -> 1 -- 0 XNOR 1 -> 0 -- 1 XNOR 0 -> 0 -- 1 XNOR 1 -> 1 -- -- Return: num function _M.XNOR(a,b) a = (isbf(a) and a) or _M:new(a) b = (isbf(b) and b) or _M:new(b) local r = _M.NOT(_M.XOR(a, b)) a.value = r % bin(a.width+1) return a.value end -- Shifts the value of a by n. Additionally returns the resulting value. -- Positive values shift left, negative values shift right. if sign-ext -- is true, then the sign bit will be extended during a right-shift. -- -- Returns: num function _M.shift(a, n, sinex) a = (isbf(a) and a) or _M:new(a) if n == 0 then return a.value end local r = a.value if n > 0 then for i=1,n do r = r+r end else -- less than 0, shift right local flr = math.floor local s = a[a.width] for i=1,math.abs(n) do r = flr(r/2) end if sinex then a.value = r a[a.width] = s r = a.value end end a.value = math.floor(r % bin(a.width+1)) return a.value end -- Rolls the value of a by n. Additionally returns the resulting value. -- Positive values roll left, negative values roll right. -- A roll is similar to a shift, however values that fall of one end -- simply return to the other end. thus rolling 100b left one would be -- 001b. and again would be 010b -- (thanks to GeDaMo) -- Returns: num function _M.roll(a, n) a = (isbf(a) and a) or _M:new(a) if n == 0 then return a.value end if (a.value >= 2^a.width-1) then --print(a.value, a.value) else a.value = (a.value * 2^(n % a.width)) % (2^a.width-1) end -- a.value = math.floor(r % bin(a.width)+1) return a.value end ------------------------------------------------------------------------- -- MODULE TAIL -- in 5.1.x the custom is to set a global equal to the module name, in all others this ill-behaved. if _VERSION == "Lua 5.1" then _G[_M._NAME]=_M end return _M
--- -- @classmod StatsStorage local middleclass = require("middleclass") local flatdb = require("flatdb") local typeutils = require("typeutils") local Stats = require("models.stats") --- -- @table instance -- @tfield FlatDB _db -- @tfield number _current local StatsStorage = middleclass("StatsStorage") --- -- @function new -- @tparam string path -- @tparam number initial_minimal [0, ∞) -- @treturn StatsStorage function StatsStorage:initialize(path, initial_minimal) assert(type(path) == "string") assert(typeutils.is_positive_number(initial_minimal)) self._db = flatdb(path) if not self._db.stats then self._db.stats = { minimal = initial_minimal, } end self:reset() end --- -- @treturn Stats function StatsStorage:stats() return Stats:new(self._current, self._db.stats.minimal) end --- -- @function increment function StatsStorage:increment() self._current = self._current + 1 end --- -- @function reset function StatsStorage:reset() self._current = 0 end --- -- @function finish function StatsStorage:finish() if self._db.stats.minimal > self._current then self._db.stats.minimal = self._current self._db:save() end self:reset() end return StatsStorage