content stringlengths 5 1.05M |
|---|
slot0 = class("CollectionScene", import("..base.BaseUI"))
slot0.SHOW_DETAIL = "event show detail"
slot0.GET_AWARD = "event get award"
slot0.ACTIVITY_OP = "event activity op"
slot0.BEGIN_STAGE = "event begin state"
slot0.ON_INDEX = "event on index"
slot0.UPDATE_RED_POINT = "CollectionScene:UPDATE_RED_POINT"
slot0.ShipOrderAsc = false
slot0.ShipIndex = {
display = {
index = IndexConst.FlagRange2Bits(IndexConst.IndexAll, IndexConst.IndexOther),
camp = IndexConst.FlagRange2Bits(IndexConst.CampAll, IndexConst.CampOther),
rarity = IndexConst.FlagRange2Bits(IndexConst.RarityAll, IndexConst.Rarity5),
extra = IndexConst.FlagRange2Bits(IndexConst.ExtraAll, IndexConst.ExtraNotObtained)
},
index = IndexConst.Flags2Bits({
IndexConst.IndexAll
}),
camp = IndexConst.Flags2Bits({
IndexConst.CampAll
}),
rarity = IndexConst.Flags2Bits({
IndexConst.RarityAll
}),
extra = IndexConst.Flags2Bits({
IndexConst.ExtraAll
})
}
slot0.MANGA_INDEX = 4
slot0.GALLERY_INDEX = 5
slot0.MUSIC_INDEX = 6
slot0.getUIName = function (slot0)
return "CollectionUI"
end
slot0.setShipGroups = function (slot0, slot1)
slot0.shipGroups = slot1
end
slot0.setAwards = function (slot0, slot1)
slot0.awards = slot1
end
slot0.setCollectionRate = function (slot0, slot1, slot2, slot3)
slot0.rate = slot1
slot0.count = slot2
slot0.totalCount = slot3
end
slot0.setLinkCollectionCount = function (slot0, slot1)
slot0.linkCount = slot1
end
slot0.setPlayer = function (slot0, slot1)
slot0.player = slot1
end
slot0.setProposeList = function (slot0, slot1)
slot0.proposeList = slot1
end
slot0.init = function (slot0)
slot0:initEvents()
slot0.blurPanel = slot0:findTF("blur_panel")
slot0.top = slot0:findTF("blur_panel/adapt/top")
slot0.leftPanel = slot0:findTF("blur_panel/adapt/left_length")
slot0.UIMgr = pg.UIMgr.GetInstance()
slot0.backBtn = findTF(slot0.top, "back_btn")
slot0.contextData.toggle = slot0.contextData.toggle or 2
slot0.toggles = {
slot0:findTF("frame/tagRoot/card", slot0.leftPanel),
slot0:findTF("frame/tagRoot/display", slot0.leftPanel),
slot0:findTF("frame/tagRoot/trans", slot0.leftPanel),
slot0:findTF("frame/tagRoot/manga", slot0.leftPanel),
slot0:findTF("frame/tagRoot/gallery", slot0.leftPanel),
slot0:findTF("frame/tagRoot/music", slot0.leftPanel)
}
slot0.toggleUpdates = {
"initCardPanel",
"initDisplayPanel",
"initCardPanel",
"initMangaPanel",
"initGalleryPanel",
"initMusicPanel"
}
slot0.cardList = slot0:findTF("main/list_card/scroll"):GetComponent("LScrollRect")
slot0.cardList.onInitItem = function (slot0)
slot0:onInitCard(slot0)
end
slot0.cardList.onUpdateItem = function (slot0, slot1)
slot0:onUpdateCard(slot0, slot1)
end
slot0.cardList.onReturnItem = function (slot0, slot1)
slot0:onReturnCard(slot0, slot1)
end
slot0.cardItems = {}
slot0.cardContent = slot0.findTF(slot0, "ships", slot0.cardList)
slot0.contextData.cardToggle = slot0.contextData.cardToggle or 1
slot0.cardToggleGroup = slot0:findTF("main/list_card/types")
slot0.cardToggles = {
slot0:findTF("char", slot0.cardToggleGroup),
slot0:findTF("link", slot0.cardToggleGroup),
slot0:findTF("blueprint", slot0.cardToggleGroup),
slot0:findTF("meta", slot0.cardToggleGroup)
}
slot0.cardList.decelerationRate = 0.07
slot0.bonusPanel = slot0:findTF("bonus_panel")
slot0.charTpl = slot0:getTpl("chartpl")
slot0.tip = slot0:findTF("tip", slot0.toggles[2])
slot0.favoriteVOs = {}
for slot5, slot6 in ipairs(pg.storeup_data_template.all) do
table.insert(slot0.favoriteVOs, Favorite.New({
id = slot5
}))
end
slot0.memoryGroups = _.map(pg.memory_group.all, function (slot0)
return pg.memory_group[slot0]
end)
slot0.memories = nil
slot0.memoryList = slot0.findTF(slot0, "main/list_memory"):GetComponent("LScrollRect")
slot0.memoryList.onInitItem = function (slot0)
slot0:onInitMemory(slot0)
end
slot0.memoryList.onUpdateItem = function (slot0, slot1)
slot0:onUpdateMemory(slot0, slot1)
end
slot0.memoryList.onReturnItem = function (slot0, slot1)
slot0:onReturnMemory(slot0, slot1)
end
slot0.memoryViewport = slot0.findTF(slot0, "main/list_memory/viewport")
slot0.memoriesGrid = slot0:findTF("main/list_memory/viewport/memories"):GetComponent(typeof(GridLayoutGroup))
slot0.memoryItems = {}
slot0.memoryMask = slot0:findTF("blur_panel/adapt/story_mask")
setActive(slot2, false)
setActive(slot0.memoryMask, false)
slot0.memoryTogGroup = slot0:findTF("memory", slot0.top)
setActive(slot0.memoryTogGroup, false)
slot0.memoryToggles = {
slot0:findTF("memory/0", slot0.top),
slot0:findTF("memory/1", slot0.top),
slot0:findTF("memory/2", slot0.top),
slot0:findTF("memory/3", slot0.top)
}
slot0.memoryFilterIndex = {
true,
true,
true
}
slot0.galleryPanelContainer = slot0:findTF("main/GalleryContainer")
slot0.musicPanelContainer = slot0:findTF("main/MusicContainer")
slot0.mangaPanelContainer = slot0:findTF("main/MangaContainer")
end
slot0.didEnter = function (slot0)
onButton(slot0, slot0.backBtn, function ()
slot0.contextData.cardScrollValue = 0
slot0.contextData:emit(slot1.ON_BACK)
end, SFX_CANCEL)
slot0.helpBtn = slot0.findTF(slot0, "help_btn", slot0.leftPanel)
onButton(slot0, slot0.helpBtn, function ()
pg.MsgboxMgr.GetInstance():ShowMsgBox({
type = MSGBOX_TYPE_HELP,
helps = pg.gametip.collection_help.tip,
weight = LayerWeightConst.THIRD_LAYER
})
end, SFX_PANEL)
setActive(slot1, getProxy(TaskProxy):mingshiTouchFlagEnabled())
onButton(slot0, slot1, function ()
getProxy(TaskProxy):dealMingshiTouchFlag(8)
end, SFX_CONFIRM)
for slot5, slot6 in ipairs(slot0.toggles) do
if PLATFORM_CODE == PLATFORM_CH and (slot5 == 1 or slot5 == 3) and LOCK_COLLECTION then
setActive(slot6, false)
else
onToggle(slot0, slot6, function (slot0)
if slot0 then
if slot0.contextData.toggle ~= then
if slot0.contextData.toggle == 1 and slot0.contextData.cardToggle == 1 then
slot0.contextData.cardScrollValue = slot0.cardList.value
end
slot0.contextData.toggle = slot0.contextData
if slot0.toggleUpdates[] then
slot0[slot0.toggleUpdates[slot0]](slot0)
slot0:calFavoriteRate()
end
end
slot1(slot0.helpBtn, setActive == 1)
if slot1 == 1 and not getProxy(SettingsProxy):IsShowCollectionHelp() then
triggerButton(slot0.helpBtn)
slot1:SetCollectionHelpFlag(true)
end
if slot1 ~= slot2.MUSIC_INDEX then
if slot0.musicView and slot0.musicView:CheckState(BaseSubView.STATES.INITED) then
slot0.musicView:tryPauseMusic()
slot0.musicView:closeSongListPanel()
end
pg.CriMgr.GetInstance():ResumeLastNormalBGM()
elseif slot1 == slot2.MUSIC_INDEX and slot0.musicView and slot0.musicView:CheckState(BaseSubView.STATES.INITED) then
pg.CriMgr.GetInstance():StopBGM()
slot0.musicView:tryPlayMusic()
end
if slot1 ~= slot2.GALLERY_INDEX and slot0.galleryView and slot0.galleryView:CheckState(BaseSubView.STATES.INITED) then
slot0.galleryView:closePicPanel()
end
end
end, SFX_UI_TAG)
end
end
for slot5, slot6 in ipairs(slot0.memoryToggles) do
onToggle(slot0, slot6, function (slot0)
if slot0 then
if slot0 == 1 then
slot1.memoryFilterIndex = {
true,
true,
true
}
else
for slot4 in ipairs(slot1.memoryFilterIndex) do
slot1.memoryFilterIndex[slot4] = slot0 - 1 == slot4
end
end
slot1:memoryFilter()
end
end, SFX_UI_TAG)
end
slot0.contextData.toggle = -1
triggerToggle(slot0.toggles[slot0.contextData.toggle], true)
if slot0.contextData.memoryGroup and pg.memory_group[slot3] then
slot0.showSubMemories(slot0, pg.memory_group[slot3])
else
triggerToggle(slot0.memoryToggles[1], true)
end
for slot7, slot8 in ipairs(slot0.cardToggles) do
triggerToggle(slot8, slot0.contextData.cardToggle == slot7)
onToggle(slot0, slot8, function (slot0)
if slot0 and slot0.contextData.cardToggle ~= then
if slot0.contextData.cardToggle == 1 then
slot0.contextData.cardScrollValue = slot0.cardList.value
end
slot0.contextData.cardToggle = slot0.contextData
slot0:initCardPanel()
slot0:calFavoriteRate()
end
end)
end
slot0.initIndexPanel(slot0)
slot0:calFavoriteRate()
pg.UIMgr.GetInstance():OverlayPanelPB(slot0.blurPanel, {
groupName = LayerWeightConst.GROUP_COLLECTION
})
onButton(slot0, slot0.bonusPanel, function ()
slot0:closeBonus()
end, SFX_PANEL)
end
slot0.updateCollectNotices = function (slot0, slot1)
setActive(slot0.tip, slot1)
setActive(slot0:findTF("tip", slot0.toggles[slot0.GALLERY_INDEX]), getProxy(AppreciateProxy):isGalleryHaveNewRes())
setActive(slot0:findTF("tip", slot0.toggles[slot0.MUSIC_INDEX]), getProxy(AppreciateProxy):isMusicHaveNewRes())
setActive(slot0:findTF("tip", slot0.toggles[slot0.MANGA_INDEX]), getProxy(AppreciateProxy):isMangaHaveNewRes())
end
slot0.calFavoriteRate = function (slot0)
setActive(slot0:findTF("total/char", slot0.top), not (slot0.contextData.toggle == 1 and slot0.contextData.cardToggle == 2))
setActive(slot0:findTF("total/link", slot0.top), slot0.contextData.toggle == 1 and slot0.contextData.cardToggle == 2)
setText(slot0:findTF("total/char/rate/Text", slot0.top), slot0.rate * 100 .. "%")
setText(slot0:findTF("total/char/count/Text", slot0.top), slot0.count .. "/" .. slot0.totalCount)
setText(slot0:findTF("total/link/count/Text", slot0.top), slot0.linkCount)
end
slot0.initCardPanel = function (slot0)
if slot0.contextData.toggle == 1 then
setActive(slot0.cardToggleGroup, true)
slot0:cardFilter()
elseif slot0.contextData.toggle == 3 then
setActive(slot0.cardToggleGroup, false)
slot0:transFilter()
end
table.sort(slot0.codeShips, function (slot0, slot1)
return slot0.index_id < slot1.index_id
end)
slot0.cardList.SetTotalCount(slot1, #slot0.codeShips, slot0.contextData.cardScrollValue or 0)
end
slot0.initIndexPanel = function (slot0)
slot0.indexBtn = slot0:findTF("index_button", slot0.top)
onButton(slot0, slot0.indexBtn, function ()
slot0 = Clone(slot0.ShipIndex)
if slot0.ShipIndex.contextData.toggle == 1 and slot1.contextData.cardToggle == 2 then
slot0.display.camp = nil
slot0.camp = nil
end
slot0.callback = function (slot0)
for slot4, slot5 in pairs(slot0) do
slot0.ShipIndex[slot4] = slot5
end
slot1:initCardPanel()
end
function (slot0)
for slot4, slot5 in pairs(slot0) do
slot0.ShipIndex[slot4] = slot5
end
slot1.initCardPanel()
end.emit(slot1, slot0.ON_INDEX, slot0)
end, SFX_PANEL)
end
slot0.onInitCard = function (slot0, slot1)
if slot0.exited then
return
end
onButton(slot0, CollectionShipCard.New(slot1).go, function ()
if not slot0.isClicked then
slot0.isClicked = true
LeanTween.delayedCall(0.2, System.Action(function ()
slot0.isClicked = false
if not false:getIsInited() then
return
end
if slot1.state == ShipGroup.STATE_UNLOCK then
slot0.contextData.cardScrollValue = slot0.cardList.value
slot0.contextData:emit(slot2.SHOW_DETAIL, slot1.showTrans, slot1.shipGroup.id)
elseif slot1.state == ShipGroup.STATE_NOTGET then
if slot1.showTrans == true and slot1.shipGroup.trans == true then
return
end
if slot1.config then
slot0:showObtain(slot1.config.description, slot1.shipGroup:getShipConfigId())
end
end
end))
end
end, SOUND_BACK)
slot0.cardItems[slot1] = CollectionShipCard.New(slot1)
end
slot0.showObtain = function (slot0, slot1, slot2)
slot0.contextData.cardScrollValue = slot0.cardList.value
pg.MsgboxMgr.GetInstance():ShowMsgBox({
type = MSGBOX_TYPE_OBTAIN,
shipId = slot2,
list = slot1,
mediatorName = CollectionMediator.__cname
})
end
slot0.skipIn = function (slot0, slot1, slot2)
slot0.contextData.displayGroupId = slot2
triggerToggle(slot0.toggles[slot1], true)
end
slot0.onUpdateCard = function (slot0, slot1, slot2)
if slot0.exited then
return
end
if not slot0.cardItems[slot2] then
slot0:onInitCard(slot2)
slot3 = slot0.cardItems[slot2]
end
if not slot0.codeShips[slot1 + 1] then
return
end
slot6 = false
if slot5.group then
slot6 = slot0.proposeList[slot5.group.id]
end
slot3:update(slot5.code, slot5.group, slot5.showTrans, slot6, slot5.id)
end
slot0.onReturnCard = function (slot0, slot1, slot2)
if slot0.exited then
return
end
if slot0.cardItems[slot2] then
slot3:clear()
end
end
slot0.cardFilter = function (slot0)
slot0.codeShips = {}
table.sort(slot1)
for slot5, slot6 in ipairs(slot1) do
if IndexConst.filterByIndex(slot0.shipGroups[pg.ship_data_group[slot6].group_type] or ShipGroup.New({
id = slot7.group_type
}), slot0.ShipIndex.index) and (slot0.contextData.cardToggle == 2 or IndexConst.filterByCamp(slot8, slot0.ShipIndex.camp)) and slot0.contextData.cardToggle == 4 == Nation.IsMeta(ShipGroup.getDefaultShipConfig(slot7.group_type).nationality) and IndexConst.filterByRarity(slot8, slot0.ShipIndex.rarity) and IndexConst.filterByExtra(slot8, slot0.ShipIndex.extra) then
slot0.codeShips[#slot0.codeShips + 1] = {
showTrans = false,
id = slot6,
code = slot6 - (slot0.contextData.cardToggle - 1) * 10000,
group = slot0.shipGroups[slot7.group_type],
index_id = slot7.index_id
}
end
end
end
slot0.transFilter = function (slot0)
slot0.codeShips = {}
table.sort(slot1)
for slot5, slot6 in ipairs(slot1) do
if pg.ship_data_trans[pg.ship_data_group[slot6].group_type] and IndexConst.filterByIndex(slot0.shipGroups[slot7.group_type] or ShipGroup.New({
remoulded = true,
id = slot7.group_type
}), slot0.ShipIndex.index) and IndexConst.filterByCamp(slot8, slot0.ShipIndex.camp) and IndexConst.filterByRarity(slot8, slot0.ShipIndex.rarity) and IndexConst.filterByExtra(slot8, slot0.ShipIndex.extra) then
slot0.codeShips[#slot0.codeShips + 1] = {
showTrans = true,
id = slot6,
code = 3000 + slot6,
group = (slot8.trans and slot8) or nil,
index_id = slot7.index_id
}
end
end
end
slot0.sortDisplay = function (slot0)
table.sort(slot0.favoriteVOs, function (slot0, slot1)
if slot0:getState(slot0.shipGroups, slot0.awards) == slot1:getState(slot0.shipGroups, slot0.awards) then
return slot0.id < slot1.id
else
return slot2 < slot3
end
end)
slot1 = 0
slot2 = slot0.contextData.displayGroupId
for slot6, slot7 in ipairs(slot0.favoriteVOs) do
if slot7.containShipGroup(slot7, slot2) then
slot1 = slot6
break
end
end
slot0.displayRect:SetTotalCount(#slot0.favoriteVOs, slot0.displayRect:HeadIndexToValue(slot1 - 1))
end
slot0.initDisplayPanel = function (slot0)
if not slot0.isInitDisplay then
slot0.isInitDisplay = true
slot0.displayRect = slot0:findTF("main/list_display"):GetComponent("LScrollRect")
slot0.displayRect.decelerationRate = 0.07
slot0.displayRect.onInitItem = function (slot0)
slot0:initFavoriteCard(slot0)
end
slot0.displayRect.onUpdateItem = function (slot0, slot1)
slot0:updateFavoriteCard(slot0, slot1)
end
slot0.favoriteCards = {}
end
slot0.sortDisplay(slot0)
end
slot0.initFavoriteCard = function (slot0, slot1)
if slot0.exited then
return
end
slot2 = FavoriteCard.New(slot1, slot0.charTpl)
onButton(slot0, slot2.awardTF, function ()
if slot0.state == Favorite.STATE_AWARD then
slot1:emit(slot2.GET_AWARD, slot0.favoriteVO.id, slot0.favoriteVO:getNextAwardIndex(slot0.awards))
elseif slot0.state == Favorite.STATE_LOCK then
pg.TipsMgr.GetInstance():ShowTips(i18n("collection_lock"))
elseif slot0.state == Favorite.STATE_FETCHED then
pg.TipsMgr.GetInstance():ShowTips(i18n("collection_fetched"))
elseif slot0.state == Favorite.STATE_STATE_WAIT then
pg.TipsMgr.GetInstance():ShowTips(i18n("collection_nostar"))
end
end, SFX_PANEL)
onButton(slot0, slot2.box, function ()
slot0:openBonus(slot1.favoriteVO)
end, SFX_PANEL)
slot0.favoriteCards[slot1] = slot2
end
slot0.updateFavoriteCard = function (slot0, slot1, slot2)
if slot0.exited then
return
end
if not slot0.favoriteCards[slot2] then
slot0:initFavoriteCard(slot2)
slot3 = slot0.favoriteCards[slot2]
end
slot3:update(slot0.favoriteVOs[slot1 + 1], slot0.shipGroups, slot0.awards)
end
slot0.openBonus = function (slot0, slot1)
if not slot0.isInitBound then
slot0.isInitBound = true
slot0.boundName = findTF(slot0.bonusPanel, "frame/name/Text"):GetComponent(typeof(Text))
slot0.progressSlider = findTF(slot0.bonusPanel, "frame/process"):GetComponent(typeof(Slider))
end
pg.UIMgr.GetInstance():BlurPanel(slot0.bonusPanel)
setActive(slot0.bonusPanel, true)
slot0.boundName.text = slot1:getConfig("name")
slot2 = slot1:getConfig("award_display")
for slot7, slot8 in ipairs(slot3) do
slot9 = slot2[slot7]
setText(findTF(slot10, "process"), slot8)
setActive(findTF(slot10, "item_tpl/unfinish"), slot1:getAwardState(slot0.shipGroups, slot0.awards, slot7) == Favorite.STATE_WAIT)
setActive(findTF(slot10, "item_tpl/get"), slot11 == Favorite.STATE_AWARD)
setActive(findTF(slot10, "item_tpl/got"), slot11 == Favorite.STATE_FETCHED)
setActive(findTF(slot10, "item_tpl/lock"), slot11 == Favorite.STATE_LOCK)
setActive(findTF(slot10, "item_tpl/icon_bg"), slot11 ~= Favorite.STATE_LOCK)
setActive(findTF(slot10, "item_tpl/bg"), slot11 ~= Favorite.STATE_LOCK)
if slot9 then
updateDrop(findTF(slot10, "item_tpl"), {
count = 0,
type = slot9[1],
id = slot9[2]
})
onButton(slot0, slot10, function ()
if slot0[1] == DROP_TYPE_RESOURCE then
slot1:emit(slot2.ON_ITEM, id2ItemId(slot0[2]))
elseif slot0[1] == DROP_TYPE_ITEM then
slot1:emit(slot2.ON_DROP, {
type = slot0[1],
id = slot0[2],
count = slot0[3]
})
elseif slot0[1] == DROP_TYPE_SHIP then
pg.MsgboxMgr.GetInstance():ShowMsgBox({
hideNo = true,
type = MSGBOX_TYPE_SINGLE_ITEM,
drop = {
type = slot0[1],
id = slot0[2],
count = slot0[3]
}
})
elseif slot0[1] == DROP_TYPE_FURNITURE then
pg.MsgboxMgr.GetInstance():ShowMsgBox({
hideNo = true,
content = "",
yesText = "text_confirm",
type = MSGBOX_TYPE_SINGLE_ITEM,
drop = {
type = DROP_TYPE_FURNITURE,
id = slot0[2],
cfg = pg.furniture_data_template[slot0[2]]
}
})
elseif slot0[1] == DROP_TYPE_EQUIP then
slot1:emit(slot2.ON_EQUIPMENT, {
equipmentId = slot0[2],
type = EquipmentInfoMediator.TYPE_DISPLAY
})
end
end, SFX_PANEL)
else
GetOrAddComponent(slot10, typeof(Button)).onClick:RemoveAllListeners()
end
end
slot0.progressSlider.value = slot1:getStarCount(slot0.shipGroups) / slot3[#slot3]
end
slot0.closeBonus = function (slot0)
pg.UIMgr.GetInstance():UnblurPanel(slot0.bonusPanel, slot0._tf)
setActive(slot0.bonusPanel, false)
end
slot0.showSubMemories = function (slot0, slot1)
slot0.contextData.memoryGroup = slot1.id
slot0.memories = _.map(slot1.memories, function (slot0)
return pg.memory_template[slot0]
end)
for slot5 in ipairs(slot0.memories) do
slot0.memories[slot5].index = slot5
end
slot0.memoryList.SetTotalCount(slot2, #slot0.memories, 0)
setActive(slot0:findTF("memory", slot0.top), false)
end
slot1 = 3
slot0.return2MemoryGroup = function (slot0)
slot0.contextData.memoryGroup = nil
slot0.memories = nil
slot2 = 0
if slot0.contextData.memoryGroup then
slot3 = 0
for slot7, slot8 in ipairs(slot0.memoryGroups) do
if slot8.id == slot1 then
slot3 = slot7
break
end
end
if slot3 >= 0 then
slot2 = Mathf.Clamp01(((slot0.memoriesGrid.cellSize.y + slot0.memoriesGrid.spacing.y) * math.floor((slot3 - 1) / slot0) + slot0.memoryList.paddingFront) / ((slot0.memoriesGrid.cellSize.y + slot0.memoriesGrid.spacing.y) * math.ceil(#slot0.memoryGroups / slot0) - slot0.memoryViewport.rect.height))
end
end
slot0.memoryList:SetTotalCount(#slot0.memoryGroups, slot2)
setActive(slot0:findTF("memory", slot0.top), true)
end
slot0.initMemoryPanel = function (slot0)
if getProxy(ActivityProxy):getActivityById(ActivityConst.QIXI_ACTIVITY_ID) and not slot2:isEnd() and getProxy(TaskProxy):getTaskById(_.flatten(slot3)[#_.flatten(slot3)]) and not slot7:isFinish() then
pg.NewStoryMgr.GetInstance():Play("HOSHO8", function ()
slot0:emit(CollectionScene.ACTIVITY_OP, {
cmd = 2,
activity_id = slot1.id
})
end, true)
end
slot0.memoryFilter(slot0)
end
slot0.onInitMemory = function (slot0, slot1)
if slot0.exited then
return
end
onButton(slot0, MemoryCard.New(slot1).go, function ()
if slot0.info then
if slot0.isGroup then
slot1:showSubMemories(slot0.info)
elseif slot0.info.is_open == 1 or pg.NewStoryMgr.GetInstance():IsPlayed(slot0.info.story, true) then
slot1:playMemory(slot0.info)
end
end
end, SOUND_BACK)
slot0.memoryItems[slot1] = MemoryCard.New(slot1)
end
slot0.onUpdateMemory = function (slot0, slot1, slot2)
if slot0.exited then
return
end
if not slot0.memoryItems[slot2] then
slot0:onInitMemory(slot2)
slot3 = slot0.memoryItems[slot2]
end
if slot0.memories then
slot3:update(false, slot0.memories[slot1 + 1])
else
slot3:update(true, slot0.memoryGroups[slot1 + 1])
end
_.any({
slot3.lock,
slot3.normal,
slot3.group
}, function (slot0)
if isActive(slot0) then
slot0.go:GetComponent(typeof(Button)).targetGraphic = slot0:GetComponent(typeof(Image))
end
return slot1
end)
end
slot0.onReturnMemory = function (slot0, slot1, slot2)
if slot0.exited then
return
end
if slot0.memoryItems[slot2] then
slot3:clear()
end
end
slot0.playMemory = function (slot0, slot1)
if slot1.type == 1 then
slot2 = findTF(slot0.memoryMask, "pic")
if string.len(slot1.mask) > 0 then
setActive(slot2, true)
slot2:GetComponent(typeof(Image)).sprite = LoadSprite(slot1.mask)
else
setActive(slot2, false)
end
setActive(slot0.memoryMask, true)
pg.NewStoryMgr.GetInstance():Play(slot1.story, function ()
setActive(slot0.memoryMask, false)
end, true)
elseif slot1.type == 2 then
slot0:emit(slot0.BEGIN_STAGE, {
memory = true,
system = SYSTEM_PERFORM,
stageId = pg.NewStoryMgr.GetInstance().StoryName2StoryId(slot2, slot1.story)
})
end
end
slot0.memoryFilter = function (slot0)
slot0.memoryGroups = {}
for slot4, slot5 in pairs(pg.memory_group) do
if slot0.memoryFilterIndex[slot5.type] then
table.insert(slot0.memoryGroups, slot5)
end
end
table.sort(slot0.memoryGroups, function (slot0, slot1)
return slot0.id < slot1.id
end)
slot0.memoryList.SetTotalCount(slot1, #slot0.memoryGroups, 0)
end
slot0.willExit = function (slot0)
if slot0.tweens then
cancelTweens(slot0.tweens)
end
pg.UIMgr.GetInstance():UnOverlayPanel(slot0.blurPanel, slot0._tf)
if slot0.bonusPanel.gameObject.activeSelf then
slot0:closeBonus()
end
Destroy(slot0.bonusPanel)
slot0.bonusPanel = nil
for slot4, slot5 in pairs(slot0.cardItems) do
slot5:clear()
end
if slot0.resPanel then
slot0.resPanel:exit()
slot0.resPanel = nil
end
if slot0.galleryView then
slot0.galleryView:Destroy()
slot0.galleryView = nil
end
if slot0.musicView then
slot0.musicView:Destroy()
slot0.musicView = nil
end
if slot0.mangaView then
slot0.mangaView:Destroy()
slot0.mangaView = nil
end
end
slot0.initGalleryPanel = function (slot0)
if not slot0.galleryView then
slot0.galleryView = GalleryView.New(slot0.galleryPanelContainer, slot0.event, slot0.contextData)
slot0.galleryView:Reset()
slot0.galleryView:Load()
end
end
slot0.initMusicPanel = function (slot0)
if not slot0.musicView then
slot0.musicView = MusicCollectionView.New(slot0.musicPanelContainer, slot0.event, slot0.contextData)
slot0.musicView:Reset()
slot0.musicView:Load()
pg.CriMgr.GetInstance():StopBGM()
end
end
slot0.initMangaPanel = function (slot0)
if not slot0.mangaView then
slot0.mangaView = MangaView.New(slot0.mangaPanelContainer, slot0.event, slot0.contextData)
slot0.mangaView:Reset()
slot0.mangaView:Load()
end
end
slot0.initEvents = function (slot0)
slot0:bind(GalleryConst.OPEN_FULL_SCREEN_PIC_VIEW, function (slot0, slot1)
slot0:emit(CollectionMediator.EVENT_OPEN_FULL_SCREEN_PIC_VIEW, slot1)
end)
slot0.bind(slot0, slot0.UPDATE_RED_POINT, function ()
slot0:updateCollectNotices()
end)
end
slot0.onBackPressed = function (slot0)
pg.CriMgr.GetInstance():PlaySoundEffect_V3(SFX_CANCEL)
if slot0.bonusPanel.gameObject.activeSelf then
slot0:closeBonus()
return
end
if slot0.galleryView then
if slot0.galleryView:onBackPressed() == true then
slot0.galleryView:Destroy()
slot0.galleryView = nil
else
return
end
end
if slot0.musicView then
if slot0.musicView:onBackPressed() == true then
slot0.musicView:Destroy()
slot0.musicView = nil
else
return
end
end
if slot0.mangaView then
if slot0.mangaView:onBackPressed() == true then
slot0.mangaView:Destroy()
slot0.mangaView = nil
else
return
end
end
triggerButton(slot0.backBtn)
end
return slot0
|
require("colorbuddy").setup()
local Color = require('colorbuddy').Color
Color.new('white', '#ffffff')
Color.new('red', '#8afef7')
Color.new('pink', '#ed2b8f')
Color.new('green', '#ff9e64')
Color.new('yellow', '#88ff99')
Color.new('blue', '#91ede2')
Color.new('aqua', '#ff2020')
Color.new('cyan', '#2fedab')
Color.new('purple', '#2bb0ed')
Color.new('violet', '#ff6666')
Color.new('orange', '#de935f')
Color.new('brown', '#a3785a')
Color.new('seagreen', '#89ab89')
Color.new('turquoise', '#598b59')
|
fx_version "cerulean"
game "gta5"
name "GGCommon"
description "Gamemode independant features for the Gun Game server"
author "Remco Troost (d0p3t)"
url "https://github.com/d0p3t/ggcommon"
dependency "screenshot-basic"
client_scripts {
"client/*.lua"
}
server_scripts {
"server/*.lua"
}
files {
"client/lib/Newtonsoft.Json.dll",
"client/lib/index.html",
"client/lib/audio/**/*.ogg",
"client/lib/*.min.css",
"client/lib/*.css",
"client/lib/*.min.js"
}
ui_page "client/lib/index.html"
server_export "PrintLog"
server_export "Log"
server_export "Screenshot"
server_export "SentryIssue"
|
includeFile("custom_content/tangible/wearables/wookiee/wke_shirt_s05.lua")
|
--ZFUNC-numseq-v1
local function numseq( n, init, f ) --> seq
init = init or 0
f = f or function ( v )
return v + 1
end
local result = {}
table.insert( result, init )
for i = 2,n do
table.insert( result, f( result[ i - 1 ] ) )
end
return result
end
return numseq
|
function start_tween (animatable, animation)
animatable.animating = true
animatable[animation] = game.animations[animation]
end
|
--[[
--MIT License
--
--Copyright (c) 2019 manilarome
--Copyright (c) 2020 Tom Meyers
--
--Permission is hereby granted, free of charge, to any person obtaining a copy
--of this software and associated documentation files (the "Software"), to deal
--in the Software without restriction, including without limitation the rights
--to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
--copies of the Software, and to permit persons to whom the Software is
--furnished to do so, subject to the following conditions:
--
--The above copyright notice and this permission notice shall be included in all
--copies or substantial portions of the Software.
--
--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
--IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
--FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
--AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
--LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
--OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
--SOFTWARE.
]]
local mouse = require("tde.lib-tde.mouse")
function test_mouse_api_exists()
assert(mouse.getInputDevices, "The getInputDevices function doesn't exist")
assert(mouse.setAcceleration, "The setAccellaration function doesn't exist")
assert(mouse.setMouseSpeed, "The setMouseSpeed function doesn't exist")
assert(mouse.setNaturalScrolling, "The setNaturalScrolling function doesn't exist")
end
function test_mouse_input_device_return_correct()
local result = mouse.getInputDevices()
assert(type(result) == "table", "The list of input devices should be a table")
-- only run this when a mouse was found
if #result > 0 then
assert(type(result[1].name) == "string", "The input device list should have a name attribute")
assert(type(result[1].id) == "number", "The input device list should have a id attribute")
end
end
function test_mouse_api_unit_tested()
local amount = 4
local result = tablelength(mouse)
assert(
result == amount,
"You didn't test all mouse api endpoints, please add them then update the amount to: " .. result
)
end
|
Utils = {}
local screenWidth, screenHeight = guiGetScreenSize()
function Utils.screenScale(val)
if screenWidth < 1280 then
return val * screenWidth / 1280
end
return val
end
function Utils.wrapAngle(value)
if not value then
return 0
end
value = math.mod(value, 360)
if value < 0 then
value = value + 360
end
return value
end
function Utils.calculateRPM(vehicle)
local vx, vy, vz = getElementVelocity(vehicle)
local speed = (vx^2 + vy^2 + vz^2)^0.5 * 161
if speed < 40 then
return speed * 162
elseif speed < 80 then
return (speed - 30) * 132
elseif speed < 120 then
return (speed - 65) * 118
elseif speed < 160 then
return (speed - 110) * 125
elseif speed < 200 then
return (speed - 130) * 92
elseif speed >= 200 then
if speed > 250 then
return 6000
else
return (speed - 130) * 50
end
end
end |
require "/scripts/util.lua"
function init()
self.detectArea = config.getParameter("detectArea")
self.detectArea[1] = object.toAbsolutePosition(self.detectArea[1])
self.detectArea[2] = object.toAbsolutePosition(self.detectArea[2])
animator.setAnimationState("portal", "off")
object.setLightColor({0, 0, 0, 0})
storage.uuid = storage.uuid or sb.makeUuid()
object.setInteractive(true)
message.setHandler("onTeleport", function(message, isLocal, data)
if not config.getParameter("returnDoor") and not storage.vanishTime then
storage.vanishTime = world.time() + config.getParameter("vanishTime")
if not (animator.animationState("portal") == "open" or animator.animationState("portal") == "on") then
animator.setAnimationState("portal", "open")
end
end
end)
if config.getParameter("messagePlayerInterval") then
self.radioMessage = util.interval(config.getParameter("messagePlayerInterval"), function()
local nearPlayers = world.entityQuery(object.position(), config.getParameter("messagePlayerRange"), {includedTypes = {"player"}})
nearPlayers = util.filter(nearPlayers, entity.entityInSight)
for _,playerId in pairs(nearPlayers) do
world.sendEntityMessage(playerId, "queueRadioMessage", "challengedoor")
end
end)
end
end
function update(dt)
if self.radioMessage ~= nil then
self.radioMessage(dt)
end
if animator.animationState("portal") == "gone" then
object.smash()
return
elseif storage.vanishTime and world.time() > storage.vanishTime then
animator.setAnimationState("portal", "vanish")
end
local players = world.entityQuery(self.detectArea[1], self.detectArea[2], {
includedTypes = {"player"},
boundMode = "CollisionArea"
})
if #players > 0 and animator.animationState("portal") == "off" then
animator.setAnimationState("portal", "open")
animator.playSound("on");
object.setLightColor(config.getParameter("lightColor", {255, 255, 255}))
elseif #players == 0 and animator.animationState("portal") == "on" and not storage.vanishTime then
animator.setAnimationState("portal", "close")
animator.playSound("off");
object.setLightColor({0, 0, 0, 0})
end
end
function onInteraction(args)
if config.getParameter("returnDoor") then
return { "OpenTeleportDialog", {
canBookmark = false,
includePlayerBookmarks = false,
destinations = { {
name = "Exit Portal",
planetName = "Return to World... Hopefully!",
icon = "return",
warpAction = "Return"
} }
}
}
else
return { "OpenTeleportDialog", {
canBookmark = false,
includePlayerBookmarks = false,
destinations = { {
name = "Challenge Portal",
planetName = "Unstable Pocket Dimension",
icon = "default",
warpAction = string.format("InstanceWorld:challengerooms:%s:%s", storage.uuid, world.threatLevel())
} }
}
}
end
end
|
local t = My.Translator.translate
local mission
My.EventHandler:register("onAttackersDetection", function()
mission = Mission:new({})
Mission:withBroker(mission, t("story_mission_plan_defense", My.Commander:getPerson(), My.World.fortress:getCallSign()))
Mission:forPlayer(mission)
mission:setHint(t("story_mission_plan_defense_hint", My.World.fortress:getSectorName()))
mission:setPlayer(My.World.player)
mission:setMissionBroker(My.World.fortress)
mission:accept()
mission:start()
My.World.player:addMission(mission)
end)
My.EventHandler:register("onFortressManned", function()
if mission ~= nil then
mission:setHint(t("story_mission_plan_defense_hint2", My.Commander:getPerson(), My.World.fortress:getSectorName()))
end
end)
My.EventHandler:register("onDefensePlanned", function()
if mission ~= nil and mission:getState() == "started" then
mission:success()
end
end)
My.EventHandler:register("onCommanderDead", function()
if mission ~= nil and mission:getState() == "started" then
mission:fail()
end
end)
|
--
-- Back ground parallax class.
--
-- @filename LgBackgroundParallax.lua
-- @copyright Copyright (c) 2015 Yaukey/yaukeywang/WangYaoqi (yaukeywang@gmail.com) all rights reserved.
-- @license The MIT License (MIT)
-- @author Yaukey
-- @date 2015-09-02
--
local DLog = YwDebug.Log
local DLogWarn = YwDebug.LogWarning
local DLogError = YwDebug.LogError
local Vector3 = Vector3
local Time = Time
-- Register new class LgBackgroundParallax.
local strClassName = "LgBackgroundParallax"
local LgBackgroundParallax = YwDeclare(strClassName, YwClass(strClassName, YwMonoBehaviour))
-- Member variables.
-- The background transforms.
LgBackgroundParallax.m_aBackgrounds = false
-- The parallax scale.
LgBackgroundParallax.m_fParallaxScale = 0.5
-- The parallax reduction factor.
LgBackgroundParallax.m_fParallaxReductionFactor = 0.4
-- The smoothing.
LgBackgroundParallax.m_fSmoothing = 8.0
-- The current camera transform.
LgBackgroundParallax.m_cCam = false
-- The previous camera pos.
LgBackgroundParallax.m_vPreviousCamPos = false
-- Constructor.
function LgBackgroundParallax:ctor()
--print("LgBackgroundParallax:ctor")
self.m_aBackgrounds = {}
self.m_vPreviousCamPos = Vector3.zero
end
-- Destructor.
function LgBackgroundParallax:dtor()
--print("LgBackgroundParallax:dtor")
self.m_aBackgrounds = nil
end
-- Awake method.
function LgBackgroundParallax:Awake()
--print("LgBackgroundParallax:Awake")
-- Check variable.
if (not self.this) or (not self.transform) or (not self.gameObject) then
DLogError("Init error in LgBackgroundParallax!")
return
end
-- Get camera.
self.m_cCam = Camera.main.transform
-- Init background transform
for i = 1, #self.m_aParameters do
self.m_aBackgrounds[i] = self.m_aParameters[i].transform
end
end
-- Start method.
function LgBackgroundParallax:Start()
--print("LgBackgroundParallax:Start")
-- The 'previous frame' had the current frame's camera position.
self.m_vPreviousCamPos = self.m_cCam.position
end
-- Update method.
function LgBackgroundParallax:Update()
--print("LgBackgroundParallax:Update")
-- The parallax is the opposite of the camera movement since the previous frame multiplied by the scale.
local fParallax = (self.m_vPreviousCamPos.x - self.m_cCam.position.x) * self.m_fParallaxScale
-- For each successive background...
local aBackgrounds = self.m_aBackgrounds
for i = 1, #aBackgrounds do
-- ... set a target x position which is their current position plus the parallax multiplied by the reduction.
local fBackgroundTargetPosX = aBackgrounds[i].position.x + fParallax * (i * self.m_fParallaxReductionFactor + 1.0)
-- Create a target position which is the background's current position but with it's target x position.
local vBackgroundTargetPos = Vector3(fBackgroundTargetPosX, aBackgrounds[i].position.y, aBackgrounds[i].position.z)
-- Lerp the background's position between itself and it's target position.
aBackgrounds[i].position = Vector3.Lerp(aBackgrounds[i].position, vBackgroundTargetPos, self.m_fSmoothing * Time.deltaTime)
end
-- Set the previousCamPos to the camera's position at the end of this frame.
self.m_vPreviousCamPos = self.m_cCam.position
end
-- Return this class.
return LgBackgroundParallax
|
local K = unpack(KkthnxUI)
local Module = K:GetModule("AurasTable")
if K.Class ~= "PRIEST" then
return
end
local list = {
["Player Aura"] = { -- 玩家光环组
{ AuraID = 586, UnitID = "player" }, -- 渐隐术
{ AuraID = 45242, UnitID = "player" }, -- 专注意志
{ AuraID = 121557, UnitID = "player" }, -- 天堂之羽
{ AuraID = 194022, UnitID = "player" }, -- 意志坚定
{ AuraID = 214121, UnitID = "player" }, -- 身心合一
},
["Target Aura"] = { -- 目标光环组
{ AuraID = 139, UnitID = "target", Caster = "player" }, -- 恢复
{ AuraID = 589, UnitID = "target", Caster = "player" }, -- 暗言术:痛
{ AuraID = 8122, UnitID = "target", Caster = "player" }, -- 心灵尖啸
{ AuraID = 15487, UnitID = "target", Caster = "player" }, -- 沉默
{ AuraID = 34914, UnitID = "target", Caster = "player" }, -- 吸血鬼之触
{ AuraID = 41635, UnitID = "target", Caster = "player" }, -- 愈合祷言
{ AuraID = 205369, UnitID = "target", Caster = "player" }, -- 心灵炸弹
{ AuraID = 217673, UnitID = "target", Caster = "player" }, -- 心灵尖刺
{ AuraID = 208065, UnitID = "target", Caster = "player" }, -- 图雷之光
{ AuraID = 200196, UnitID = "target", Caster = "player" }, -- 圣言术:罚
{ AuraID = 200200, UnitID = "target", Caster = "player" }, -- 圣言术:罚
{ AuraID = 214121, UnitID = "target", Caster = "player" }, -- 身心合一
{ AuraID = 121557, UnitID = "target", Caster = "player" }, -- 天堂之羽
{ AuraID = 204263, UnitID = "target", Caster = "player" }, -- 闪光力场
{ AuraID = 194384, UnitID = "target", Caster = "player" }, -- 救赎
{ AuraID = 214621, UnitID = "target", Caster = "player" }, -- 教派分歧
{ AuraID = 152118, UnitID = "target", Caster = "player" }, -- 意志洞悉
{ AuraID = 204213, UnitID = "target", Caster = "player" }, -- 净化邪恶
{ AuraID = 335467, UnitID = "target", Caster = "player" }, -- 噬灵疫病
{ AuraID = 323673, UnitID = "target", Caster = "player" }, -- 控心术
{ AuraID = 342132, UnitID = "target", Caster = "player" }, -- 盛怒法夜
{ AuraID = 325203, UnitID = "target", Caster = "player" }, -- 邪恶灌注
{ AuraID = 17, UnitID = "target", Caster = "player", Value = true }, -- 真言术:盾
{ AuraID = 208772, UnitID = "target", Caster = "player", Value = true }, -- 惩击
{ AuraID = 271466, UnitID = "target", Caster = "player", Value = true }, -- 微光屏障
},
["Special Aura"] = { -- 玩家重要光环组
{ AuraID = 17, UnitID = "player", Caster = "player" }, -- 真言术:盾
{ AuraID = 194384, UnitID = "player", Caster = "player" }, -- 救赎
{ AuraID = 27827, UnitID = "player" }, -- 救赎之魂
{ AuraID = 47536, UnitID = "player" }, -- 全神贯注
{ AuraID = 65081, UnitID = "player" }, -- 身心合一
{ AuraID = 47585, UnitID = "player" }, -- 消散
{ AuraID = 15286, UnitID = "player" }, -- 吸血鬼的拥抱
{ AuraID = 197937, UnitID = "player" }, -- 延宕狂乱
{ AuraID = 194249, UnitID = "player" }, -- 虚空形态
{ AuraID = 205372, UnitID = "player" }, -- 虚空射线
{ AuraID = 193223, UnitID = "player" }, -- 疯入膏肓
{ AuraID = 196490, UnitID = "player" }, -- 纳鲁之能
{ AuraID = 114255, UnitID = "player" }, -- 圣光涌动
{ AuraID = 196644, UnitID = "player" }, -- 图雷的祝福
{ AuraID = 197030, UnitID = "player" }, -- 圣洁
{ AuraID = 200183, UnitID = "player" }, -- 神圣化身
{ AuraID = 197763, UnitID = "player" }, -- 争分夺秒
{ AuraID = 198069, UnitID = "player" }, -- 阴暗面之力
{ AuraID = 123254, UnitID = "player" }, -- 命运多舛
{ AuraID = 211440, UnitID = "player" }, -- 神牧神器
{ AuraID = 211442, UnitID = "player" }, -- 神牧神器
{ AuraID = 252848, UnitID = "player" }, -- T21戒律
{ AuraID = 253437, UnitID = "player" }, -- T21神圣2
{ AuraID = 253443, UnitID = "player" }, -- T21神圣4
{ AuraID = 216135, UnitID = "player" }, -- 戒律法袍
{ AuraID = 271466, UnitID = "player" }, -- 微光屏障
{ AuraID = 124430, UnitID = "player" }, -- 暗影洞察
{ AuraID = 197871, UnitID = "player" }, -- 黑暗天使长
},
["Focus Aura"] = { -- 焦点光环组
{ AuraID = 139, UnitID = "focus", Caster = "player" }, -- 恢复
},
["Spell Cooldown"] = { -- 冷却计时组
{ SlotID = 13 }, -- 饰品1
{ SlotID = 14 }, -- 饰品2
{ SpellID = 64843 }, -- 神圣赞美诗
{ SpellID = 33206 }, -- 痛苦压制
},
}
Module:AddNewAuraWatch("PRIEST", list)
|
-- Copyright (C) 2012 Nicholas Carlson
--
-- Permission is hereby granted, free of charge, to any person obtaining a
-- copy of this software and associated documentation files (the "Software"),
-- to deal in the Software without restriction, including without limitation
-- the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Software, and to permit persons to whom the
-- Software is furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
local ffi = require 'ffi'
local gl = eiga.alias.gl()
local glfw = eiga.alias.glfw()
local soil = eiga.ffi.soil
local physfs = eiga.alias.physfs()
local Matrix4 = require 'math.mat4'
local Vector3 = require 'math.vec3'
local i = 0.25
local data = {
position = { i, -i, -i, 1, --back
-i, -i, -i, 1,
i, i, -i, 1,
-i, i, -i, 1,
-i, -i, i, 1, --front
i, -i, i, 1,
-i, i, i, 1,
i, i, i, 1,
-i, -i, -i, 1, --left
-i, -i, i, 1,
-i, i, -i, 1,
-i, i, i, 1,
i, -i, i, 1, --right
i, -i, -i, 1,
i, i, i, 1,
i, i, -i, 1,
-i, -i, -i, 1, --bottom
i, -i, -i, 1,
-i, -i, i, 1,
i, -i, i, 1,
-i, i, i, 1, --top
i, i, i, 1,
-i, i, -i, 1,
i, i, -i, 1 };
texcoord = { 0, 1, 1, 1, 0, 0, 1, 0,
0, 1, 1, 1, 0, 0, 1, 0,
0, 1, 1, 1, 0, 0, 1, 0,
0, 1, 1, 1, 0, 0, 1, 0,
0, 1, 1, 1, 0, 0, 1, 0,
0, 1, 1, 1, 0, 0, 1, 0 };
index = { 0, 1, 3, 0, 3, 2,
4, 5, 7, 4, 7, 6,
8, 9, 11, 8, 11, 10,
12, 13, 15, 12, 15, 14,
16, 17, 19, 16, 19, 18,
20, 21, 23, 20, 23, 22 };
}
local mesh = eiga.graphics.newMesh( "IndexPositionTexCoord" )
local effect = eiga.graphics.newEffect( "assets/effect.vert",
"assets/effect.frag" );
local m = Matrix4.scale( 2.0, 2.0, 2.0 )
local v = Matrix4.lookat( Vector3( 0, 0, -3 ),
Vector3( 0, 0, 0 ),
Vector3( 0, 1, 0 ) )
local p = Matrix4.perspectiveFov( 55, 16/9, 0.1, 100 )
function eiga.load ( args )
gl.Enable( gl.CULL_FACE )
gl.Enable( gl.TEXTURE_2D )
gl.Enable( gl.BLEND )
gl.BlendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA )
gl.Enable( gl.DEPTH_TEST )
gl.DepthFunc( gl.LESS )
gl.ActiveTexture( gl.TEXTURE0 )
stone_texture = eiga.graphics.newTexture( "assets/stone.png", gl.NEAREST, gl.NEAREST )
gl.BindTexture( gl.TEXTURE_2D, stone_texture )
for i=#data.position+1, 1024 do data.position[i] = 0 end
mesh.buffers.position:setData( data.position )
for i=#data.texcoord+1, 1024 do data.texcoord[i] = 0 end
mesh.buffers.texcoord:setData( data.texcoord )
mesh.buffers.index:setData( data.index )
mesh:compile( effect )
effect:sendTexture( 0, "tex0")
effect:sendMatrix4( m, "Model" )
effect:sendMatrix4( v, "View" )
effect:sendMatrix4( p, "Projection" )
end
function eiga.update ( dt )
effect:sendMatrix4( Matrix4.rotate( eiga.timer.get_time(), 0.3, 1, 0 ) * m , "Model" )
end
function eiga.draw ()
mesh:draw( #data.index, effect )
end
function eiga.keypressed ( key )
if key == glfw.KEY_ESC then
eiga.event.push("quit")
end
end
function eiga.resized ( width, height )
gl.Viewport( 0, 0, width, height )
end
|
local DataDependentModule, parent = torch.class('nn.DataDependentModule', 'nn.Module')
function DataDependentModule:__init(DDM_learning_rate)
parent.__init(self)
self.gradInput = {}
self.DDM_learning_rate = DDM_learning_rate or 0
end
function DataDependentModule:updateOutput(input)
self.output = input[1]
return self.output
end
function DataDependentModule:updateGradInput(input, gradOutput)
self.gradInput[1] = gradOutput:clone()
DDM_vec = input[2]
--print(DDM_vec)
self.gradInput[2] = gradOutput[{{},2}]:clone()
for i=1, self.gradInput[1]:size(1) do
self.gradInput[1][{i,2}] = self.gradInput[1][{i,2}]*DDM_vec[{i}]
self.gradInput[2][{i}] = self.gradInput[2][{i}]*input[1][{i,2}]*self.DDM_learning_rate
end
return self.gradInput
end
|
-- Copyright (C) 2016 Gernot Riegler
-- Institute for Computer Graphics and Vision (ICG)
-- Graz University of Technology (TU GRAZ)
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- 3. All advertising materials mentioning features or use of this software
-- must display the following acknowledgement:
-- This product includes software developed by the ICG, TU GRAZ.
-- 4. Neither the name of the ICG, TU GRAZ 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 ''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 PROVIDER 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 model = {}
local function atgvl2(max_iter, lambda, edge_w, tgv_alpha0, tgv_alpha1, tensor_beta, tensor_gamma)
-- parameters
local max_iter = max_iter or 10
local lambda = lambda or 1
local edge_w = edge_w or 1
local tgv_alpha0 = tgv_alpha0 or 17
local tgv_alpha1 = tgv_alpha1 or 1.2
local tensor_beta = tensor_beta or 10
local tensor_gamma = tensor_gamma or 0.75
local eta_p = 3
local eta_q = 2
local tau = 1;
local sigma = 1 / tau;
local timestep_lambda = 1
local lambda_modules = {}
-- split net output estimate/edge
local input = nn.Identity()()
local u_init = nn.SelectTable(1)(input)
local edge = icgnn.IcgExpMul()
edge.weight:fill(math.log(edge_w))
edge = edge(nn.SelectTable(2)(input))
-- create anisotropic tensor
local tensor_abs = icgnn.IcgL2Norm()(edge)
local n_normed = nn.CDivTable()({edge, nn.Replicate(2, 1, 3)( nn.Threshold(0, 1e-6)(tensor_abs) )})
local nT_normed = icgnn.IcgVectorRotate()(n_normed)
local mul_tensor_b = nn.Mul(); mul_tensor_b.weight:fill(-tensor_beta)
local wtensor = nn.Threshold(1e-8, 1e-8, true)( nn.Exp()( mul_tensor_b( nn.Power(tensor_gamma)(tensor_abs) )) )
local n_normed_split = nn.SplitTable(1, 3)(n_normed)
local nT_normed_split = nn.SplitTable(1, 3)(nT_normed)
local atensor = nn.CAddTable()({nn.CMulTable()({wtensor, nn.Power(2)(nn.SelectTable(1)(n_normed_split))}), nn.Power(2)(nn.SelectTable(1)(nT_normed_split))})
local ctensor = nn.CAddTable()({nn.CMulTable()({wtensor, nn.SelectTable(1)(n_normed_split), nn.SelectTable(2)(n_normed_split)}), nn.CMulTable()({nn.SelectTable(1)(nT_normed_split), nn.SelectTable(2)(nT_normed_split)})})
local btensor = nn.CAddTable()({nn.CMulTable()({wtensor, nn.Power(2)(nn.SelectTable(2)(n_normed_split))}), nn.Power(2)(nn.SelectTable(2)(nT_normed_split))})
-- set up
local atensor2 = nn.Power(2)(atensor)
local btensor2 = nn.Power(2)(btensor)
local ctensor2 = nn.Power(2)(ctensor)
local eta_u = nn.Threshold(1e-8, 1e-8, false)( nn.MulConstant(tgv_alpha1^2, true)( nn.CAddTable()({atensor2, btensor2, nn.MulConstant(2, false)(ctensor2), nn.Power(2)(nn.CAddTable()({atensor, ctensor})), nn.Power(2)(nn.CAddTable()({btensor, ctensor}))}) ) )
local eta_v1 = nn.AddConstant(4*tgv_alpha0^2, true)(icgnn.IcgCAddTable({tgv_alpha1^2, tgv_alpha1^2}, true)({btensor2, ctensor2}))
local eta_v2 = nn.AddConstant(4*tgv_alpha0^2, true)(icgnn.IcgCAddTable({tgv_alpha1^2, tgv_alpha1^2}, true)({atensor2, ctensor2}))
local eta_v = nn.JoinTable(1, 3)({eta_v1, eta_v2})
-- iterations
local d = nn.Identity()(u_init)
local u = nn.Identity()(d)
local u_ = nn.Identity()(u)
local v_, p_x, p_y, q
local u_x, u_y, du_tensor_x, du_tensor_y, projection_p, Tp_x, Tp_y, dq_tensor, div_p
for iter = 1, max_iter do
local mu = 1 / math.sqrt(1 + 0.7 * tau * timestep_lambda)
if sigma >= 1e3 then mu = 1 end
-- dual variables update
local u_xy = nil
if iter == 1 then
u_xy = nn.SplitTable(1, 3)( icgnn.IcgNabla()(u_) )
else
u_xy = nn.SplitTable(1, 3)( icgnn.IcgCAddTable({1, -1}, true)({icgnn.IcgNabla()(u_), v_}) )
end
u_x = nn.SelectTable(1)(u_xy)
u_y = nn.SelectTable(2)(u_xy)
du_tensor_x = nn.CAddTable()({nn.CMulTable()({atensor, u_x}), nn.CMulTable()({ctensor, u_y})})
du_tensor_y = nn.CAddTable()({nn.CMulTable()({ctensor, u_x}), nn.CMulTable()({btensor, u_y})})
if iter == 1 then
local mul_du_tensor_x = nn.Mul(); mul_du_tensor_x.weight:fill(tgv_alpha1 * sigma / eta_p)
p_x = mul_du_tensor_x(du_tensor_x)
local mul_du_tensor_y = nn.Mul(); mul_du_tensor_y.weight:fill(tgv_alpha1 * sigma / eta_p)
p_y = mul_du_tensor_y(du_tensor_y)
else
local mul_du_tensor_x = nn.Mul(); mul_du_tensor_x.weight:fill(tgv_alpha1 * sigma / eta_p)
p_x = nn.CAddTable()({p_x, mul_du_tensor_x(du_tensor_x)})
local mul_du_tensor_y = nn.Mul(); mul_du_tensor_y.weight:fill(tgv_alpha1 * sigma / eta_p)
p_y = nn.CAddTable()({p_y, mul_du_tensor_y(du_tensor_y)})
end
projection_p = nn.Threshold(1, 1, true)(nn.Sqrt()(nn.CAddTable()({nn.Power(2)(p_x), nn.Power(2)(p_y)})))
p_x = nn.CDivTable()({p_x, projection_p})
p_y = nn.CDivTable()({p_y, projection_p})
if iter > 1 and iter < max_iter then
local grad_v = icgnn.IcgNabla()(v_)
if iter == 2 then
local mul_grad_v = nn.Mul(); mul_grad_v.weight:fill(tgv_alpha0 * sigma / eta_q)
q = mul_grad_v(grad_v)
else
local mul_grad_v = nn.Mul(); mul_grad_v.weight:fill(tgv_alpha0 * sigma / eta_q)
q = nn.CAddTable()({q, mul_grad_v(grad_v)})
end
local projection_q = nn.Threshold(1, 1, true)(icgnn.IcgL2Norm()(q))
q = nn.CDivTable()({q, nn.Replicate(4)(projection_q)})
end
-- primal variables update
u_ = nn.Identity()(u)
if iter >= 2 and iter < max_iter then
v_ = nn.Identity()(v)
end
Tp_x = nn.CAddTable()({nn.CMulTable()({atensor, p_x}), nn.CMulTable()({ctensor, p_y})})
Tp_y = nn.CAddTable()({nn.CMulTable()({ctensor, p_x}), nn.CMulTable()({btensor, p_y})})
dq_tensor = nn.JoinTable(1, 3)({Tp_x, Tp_y})
div_p = icgnn.IcgNablaT(true)( dq_tensor )
local lambda_numerator = icgnn.IcgExpMul()
lambda_numerator.weight:fill(math.log(lambda * tau))
local numerator = nn.CAddTable()({ u_, nn.CDivTable()({ nn.CAddTable()({nn.MulConstant(tau * tgv_alpha1, true)(div_p), lambda_numerator(d)}), eta_u }) })
local lambda_denominator = icgnn.IcgExpMul()
lambda_denominator.weight:fill(math.log(lambda * tau))
local denominator = nn.AddConstant(1, true)(lambda_denominator(nn.Power(-1)(eta_u)))
u = nn.CDivTable()({numerator, denominator})
if iter < max_iter then
if iter == 1 then
v = nn.CDivTable()({ nn.MulConstant(tau * tgv_alpha1, true)(dq_tensor), eta_v })
else
local div_q = icgnn.IcgNablaT(true)(q)
v = nn.CAddTable()({ v_, nn.CDivTable()({ icgnn.IcgCAddTable({tau * tgv_alpha1, tau * tgv_alpha0}, true)({dq_tensor, div_q}), eta_v }) })
end
end
-- over relaxation
u_ = icgnn.IcgCAddTable({1 + mu, -mu}, true)({u, u_})
if iter < max_iter then
if iter == 1 then
v_ = nn.MulConstant(1 + mu, false)(v)
else
v_ = icgnn.IcgCAddTable({1 + mu, -mu}, true)({v, v_})
end
end
sigma = sigma / mu
tau = tau * mu
end
local net = nn.gModule({input}, {u_})
return net
end
function model.load(opt)
local backend
if opt.cudnn then
backend = cudnn
else
backend = nn
end
opt.model_name = 'atgvl2'
opt.criterion = nn.MSECriterion()
opt.optimizer = optim['sgd']
opt.learningRate = 1e-4
opt.clip_gradient = 0.1
opt.batch_size = 32
local atgvl2_net = atgvl2(unpack(opt.atgvl2_params))
opt.net = atgvl2_net
return opt
end
return model
|
local ANIMALS = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}
local ELEMENTS = {"Wood","Fire","Earth","Metal","Water"}
function element(year)
local idx = math.floor(((year - 4) % 10) / 2)
return ELEMENTS[idx + 1]
end
function animal(year)
local idx = (year - 4) % 12
return ANIMALS[idx + 1]
end
function yy(year)
if year % 2 == 0 then
return "yang"
else
return "yin"
end
end
function zodiac(year)
local e = element(year)
local a = animal(year)
local y = yy(year)
print(year.." is the year of the "..e.." "..a.." ("..y..")")
end
zodiac(1935)
zodiac(1938)
zodiac(1968)
zodiac(1972)
zodiac(1976)
zodiac(2017)
|
local messager = require 'script.messager'
local code = require 'script.code'
local redis = require 'script.redis'
local cheat = require 'script.common.cheat'
local data, err = messager.recive()
if not data then
ngx.log(ngx.WARN, err)
messager.response {
result = false,
error = code.ERROR_PROTO_ERROR,
message = err,
}
return
end
local function call()
if data.type == 'cheat' then
return redis.call(cheat.report, data.value)
end
error('Unknown proto:' .. tostring(data.type))
end
local suc, res = xpcall(call, debug.traceback)
if not suc then
ngx.log(ngx.ERR, res)
messager.response {
request = data.type,
result = false,
error = code.ERROR_RUNTIME,
message = res,
}
return
end
messager.response {
request = data.type,
result = true,
value = res,
}
|
-- Obstacle.lua
Obstacle = class('Obstacle')
function Obstacle.initialize(this)
this.Pos = {X = 0, Y = 300}
this.Vel = {X = 500, Y = 0}
this.Graphic = nil
end
function Obstacle.draw(this)
love.graphics.draw(this.Graphic, this.Pos.X, this.Pos.Y)
end
function Obstacle.update(this, dt)
-- Movement
this.Pos.X = this.Pos.X + (this.Vel.X * dt)
this.Pos.Y = this.Pos.Y + (this.Vel.Y * dt)
end |
object_draft_schematic_weapon_component_shared_new_weapon_comp_blade_vibro_unit = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_blade_vibro_unit.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_blade_vibro_unit, "object/draft_schematic/weapon/component/shared_new_weapon_comp_blade_vibro_unit.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_blade_vibro_unit_advanced = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_blade_vibro_unit_advanced.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_blade_vibro_unit_advanced, "object/draft_schematic/weapon/component/shared_new_weapon_comp_blade_vibro_unit_advanced.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_blade_vibro_unit_exceptional = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_blade_vibro_unit_exceptional.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_blade_vibro_unit_exceptional, "object/draft_schematic/weapon/component/shared_new_weapon_comp_blade_vibro_unit_exceptional.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_pistol_barrel = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_pistol_barrel.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_pistol_barrel, "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_pistol_barrel.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_pistol_barrel_advanced = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_pistol_barrel_advanced.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_pistol_barrel_advanced, "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_pistol_barrel_advanced.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_pistol_barrel_exceptional = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_pistol_barrel_exceptional.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_pistol_barrel_exceptional, "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_pistol_barrel_exceptional.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_rifle_barrel = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_rifle_barrel.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_rifle_barrel, "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_rifle_barrel.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_rifle_barrel_advanced = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_rifle_barrel_advanced.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_rifle_barrel_advanced, "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_rifle_barrel_advanced.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_rifle_barrel_exceptional = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_rifle_barrel_exceptional.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_blaster_rifle_barrel_exceptional, "object/draft_schematic/weapon/component/shared_new_weapon_comp_blaster_rifle_barrel_exceptional.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_acid = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_acid.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_acid, "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_acid.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_cold = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_cold.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_cold, "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_cold.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_electric = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_electric.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_electric, "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_electric.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_heat = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_heat.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_heat, "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_heat.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_heavy = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_heavy.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_elemental_heavy, "object/draft_schematic/weapon/component/shared_new_weapon_comp_elemental_heavy.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_gas_cartridge = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_gas_cartridge.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_gas_cartridge, "object/draft_schematic/weapon/component/shared_new_weapon_comp_gas_cartridge.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_gas_cartridge_advanced = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_gas_cartridge_advanced.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_gas_cartridge_advanced, "object/draft_schematic/weapon/component/shared_new_weapon_comp_gas_cartridge_advanced.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_gas_cartridge_exceptional = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_gas_cartridge_exceptional.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_gas_cartridge_exceptional, "object/draft_schematic/weapon/component/shared_new_weapon_comp_gas_cartridge_exceptional.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_pistol_barrel = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_pistol_barrel.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_pistol_barrel, "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_pistol_barrel.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_pistol_barrel_advanced = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_pistol_barrel_advanced.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_pistol_barrel_advanced, "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_pistol_barrel_advanced.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_pistol_barrel_exceptional = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_pistol_barrel_exceptional.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_pistol_barrel_exceptional, "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_pistol_barrel_exceptional.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_rifle_barrel = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_rifle_barrel.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_rifle_barrel, "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_rifle_barrel.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_rifle_barrel_advanced = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_rifle_barrel_advanced.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_rifle_barrel_advanced, "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_rifle_barrel_advanced.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_rifle_barrel_exceptional = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_rifle_barrel_exceptional.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_projectile_rifle_barrel_exceptional, "object/draft_schematic/weapon/component/shared_new_weapon_comp_projectile_rifle_barrel_exceptional.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_reinforcement_core = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_reinforcement_core.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_reinforcement_core, "object/draft_schematic/weapon/component/shared_new_weapon_comp_reinforcement_core.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_reinforcement_core_advanced = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_reinforcement_core_advanced.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_reinforcement_core_advanced, "object/draft_schematic/weapon/component/shared_new_weapon_comp_reinforcement_core_advanced.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_reinforcement_core_exceptional = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_reinforcement_core_exceptional.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_reinforcement_core_exceptional, "object/draft_schematic/weapon/component/shared_new_weapon_comp_reinforcement_core_exceptional.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_scope = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_scope.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_scope, "object/draft_schematic/weapon/component/shared_new_weapon_comp_scope.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_new_weapon_comp_stock = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_new_weapon_comp_stock.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_new_weapon_comp_stock, "object/draft_schematic/weapon/component/shared_new_weapon_comp_stock.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_projectile_rifle_barrel_faux_bowcaster = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_projectile_rifle_barrel_faux_bowcaster.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_projectile_rifle_barrel_faux_bowcaster, "object/draft_schematic/weapon/component/shared_projectile_rifle_barrel_faux_bowcaster.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_vibro_unit_nightsister = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_vibro_unit_nightsister.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_vibro_unit_nightsister, "object/draft_schematic/weapon/component/shared_vibro_unit_nightsister.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_draft_schematic_weapon_component_shared_weapon_power_bit = SharedDraftSchematicObjectTemplate:new {
clientTemplateFileName = "object/draft_schematic/weapon/component/shared_weapon_power_bit.iff"
}
ObjectTemplates:addClientTemplate(object_draft_schematic_weapon_component_shared_weapon_power_bit, "object/draft_schematic/weapon/component/shared_weapon_power_bit.iff")
------------------------------------------------------------------------------------------------------------------------------------
|
package("newtondynamics")
set_homepage("http://newtondynamics.com")
set_description("Newton Dynamics is an integrated solution for real time simulation of physics environments.")
set_license("zlib")
set_urls("https://github.com/MADEAPPS/newton-dynamics.git")
add_versions("v3.14d", "e501c6d13e127a595c847d92b12ca3c7616a441d")
if is_plat("mingw") and is_subhost("msys") then
add_extsources("pacman::newton-dynamics")
elseif is_plat("linux") then
add_extsources("pacman::newton-dynamics")
end
if is_plat("linux", "android") then
add_syslinks("dl", "pthread")
end
on_load(function (package)
if package:is_plat("windows") and not package:config("shared") then
package:add("defines", "_NEWTON_STATIC_LIB")
end
end)
on_install("windows", "linux", "macosx", "mingw", function (package)
os.cd("newton-3.14")
local configs = {}
configs.kind = package:config("shared") and "shared" or "static"
configs.mode = package:debug() and "debug" or "release"
if not package:config("shared") and package:is_plat("linux", "android") and package:config("pic") ~= false then
configs.cxflags = "-fPIC"
end
os.cp(path.join(package:scriptdir(), "port", "xmake.lua"), "xmake.lua")
import("package.tools.xmake").install(package, configs)
end)
on_test(function (package)
assert(package:check_cxxsnippets({test = [[
void test(int args, char** argv) {
NewtonWorld* world = NewtonCreate();
NewtonDestroy(world);
}
]]}, {includes = "newton/Newton.h"}))
end)
|
local p = game.Players.LocalPlayer
local Mpc = p.Character
local mouse = p:GetMouse()
visible=false
function fgeld(zName,zParent,zPart0,zPart1,zCoco,a,b,c,d,e,f)
local funcw = Instance.new("Weld")
funcw.Name = zName
funcw.Parent = zParent
funcw.Part0 = zPart0
funcw.Part1 = zPart1
if (zCoco == true) then
funcw.C0 = CFrame.new(a,b,c) *CFrame.fromEulerAnglesXYZ(d,e,f)
else
funcw.C1 = CFrame.new(a,b,c) *CFrame.fromEulerAnglesXYZ(d,e,f)
end
return funcw
end
-------------------
size = 3
t2 = game.Players.LocalPlayer.Character.Torso
pcall(function() game.Players.LocalPlayer.Character.Torso["Something Beautiful"]:Remove() end)
mdl = Instance.new("Model",t2)
mdl.Name = ("Something Beautiful")
local bl = Instance.new("Part")
bl.TopSurface = 0
bl.BottomSurface = 0
bl.CanCollide = false
bl.BrickColor = Mpc.Torso.BrickColor
bl.Shape = "Ball"
bl.Parent = mdl
bl.Size = Vector3.new(1,1,1)
local dm = Instance.new("SpecialMesh")
dm.MeshType = "Sphere"
dm.Parent = bl
dm.Scale = Vector3.new(1.2,1.2,1.2)
fgeld("weld",mdl,t2,bl,true,-0.5,0.5,-0.6,0,0,0)
local br = Instance.new("Part")
br.TopSurface = 0
br.BottomSurface = 0
br.CanCollide = false
br.BrickColor = Mpc.Torso.BrickColor
br.Shape = "Ball"
br.Parent = mdl
br.Size = Vector3.new(1,1,1)
local dm = Instance.new("SpecialMesh")
dm.MeshType = "Sphere"
dm.Parent = br
dm.Scale = Vector3.new(1.2,1.2,1.2)
fgeld("weld",mdl,t2,br,true,0.5,0.5,-0.6,0,0,0)
local bln = Instance.new("Part")
bln.BrickColor = BrickColor.new("Pink")
bln.TopSurface = 0
bln.BottomSurface = 0
bln.CanCollide = false
bln.Shape = "Ball"
bln.Parent = mdl
bln.Size = Vector3.new(1,1,1)
local dm = Instance.new("SpecialMesh")
dm.MeshType = "Sphere"
dm.Parent = bln
dm.Scale = Vector3.new(0.2,0.2,0.2)
fgeld("weld",mdl,t2,bln,true,-0.5,0.5,-1.2,0,0,0)
local brn = Instance.new("Part")
brn.BrickColor = BrickColor.new("Pink")
brn.TopSurface = 0
brn.BottomSurface = 0
brn.CanCollide = false
brn.Shape = "Ball"
brn.Parent = mdl
brn.Size = Vector3.new(1,1,1)
local dm = Instance.new("SpecialMesh")
dm.MeshType = "Sphere"
dm.Parent = brn
dm.Scale = Vector3.new(0.2,0.2,0.2)
fgeld("weld",mdl,t2,brn,true,0.5,0.5,-1.2,0,0,0)
for i,v in pairs(mdl:children()) do
if v:IsA("Part") then
v.Transparency=0
end
end
end
mouse.KeyDown:connect(function(key)
if key == "n" and visible==true then
for i,v in pairs(mdl:children()) do
if v:IsA("Part") then
v.Transparency=1
end
end
end
visible=false
end)
mouse.KeyDown:connect(function(key)
if key == "n" and visible==false then
for i,v in pairs(mdl:children()) do
if v:IsA("Part") then
v.Transparency=0
end
end
end
visible=true
end)
local V = Instance.new("Part", Mpc)
V.Size = Vector3.new(0.5,1,0.25)
V.BrickColor = Mpc.Torso.BrickColor
Instance.new("SpecialMesh",V).MeshType = "Sphere"
local VW = Instance.new("Weld", V)
VW.Part0 = Mpc.Torso
VW.Part1 = V
VW.C0 = CFrame.new(0,-1,-0.5)
local GH = Instance.new("Part", V)
GH.Size = Vector3.new(0.25,0.5,0.25)
GH.BrickColor = BrickColor.new("Pink")
Instance.new("SpecialMesh",GH).MeshType = "Sphere"
local GHW = Instance.new("Weld", GH)
GHW.Part0 = V
GHW.Part1 = GH
GHW.C0 = CFrame.new(0, 0,-0.1)
local V = Instance.new("Part", Mpc)
V.Size = Vector3.new(0.5,1,0.25)
V.BrickColor = Mpc.Torso.BrickColor
Instance.new("SpecialMesh",V).MeshType = "Sphere"
local VW = Instance.new("Weld", V)
VW.Part0 = Mpc.Torso
VW.Part1 = V
VW.C0 = CFrame.new(0,-1,-0.5)
local GH = Instance.new("Part", V)
GH.Size = Vector3.new(0.25,0.5,0.25)
GH.BrickColor = BrickColor.new("Pink")
Instance.new("SpecialMesh",GH).MeshType = "Sphere"
local GHW = Instance.new("Weld", GH)
GHW.Part0 = V
GHW.Part1 = GH
GHW.C0 = CFrame.new(0, 0,-0.1) |
local request = KEYS[1]
local value = ARGV[1]
if redis.call('get', request) == value then
return redis.call('del', request)
else
return -1
end |
--[[
Load this test file by adding
lua_preload_file ./lua_preload_file.lua
to the civetweb.conf file
]]
mg.preload = "lua_preload_file successfully loaded"
|
local collectionService = game:GetService("CollectionService")
local insert = game:GetService("InsertService")
-- https://devforum.roblox.com/t/how-can-i-get-a-random-position-located-through-the-size-of-the-part/253540/6
function getRandomInPart(part)
local random = Random.new()
local randomCFrame = part.CFrame * CFrame.new(random:NextNumber(-part.Size.X/2,part.Size.X/2), random:NextNumber(-part.Size.Y/2,part.Size.Y/2), random:NextNumber(-part.Size.Z/2,part.Size.Z/2))
return randomCFrame
end
print("loading server spawn manager cleanup proccess...")
local cleanup = coroutine.create(function ()
while true do
wait(5)
for i, item in pairs(game.Workspace:WaitForChild("spawnStorage"):GetDescendants()) do
if item:IsA("Model") then
local innerCount = #item:GetChildren()
if innerCount == 0 then
item:Destroy()
end
end
end
end
end)
coroutine.resume(cleanup)
print("loading server spawn manager...")
-- configure this table for new mobs
local mobSpawns = {
bull = collectionService:GetTagged("BullSpawn"),
forestMage = collectionService:GetTagged("ForestMageSpawn")
}
local mobIds = {
bull = 7214764565,
forestMage = 7384742784
}
local tick = 5
-- every tick, we spawn new mobs at areas that need them
local enableSpawnInstance = game.ServerStorage:FindFirstChild("enableMobSpawn")
local enableSpawn = true
if enableSpawnInstance ~= nil then
enableSpawn = enableSpawnInstance.Value
end
function spawnMob(mobName, instances)
if game.Workspace:FindFirstChild("spawnStorage") == nil then
warn("creating spawn storage in studio is recommened.")
local spawnStorage = Instance.new("Folder")
spawnStorage.Name = "spawnStorage"
spawnStorage.Parent = game.Workspace
end
local spawnStorage = game.Workspace:FindFirstChild("spawnStorage")
if spawnStorage:FindFirstChild(mobName) == nil then
local folder = Instance.new("Folder")
folder.Name = mobName
folder.Parent = game.Workspace.spawnStorage
end
for mobIndex, instance in pairs(instances) do
local spawnLimit = instance:FindFirstChild("maxLimit")
if spawnLimit == nil then
spawnLimit = 15
else
spawnLimit = spawnLimit.Value
end
local mobStore = spawnStorage[mobName]:FindFirstChild(tostring(mobIndex))
if mobStore == nil then
local inst = Instance.new("Folder")
inst.Name = tostring(mobIndex)
inst.Parent = spawnStorage[mobName]
mobStore = inst
end
local currentSpawns = #mobStore:GetChildren()
if currentSpawns >= spawnLimit then
print("not spawning: max limit reached.")
else
-- spawn mob
if mobIds[mobName] == nil then
warn("not spawning "..mobName..": asset id not found.")
else
local insertItem = insert:LoadAsset(mobIds[mobName])
local mobModel = insertItem:GetChildren()[1]
insertItem.Parent = mobStore
mobModel:MoveTo(getRandomInPart(instance).Position)
end
end
end
end
while enableSpawn do
-- don't use wait, might migrate the reset of the codebase over to using task.wait soon
task.wait(tick)
for mobName, mobInstances in pairs(mobSpawns) do
spawnMob(mobName, mobInstances)
end
end |
--====================================================================--
-- dmc_ui/dmc_widget/widget_text.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2015 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
--== DMC Corona UI : Text Widget
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
--== DMC UI Setup
--====================================================================--
local dmc_ui_data = _G.__dmc_ui
local dmc_ui_func = dmc_ui_data.func
local ui_find = dmc_ui_func.find
--====================================================================--
--== DMC UI : newText
--====================================================================--
--====================================================================--
--== Imports
local Objects = require 'dmc_objects'
local uiConst = require( ui_find( 'ui_constants' ) )
local WidgetBase = require( ui_find( 'core.widget' ) )
local WidgetHelp = require( ui_find( 'core.widget_helper' ) )
--====================================================================--
--== Setup, Constants
local newText = display.newText
local ssub = string.sub
--== To be set in initialize()
local dUI = nil
local FontMgr = nil
--====================================================================--
--== Support Functions
local function testTextLength( text, params )
-- print( "Text:testTextLength", text, params.width )
local w = params.width
local f = params.font
local fs = params.fontSize
local fsm = params.fontSizeMinimum
local _ssub = ssub
local _newText = newText
--== check size with defaults
local o = _newText{
text=text,
font=f,
fontSize=fs
}
local tw = o.width
o:removeSelf()
if tw < w then return text, fs end
--== check for font minimum
if fsm~=0 then
local cfs = fs-1 -- current font size
while cfs>=fsm do
local o = _newText{
text=text,
font=f,
fontSize=cfs
}
local tw = o.width
o:removeSelf()
if tw > w then
cfs = cfs-1
else
break
end
end
if cfs<fsm then
-- text too big, shorten with '...'
fs=fsm
else
return text, cfs
end
end
--== check for ellipses
local cnt = 0
local prev = '...'
while true do
local t = ssub( text, 0, cnt )..'...'
local o = _newText{
text=t,
font=f,
fontSize=fs
}
local tw = o.width
o:removeSelf()
if tw <= w then
cnt = cnt + 1 ; prev = t
else
break
end
end
return prev, fs
end
--====================================================================--
--== Text Widget Class
--====================================================================--
--- Text Widget Module.
-- displays text content. this widget wraps the a Corona OpenGL Text component to provide its core functionality.
--
-- **Inherits from:** <br>
-- * @{Core.Widget}
--
-- **Style Object:** <br>
-- * @{Style.Text}
--
-- @classmod Widget.Text
-- @usage
-- dUI = require 'dmc_ui'
-- widget = dUI.newText()
local Text = newClass( WidgetBase, { name="Text Widget" } )
--- Class Constants.
-- @section
--== Class Constants
--- Constant for 'left'
Text.LEFT = 'left'
--- Constant for 'center'
Text.CENTER = 'center'
--- Constant for 'right'
Text.RIGHT = 'right'
--== Style/Theme Constants
Text.STYLE_CLASS = nil -- added later
Text.STYLE_TYPE = uiConst.TEXT
-- TODO: hook up later
-- Text.DEFAULT = 'default'
-- Text.THEME_STATES = {
-- Text.DEFAULT,
-- }
--== Event Constants
Text.EVENT = 'text-widget-event'
Text.DIMENSION_CHANGED = 'dimension-changed-event'
--======================================================--
-- Start: Setup DMC Objects
--== Init
function Text:__init__( params )
-- print( "Text:__init__", params )
params = params or {}
if params.text==nil then params.text="" end
self:superCall( '__init__', params )
--==--
--== Create Properties ==--
-- properties in this class
self._text = params.text
self._text_dirty=true
-- properties from style
-- virtual
self._displayWidth_dirty=true
self._displayHeight_dirty=true
self._rectBgWidth_dirty=true
self._rectBgHeight_dirty=true
self._align_dirty=true
self._fillColor_dirty = true
self._font_dirty=true
self._fontSize_dirty=true
self._marginX_dirty=true
self._marginY_dirty=true
self._strokeColor_dirty=true
self._strokeWidth_dirty=true
self._textColor_dirty=true
self._textObject_dirty=true
-- virtual
self._textX_dirty=true
self._textY_dirty=true
--== Object References ==--
self._txtText = nil -- our text object
self._rectBg = nil -- our background object
end
--[[
function Text:__undoInit__()
-- print( "Text:__undoInit__" )
--==--
self:superCall( '__undoInit__' )
end
--]]
--== createView
function Text:__createView__()
-- print( "Text:__createView__" )
self:superCall( '__createView__' )
--==--
local o = display.newRect( 0,0,0,0 )
o.anchorX, o.anchorY = 0.5, 0.5
self:insert( o )
self._rectBg = o
end
function Text:__undoCreateView__()
-- print( "Text:__undoCreateView__" )
self._rectBg:removeSelf()
self._rectBg=nil
--==--
self:superCall( '__undoCreateView__' )
end
--== initComplete
--[[
function Text:__initComplete__()
-- print( "Text:__initComplete__" )
self:superCall( '__initComplete__' )
--==--
end
--]]
function Text:__undoInitComplete__()
--print( "Text:__undoInitComplete__" )
self:_removeText()
--==--
self:superCall( '__undoInitComplete__' )
end
-- END: Setup DMC Objects
--======================================================--
--====================================================================--
--== Static Methods
function Text.initialize( manager )
-- print( "Text.initialize" )
dUI = manager
local Widget = nil
FontMgr = dUI.FontMgr
local Style = dUI.Style
Text.STYLE_CLASS = Style.Text
Style.registerWidget( Text )
end
--====================================================================--
--== Public Methods
--== .align
--- [**style**] set/get align.
-- values are 'left', 'center', 'right'
--
-- @within Properties
-- @function .align
-- @usage widget.align = 'center'
-- @usage print( widget.align )
Text.__getters.align = WidgetHelp.__getters.align
Text.__setters.align = WidgetHelp.__setters.align
--== .fillColor
--- [**style**] set/get Style value for Widget fill color.
--
-- @within Properties
-- @function .fillColor
-- @usage style.fillColor = '#ff0000'
-- @usage print( style.fillColor )
Text.__getters.fillColor = WidgetHelp.__getters.fillColor
Text.__setters.fillColor = WidgetHelp.__setters.fillColor
--== .font
--- [**style**] set/get font.
-- can either be Corona font (eg, native.systemFont) or one installed in system (eg, 'Helvetica-Grande')
--
-- @within Properties
-- @function .font
-- @usage widget.font = native.systemFont
-- @usage print( widget.font )
Text.__getters.font = WidgetHelp.__getters.font
Text.__setters.font = WidgetHelp.__setters.font
--== .fontSize
--- [**style**] set/get fontSize.
-- set the font size of the text.
--
-- @within Properties
-- @function .fontSize
-- @usage widget.fontSize = 18
-- @usage print( widget.fontSize )
Text.__getters.fontSize = WidgetHelp.__getters.fontSize
Text.__setters.fontSize = WidgetHelp.__setters.fontSize
--== .marginX
--- [**style**] set/get marginX.
-- set the margin inset of the widget. this value is *subtracted* from the widget width.
--
-- @within Properties
-- @function .marginX
-- @usage widget.marginX = 18
-- @usage print( widget.marginX )
Text.__getters.marginX = WidgetHelp.__getters.marginX
Text.__setters.marginX = WidgetHelp.__setters.marginX
--== .strokeWidth
--- [**style**] set/get strokeWidth.
-- set stroke width for the simple background.
--
-- @within Properties
-- @function .strokeWidth
-- @usage widget.strokeWidth = 18
-- @usage print( widget.strokeWidth )
Text.__getters.strokeWidth = WidgetHelp.__getters.strokeWidth
Text.__setters.strokeWidth = WidgetHelp.__setters.strokeWidth
--== .textColor
--- [**style**] set/get textColor.
-- set the font size of the text.
--
-- @within Properties
-- @function .textColor
-- @usage widget.textColor = 18
-- @usage print( widget.textColor )
Text.__getters.textColor = WidgetHelp.__getters.textColor
Text.__setters.textColor = WidgetHelp.__setters.textColor
--[[
we use custom getters for width/height
without width/height, we just use dimensions
from text object after creation
--]]
--== .width (custom)
--- [**style**] set/get width.
-- Note: this property changes both the width of the DMC Text Widget and the encapsulated Corona Text widget. If the style is unset, then the width value is the width of the encapsulated Corona Text widget. If the style value is set, then then the width for both will change to that value.
--
-- @within Properties
-- @function .width
-- @usage widget.width = 5
-- @usage print( widget.width )
function Text.__getters:width()
-- print( 'Text.__getters:width' )
local style = self.curr_style
local w, t = style.width, self._txtText
if w==0 and t then
w=t.width+style.marginX*2
end
return w
end
function Text.__setters:width( value )
-- print( 'Text.__setters:width', value )
self.curr_style.width = value
end
--== .height (custom)
--- [**style**] set/get height.
-- Note: this property *doesn't* change the height of the actual *Corona Text widget*, that remains constant. If the style is unset, then the height value is the height of the encapsulated Corona Text widget. If the style value is set, then then the height is that value, even if the height of the Corona Text widget is different. (If the height of the Corona Text widget is set then it becomes a multi-line text widget.)
--
-- @within Properties
-- @function .height
-- @usage widget.height = 5
-- @usage print( widget.height )
function Text.__getters:height()
-- print( 'Text.__getters:height' )
local style = self.curr_style
local h, t = style.height, self._txtText
if h==0 then
h = self:getTextHeight()+style.marginY*2
end
return h
end
function Text.__setters:height( value )
-- print( 'Text.__setters:height', value )
self.curr_style.height = value
end
--== .text
--- set/get widget text.
--
-- @within Properties
-- @function .text
-- @usage widget.text = 5
-- @usage print( widget.text )
function Text.__getters:text()
return self._text
end
function Text.__setters:text( value )
-- print( 'Text.__setters:text', value )
assert( type(value)=='string' )
--==--
if self._text == value then return end
self._text = value
self._text_dirty=true
self:__invalidateProperties__()
end
--- get height of Corona Text object.
-- return the height of the encapsulated Corona text object, not height of the DMC Text Widget. returns 0 if Corona Text has yet to be created.
--
-- @within Methods
-- @function :getTextHeight
-- @treturn number height of Corona Text object
-- @usage print( widget:getTextHeight() )
function Text:getTextHeight()
-- print( "Text:getTextHeight", self._txtText )
local val = 0
local o = self._txtText
if o then val = o.height end
return val
end
--== .setFillColor
--- set the fill color of the simple background.
--
-- @within Methods
-- @function :setFillColor
-- @usage
-- widget:setFillColor( grey )
-- widget:setFillColor( grey, a )
-- widget:setFillColor( r, g, b, a )
-- widget:setFillColor( gradient )
Text.setFillColor = WidgetHelp.setFillColor
Text.setFillColor = WidgetHelp.setFillColor
--== .setStrokeColor
--- set stroke color of the simple background.
--
-- @within Methods
-- @function :setStrokeColor
-- @usage
-- widget:setStrokeColor( grey )
-- widget:setStrokeColor( grey, a )
-- widget:setStrokeColor( r, g, b, a )
-- widget:setStrokeColor( gradient )
Text.setStrokeColor = WidgetHelp.setStrokeColor
Text.setStrokeColor = WidgetHelp.setStrokeColor
--== .setTextColor
--- set color of text.
--
-- @within Methods
-- @function :setTextColor
-- @usage
-- widget:setTextColor( grey )
-- widget:setTextColor( grey, a )
-- widget:setTextColor( r, g, b, a )
-- widget:setTextColor( gradient )
Text.setTextColor = WidgetHelp.setTextColor
Text.setTextColor = WidgetHelp.setTextColor
--====================================================================--
--== Private Methods
function Text:_removeText()
-- print( "Text:_removeText" )
local o = self._txtText
if not o then return end
o:removeSelf()
self._txtText = nil
end
function Text:_createText()
-- print( "Text:_createText" )
local style = self.curr_style
local o -- object
self:_removeText()
local w, h = style.width, style.height
local font, fontSize = style.font, style.fontSize
local text = self._text
local tw
if w==0 then
tw=nil
else
tw = w - style.marginX*2
text, fontSize = testTextLength( text, {
width=w, font=font,
fontSize=fontSize,
fontSizeMinimum=style.fontSizeMinimum
})
end
o = newText{
x=0, y=0,
width=tw,
-- don't use height, turns into multi-line
height=nil,
text=text,
align=style.align,
font=font,
fontSize=fontSize,
}
self:insert( o )
self._txtText = o
--== Reset properties
self._x_dirty=true
self._y_dirty=true
self._width_dirty=true
self._height_dirty=true
if w==0 or h==0 then
self._textDimension_dirty=true
end
self._text_dirty=false
self._textColor_dirty=true
end
function Text:__commitProperties__()
-- print( 'Text:__commitProperties__' )
local style = self.curr_style
-- local metric = FontMgr:getFontMetric( style.font, style.fontSize )
-- metric={offsetX=0,offsetY=0}
if self._width_dirty then
self._width_dirty=false
self._anchorX_dirty=true
self._displayWidth_dirty=true
self._rectBgWidth_dirty=true
self._textObject_dirty=true
end
if self._height_dirty then
self._height_dirty=false
self._anchorY_dirty=true
self._displayHeight_dirty=true
self._rectBgHeight_dirty=true
end
-- create new text if necessary
if self._align_dirty or self._font_dirty or self._fontSize_dirty or self._textObject_dirty then
self:_createText()
self._align_dirty=false
self._font_dirty=false
self._fontSize_dirty=false
self._textObject_dirty=false
end
local view = self.view
local bg = self._rectBg
local txt = self._txtText
--== position sensitive
-- set text string
if self._text_dirty then
self._text_dirty=false
end
if self._marginX_dirty then
self._marginX_dirty=false
self._displayWidth_dirty=true
self._rectBgWidth_dirty=true
self._textX_dirty=true
end
if self._marginY_dirty then
--== Reminder, we don't set text height ==--
self._marginY_dirty=false
self._displayHeight_dirty=true
self._rectBgHeight_dirty=true
self._textY_dirty=true
end
-- bg width/height
if self._rectBgWidth_dirty then
bg.width = self.width -- use getter
self._rectBgWidth_dirty=false
end
if self._rectBgHeight_dirty then
bg.height = self.height -- use getter
self._rectBgHeight_dirty=false
end
if self._displayWidth_dirty then
self._displayWidth_dirty=false
end
if self._displayHeight_dirty then
--== !! DO NOT SET HEIGHT OF TEXT !! ==--
--[[
-- -- txt.height = self.height
--]]
self._displayHeight_dirty=false
end
-- anchorX/anchorY
if self._anchorX_dirty then
bg.anchorX = style.anchorX
self._anchorX_dirty=false
self._x_dirty=true
self._textX_dirty=true
end
if self._anchorY_dirty then
bg.anchorY = style.anchorY
self._anchorY_dirty=false
self._y_dirty=true
self._textY_dirty=true
end
-- x/y
if self._x_dirty then
view.x = self._x
self._x_dirty = false
self._textX_dirty=true
end
if self._y_dirty then
view.y = self._y
self._y_dirty = false
self._textY_dirty=true
end
-- text align x/y
if self._textX_dirty then
local align = style.align
local w = style.width
local width = self.width -- use getter, it's smart
local offset
if align == self.LEFT then
txt.anchorX = 0
offset = -width*(style.anchorX)
if w~=nil then
offset = offset+style.marginX
end
txt.x=offset
elseif align == self.RIGHT then
txt.anchorX = 1
offset = width*(1-style.anchorX)
if w~=nil then
offset = offset-style.marginX
end
txt.x=offset
else
txt.anchorX = 0.5
offset = width*(0.5-style.anchorX)
txt.x=offset
end
self._textX_dirty = false
end
if self._textY_dirty then
local height = self.height -- use getter
local offset
txt.anchorY = 0.5
offset = height/2-height*(style.anchorY)
txt.y=offset
self._textY_dirty=false
end
--== non-position sensitive
-- textColor/fillColor
if self._fillColor_dirty or self._debugOn_dirty then
if style.debugOn==true then
bg:setFillColor( 1,0,0,0.2 )
else
bg:setFillColor( unpack( style.fillColor ))
end
self._fillColor_dirty=false
self._debugOn_dirty=false
end
if self._strokeColor_dirty then
bg:setStrokeColor( unpack( style.strokeColor ))
self._strokeColor_dirty=false
end
if self._strokeWidth_dirty then
bg.strokeWidth = style.strokeWidth
self._strokeWidth_dirty=false
end
if self._textColor_dirty then
txt:setTextColor( unpack( style.textColor ) )
self._textColor_dirty=false
end
if self._textDimension_dirty then
self:dispatchEvent( self.EVENT, {width=self.width,height=self.height}, {merge=true} )
self._textDimension_dirty=false
end
end
--====================================================================--
--== Event Handlers
function Text:stylePropertyChangeHandler( event )
-- print( "Text:stylePropertyChangeHandler", event.type, event.property )
local style = event.target
local etype= event.type
local property= event.property
local value = event.value
-- print( "Style Changed", etype, property, value )
if etype==style.STYLE_RESET then
self._debugOn_dirty = true
self._width_dirty=true
self._height_dirty=true
self._anchorX_dirty=true
self._anchorY_dirty=true
self._align_dirty=true
self._fillColor_dirty = true
self._font_dirty=true
self._fontSize_dirty=true
self._marginX_dirty=true
self._marginY_dirty=true
self._strokeColor_dirty=true
self._strokeWidth_dirty=true
self._text_dirty=true
self._textColor_dirty=true
property = etype
else
if property=='debugActive' then
self._debugOn_dirty=true
elseif property=='width' then
self._width_dirty=true
elseif property=='height' then
self._height_dirty=true
elseif property=='anchorX' then
self._anchorX_dirty=true
elseif property=='anchorY' then
self._anchorY_dirty=true
elseif property=='align' then
self._align_dirty=true
elseif property=='fillColor' then
self._fillColor_dirty=true
elseif property=='font' then
self._font_dirty=true
elseif property=='fontSize' then
self._fontSize_dirty=true
elseif property=='marginX' then
self._marginX_dirty=true
elseif property=='marginY' then
self._marginY_dirty=true
elseif property=='strokeColor' then
self._strokeColor_dirty=true
elseif property=='strokeWidth' then
self._strokeWidth_dirty=true
elseif property=='text' then
self._text_dirty=true
elseif property=='textColor' then
self._textColor_dirty=true
end
end
self:__invalidateProperties__()
self:__dispatchInvalidateNotification__( property, value )
end
return Text
|
FLAG.PrintName = "Squad Leader";
FLAG.Flag = "C";
FLAG.Color = Color( 60, 20, 20, 255 );
FLAG.Loadout = { };
FLAG.ItemLoadout = { "radio", "zipties", "smallmedkit", "weapon_cc_medkit", "weapon_cc_stunstick", "weapon_cc_flare", "weapon_cc_pistol", "weapon_cc_smg", "weapon_cc_shotgun", "weapon_cc_doorbreach", "weapon_cc_beanbag", "weapon_cc_grenade", "weapon_cc_flashbang", "weapon_cc_manhack", "combineturret" };
FLAG.CharName = "CCA-C18.$SQUAD-SqL.$CID";
FLAG.CanJW = true;
FLAG.CanEditLoans = true;
FLAG.CanEditCPs = true;
function FLAG.ModelFunc( ply )
if( ply:Gender() == GENDER_FEMALE ) then
return "models/player/police_fem.mdl";
end
return "models/player/police.mdl";
end
|
game.reload_script()
for index, force in pairs(game.forces) do
local technologies = force.technologies;
local recipes = force.recipes;
force.reset_recipes()
force.reset_technologies()
end
|
FYAC_BWords = {}
FYAC_BWords.Words = {
-- 'haha',
-- 'lol',
-- 'xddd',
'chocolate',
'panickey',
'jolmany',
'killmenu'
}
|
local server = require "nvim-lsp-installer.server"
local path = require "nvim-lsp-installer.path"
local std = require "nvim-lsp-installer.installers.std"
local context = require "nvim-lsp-installer.installers.context"
local installers = require "nvim-lsp-installer.installers"
local process = require "nvim-lsp-installer.process"
return function(name, root_dir)
return server.Server:new {
name = name,
root_dir = root_dir,
homepage = "https://wiki.gnome.org/Projects/Vala",
languages = { "vala" },
installer = {
std.ensure_executables {
{ "meson", "meson was not found in path. Refer to https://mesonbuild.com/Getting-meson.html" },
{ "ninja", "ninja was not found in path. Refer to https://ninja-build.org/" },
{ "valac", "valac was not found in path. Refer to https://wiki.gnome.org/Projects/Vala" },
},
context.use_github_release_file("Prince781/vala-language-server", function(version)
return ("vala-language-server-%s.tar.xz"):format(version)
end),
context.capture(function(ctx)
return installers.pipe {
std.untarxz_remote(ctx.github_release_file),
std.rename(
("vala-language-server-%s"):format(ctx.requested_server_version),
"vala-language-server"
),
}
end),
function(_, callback, ctx)
local c = process.chain {
cwd = path.concat { ctx.install_dir, "vala-language-server" },
stdio_sink = ctx.stdio_sink,
}
c.run("meson", { ("-Dprefix=%s"):format(ctx.install_dir), "build" })
c.run("ninja", { "-C", "build", "install" })
c.spawn(callback)
end,
std.rmrf "vala-language-server",
context.receipt(function(receipt, ctx)
receipt:with_primary_source(receipt.github_release_file(ctx))
end),
},
default_options = {
cmd_env = {
PATH = process.extend_path { path.concat { root_dir, "bin" } },
},
},
}
end
|
local function CreditsText( pn )
local text = Def.ActorFrame{
InitCommand=function(self)
self:name("Credits" .. PlayerNumberToString(pn))
end;
UpdateVisibleCommand=function(self)
local screen = SCREENMAN:GetTopScreen();
local bShow = true;
if screen then
local sClass = screen:GetName();
bShow = THEME:GetMetric( sClass, "ShowCreditDisplay" );
end
self:visible( bShow );
end;
UpdateTextCommand=function(self)
local str = ScreenSystemLayerHelpers.GetCreditsMessage(pn);
end;
LoadActor("Test_Isla.png")..{
InitCommand=function(self)
self:name("Credits_Icon" .. PlayerNumberToString(pn))
self:maxwidth(50);
if pn == PLAYER_1 then
self:horizalign(left):vertalign(bottom)
self:x(SCREEN_LEFT):y(SCREEN_BOTTOM);
else
self:horizalign(right):vertalign(bottom)
self:x(SCREEN_RIGHT):y(SCREEN_BOTTOM);
end
end;
UpdateTextCommand=function(self)
local str = ScreenSystemLayerHelpers.GetCreditsMessage(pn);
self:visible(str ~= "PRESS START" and str ~= "NOT PRESENT" and str ~= "INSERT CARD" and str ~= "")
end;
}
LoadFont(Var "LoadingScreen","credits") .. {
InitCommand=function(self)
self:name("Credits_Text" .. PlayerNumberToString(pn))
end;
UpdateTextCommand=function(self)
local str = ScreenSystemLayerHelpers.GetCreditsMessage(pn);
self:settext(str);
if str ~= "PRESS START" and str ~= "NOT PRESENT" and str ~= "INSERT CARD" and str ~= "" then
if pn == PLAYER_1 then
self:x(SCREEN_LEFT+55):y(SCREEN_BOTTOM-16);
else
self:x(SCREEN_RIGHT-55):y(SCREEN_BOTTOM-16);
end
else
if pn == PLAYER_1 then
self:x(SCREEN_LEFT+15):y(SCREEN_BOTTOM-16);
else
self:x(SCREEN_RIGHT-15):y(SCREEN_BOTTOM-16);
end
end
end;
};
};
return text;
end;
--[[ local function PlayerPane( PlayerNumber )
local t = Def.ActorFrame {
InitCommand=function(self)
self:name("PlayerPane" .. PlayerNumberToString(PlayerNumber));
-- ActorUtil.LoadAllCommandsAndSetXY(self,Var "LoadingScreen");
end
};
t[#t+1] = Def.ActorFrame {
Name = "Background";
Def.Quad {
InitCommand=cmd(zoomto,160,28;queuecommand,"On");
OnCommand=cmd(diffuse,PlayerColor(PlayerNumber);fadebottom,1);
};
};
t[#t+1] = Def.BitmapText{
Font="Common Normal";
Name = "PlayerText";
InitCommand=cmd(x,-60;maxwidth,80/0.5;zoom,0.5;queuecommand,"On");
OnCommand=cmd(playcommand,"Set");
SetCommand=function(self)
local profile = PROFILEMAN:GetProfile( PlayerNumber) or PROFILEMAN:GetMachineProfile()
if profile then
self:settext( profile:GetDisplayName() );
else
self:settext( "NoProf" );
end
end;
};
return t
end --]]
--
local t = Def.ActorFrame {}
-- Aux
t[#t+1] = LoadActor(THEME:GetPathB("ScreenSystemLayer","aux"));
-- Credits
t[#t+1] = Def.ActorFrame {
--[[ PlayerPane( PLAYER_1 ) .. {
InitCommand=cmd(x,scale(0.125,0,1,SCREEN_LEFT,SCREEN_WIDTH);y,SCREEN_BOTTOM-16)
}; --]]
CreditsText( PLAYER_1 );
CreditsText( PLAYER_2 );
};
-- Text
t[#t+1] = Def.ActorFrame {
OnCommand=cmd(finishtweening;addx,10;decelerate,0.2;addx,-10;);
OffCommand=cmd(sleep,3;linear,0.5;addx,-10;sleep,0.01;addx,10;);
Def.Quad {
InitCommand=cmd(zoomtowidth,SCREEN_WIDTH;zoomtoheight,30;horizalign,left;vertalign,top;y,SCREEN_TOP;diffuse,color("0,0,0,0"));
OnCommand=cmd(finishtweening;decelerate,0.2;diffusealpha,0.85;);
OffCommand=cmd(sleep,3;linear,0.5;diffusealpha,0;);
};
Def.BitmapText{
Font="Common Normal";
Name="Text";
InitCommand=cmd(maxwidth,750;horizalign,left;vertalign,top;y,SCREEN_TOP+10;x,SCREEN_LEFT+10;shadowlength,1;diffusealpha,0;);
OnCommand=cmd(finishtweening;decelerate,0.2;diffusealpha,1;zoom,0.5);
OffCommand=cmd(sleep,3;linear,0.5;diffusealpha,0;);
};
SystemMessageMessageCommand = function(self, params)
self:GetChild("Text"):settext( params.Message );
self:playcommand( "On" );
if params.NoAnimate then
self:finishtweening();
end
self:playcommand( "Off" );
end;
HideSystemMessageMessageCommand = cmd(finishtweening);
};
return t;
|
if CLIENT then return end
include( 'shared.lua' )
AddCSLuaFile( 'cl_init.lua' )
util.AddNetworkString('bail_player_now')
local wait = wait or {}
local npcclass = 'npc_courier'
function ENT:Initialize()
self:InitVars()
self:DontDeleteOnRemove( self )
self.CanUse = true
self:SetModel( ARREST_NPC_MODEL )
self:SetHullType( HULL_HUMAN )
self:SetHullSizeNormal()
self:SetNPCState( NPC_STATE_SCRIPT )
self:SetSolid( SOLID_BBOX )
self:CapabilitiesAdd( CAP_ANIMATEDFACE + CAP_TURN_HEAD )
self:SetUseType( SIMPLE_USE )
self:DropToFloor()
self:SetSequence( 4 )
self:SetTrigger( true )
end
local cleanup = game.CleanUpMap
function game.CleanUpMap(send,flr)
if !flr then flr = {} end
if !table.HasValue(flr,npcclass) then
flr[#flr+1] = npcclass --after cleanup, insert npc in table
end
cleanup(send,flr)
end
function ENT:OnRemove()
end
function ENT:SpawnFunction( ply, tr, ClassName )
if ( !tr.Hit ) then return end
local SpawnPos = tr.HitPos + tr.HitNormal * 20
local ent = ents.Create( ClassName )
ent:SetPos( SpawnPos )
ent:Spawn()
ent:Activate()
return ent
end
function ENT:AcceptInput( name, ent, ply )
if( name == "Use" and IsValid( ply ) and ply:IsPlayer() and ply:Alive() )then
if( self.NextUse <= CurTime() )then
self.NextUse = CurTime() + self.CoolDown
net.Start( 'open_bail_menu' )
net.WriteEntity( self )
net.Send( ply )
end
end
end
net.Receive('bail_player_now', function(ln,pl)
local ent = net.ReadEntity()
if !table.HasValue(ARREST_BAILLIST, ent) then return end
if ent:getJailReason() == 'nil' then pl:ChatPrint(ent:Nick().." не арестован!") return '' end
if !pl:canAfford(ent:getBailPrice()) then pl:ChatPrint("Not enought money! Need "..ent:getBailPrice()..ARREST_MONEYPREFIX) return '' end
pl:addMoney(-ent:getBailPrice())
pl:ChatPrint("Ты внес залог за "..ent:Nick().." в размере "..ent:getBailPrice()..ARREST_MONEYPREFIX)
ent:ChatPrint(pl:Nick().." внес за Вас залог в размере "..ent:getBailPrice()..ARREST_MONEYPREFIX)
ent:unArrest(pl)
ent:setJailReason('nil')
table.RemoveByValue(ARREST_BAILLIST, ent)
net.Start('send_table')
net.WriteTable(ARREST_BAILLIST)
net.Broadcast()
end) |
antimage_spell_shield_lua = class({})
LinkLuaModifier( "modifier_antimage_spell_shield_lua", "lua_abilities/antimage_spell_shield_lua/modifier_antimage_spell_shield_lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
function antimage_spell_shield_lua:GetIntrinsicModifierName()
return "modifier_antimage_spell_shield_lua"
end
--------------------------------------------------------------------------------
|
if not pcall(require, "telescope") then
return
end
local sorters = require "telescope.sorters"
TelescopeMapArgs = TelescopeMapArgs or {}
local map_tele = function(mode, key, f, options, buffer)
local map_key = vim.api.nvim_replace_termcodes(key .. f, true, true, true)
TelescopeMapArgs[map_key] = options or {}
-- local mode = "n"
local rhs = string.format("<cmd>lua R('configs.telescope')['%s'](TelescopeMapArgs['%s'])<CR>", f, map_key)
local map_options = {
noremap = true,
silent = true,
}
if not buffer then
vim.api.nvim_set_keymap(mode, key, rhs, map_options)
else
vim.api.nvim_buf_set_keymap(0, mode, key, rhs, map_options)
end
end
-- -- Dotfiles
-- map_tele("n", "<Leader>en", "edit_neovim")
-- map_tele("n", "<Leader>ed", "edit_dotfiles")
-- Search
-- TODO: I would like to completely remove _mock from my search results here when I'm in SG/SG
-- map_tele("n", "<space>gw", "grep_string", {
-- short_path = true,
-- word_match = "-w",
-- only_sort_text = true,
-- layout_strategy = "vertical",
-- sorter = sorters.get_fzy_sorter(),
-- })
-- map_tele("n", "<localleader>f/", "grep_last_search", {
-- layout_strategy = "vertical",
-- })
-- Files
-- map_tele("n", "<space>ft", "git_files")
-- map_tele("n", "<Leader>gp", "grep_prompt")
map_tele("v", "<Leader>gg", "grep_prompt_visual")
-- map_tele("n", "<Leader>gq", "grep_quickfix")
-- map_tele("n", "<Leader>gg", "live_grep")
-- map_tele("n", "<Leader>G", "grep_prompt_regex_filetype")
-- map_tele("n", "<Leader>GG", "grep_prompt_regex_filetype_add_args")
map_tele("v", "<Leader>G", "grep_prompt_regex_filetype")
-- map_tele("n", "**", "find_word")
-- map_tele("n", "<Leader>fd", "find_files")
-- map_tele("n", "<Leader><leader>", "find_files")
-- map_tele("n", "<Leader>ft", "search_only_certain_files")
-- map_tele("n", "<space>fo", "oldfiles")
-- map_tele("n", "<space>fv", "find_nvim_source")
-- map_tele("n", "<leader>fe", "file_browser")
-- map_tele("n", "<leader>fr", 'registers')
-- map_tele("n", "<Leader>.", "symbol?")
-- map_tele("n", "<Leader>hh",'help_tags')
-- map_tele("n", "<Leader>hk",'keymaps')
-- map_tele("n", "<Leader>:",'commands')
--
map_tele("n", "<LocalLeader>.",'lsp_document_symbols')
map_tele("n", "<localleader>fl", 'loclist')
map_tele("n", "<localleader>g", 'curbuf')
map_tele("n", "<localleader>fi", "tbs_infrastructure_search")
map_tele("n", "<localleader>gi", "tbs_infrastructure_live_grep")
map_tele("v", "<localleader>gi", "tbs_infrastructure_grep_string")
map_tele("n", "<localleader>gip", "tbs_infrastructure_live_grep")
return map_tele
|
function dataRequest(host,service)
m.broadcast(host,service)
_,_,_,_,_,data = event.pull("modem_message")
m.send(client,response,data)
print(tostring(service))
return
end
|
--[[
Print the time in particular timeZone
Refs:
http://man7.org/linux/man-pages/man1/date.1.html
https://stackoverflow.com/questions/9676113/lua-os-execute-return-value
]]
local handle = io.popen("TZ='America/New_York' date")
local result = handle:read("*a")
print(result)
--[[ Prints complete date/time
Fri Apr 3 07:36:45 EDT 2020
]]
handle = io.popen("TZ=Canada/Pacific date +%B")
result = handle:read("*a")
print(result) -- Prints only Month
handle:close()
|
-- OptimisticSide
-- 5/9/2021
-- Command manager
local REVOKE_PREFIX = "un"
local Commands = {}
-- Find a command.
function Commands.findCommand(call)
-- Commands are not case-sensitive.
call = string.lower(call)
-- Handle reverse commands.
local procedure = "invoke"
if string.sub(call, 1, #REVOKE_PREFIX) == REVOKE_PREFIX then
procedure = "revoke"
end
for _, command in ipairs(Commands.cache) do
-- Check if command's name matches.
if string.lower(command.name) == call then
return command, procedure
end
-- Check command's aliases.
for _, aliase in ipairs(command.aliases or {}) do
if string.lower(aliase) == call then
return command, procedure
end
end
-- Check for special opposites.
for _, opposite in ipairs(command.opposites or {}) do
if string.lower(opposite) == call then
procedure = "revoke"
return command, procedure
end
end
end
end
return Commands
|
local String = require('string')
local Table = require('table')
--[[
local s = '/iframe-12.34234.html'
local params = {}
p(String.gsub(s, '/iframe(.*).html', function(prm)
if prm then Table.insert(params, prm) end
end))
p('gsub', s, params)
local s = '/iframe-12.34234.html'
p('match', String.match(s, '/iframe(.-)%.(.-)%.html'))
]]--
for cookie in String.gmatch(' ; JSESSIONID = foo', '[^;]+') do
local name, value = String.match(cookie, '%s*([^=%s]-)%s*=%s*([^%s]*)')
p(name, value)
end
|
--[[
pls give credit
and
dont name it the same thing
and
have fun
]]
|
ENT.Type = "anim"
ENT.Base = "cw_ammo_ent_base"
ENT.PrintName = ".44 Magnum Ammo"
ENT.Author = "Spy"
ENT.Spawnable = true
ENT.AdminSpawnable = true
ENT.Category = "CW 2.0 Ammo"
ENT.CaliberSpecific = true
ENT.AmmoCapacity = 30
ENT.ResupplyAmount = 6
ENT.Caliber = ".44 Magnum"
ENT.Model = "models/Items/BoxSRounds.mdl" |
local L = LibStub("AceLocale-3.0"):GetLocale("ClassicCodex")
local AceConfigRegistry = LibStub("AceConfigRegistry-3.0")
local AceConfigDialog = LibStub("AceConfigDialog-3.0")
local AceConfigCmd = LibStub("AceConfigCmd-3.0")
CodexConfig = {}
CodexColors = {}
DefaultCodexConfig = {
["trackingMethod"] = 1, -- 1: All Quests; 2: Tracked Quests; 3: Manual; 4: Hide
["autoAccept"] = false, -- Auto-accept quests
["autoTurnin"] = false, -- Auto-turnin quests
["nameplateIcon"] = false, -- Show quest icon above nameplates
["minimapButton"] = true, -- Show button of codex browser on the edge of the minimap
["continentIcon"] = false, -- Show quest markers on continent map (top two levels of the world map)
["zoneMapIcon"] = true, -- Show quest markers on zone map (the third and subsequent levels of the world map)
["miniMapIcon"] = true, -- Show quest markers on mini map
["allQuestGivers"] = true, -- Show available quest givers
["currentQuestGivers"] = true, -- Show current quest giver nodes
["alwaysShowId"] = false, -- Display unit/object/item/quest id in non-id search results
["showLowLevel"] = false, -- Show low level quest giver nodes
["showHighLevel"] = true, -- Show level+3 quest giver nodes
["showFestival"] = false, -- Show event quest giver nodes
["colorBySpawn"] = true,
["questMarkerSize"] = 15,
["spawnMarkerSize"] = 15,
["bossMarkerSize"] = 25, -- Display a larger icon for the boss or a single target to help you find it.
["minimumDropChance"] = 2, -- (%) Hide markers with a drop probability less than this value
["showTrackingMethodDropdown"] = true, -- Show Tracking Method Dropdown on the World Map
["showUnitTooltip"] = true, -- Show quest name in mouseover tooltip of units
}
CodexConfigFrame = CreateFrame("Frame", "CodexConfigFrame", UIParent)
function CodexConfigFrame:LoadConfig()
if not CodexConfig then CodexConfig = {} end
for key, val in pairs(DefaultCodexConfig) do
if CodexConfig[key] == nil then
if key == "colorList" then
CodexConfig[key] = {unpack(val)}
else
CodexConfig[key] = val
end
end
end
self:UpdateMinimapButton()
self.configTable = {
type = "group",
name = "ClassicCodex",
args = {
---------------------------------------- column 1 ----------------------------------------
autoAccept = {
order = 101, -- row: 1, column: 1
type = "toggle",
width = 1.5, -- make two checkboxes on the same line
name = L["Auto-Accept Quests"],
desc = L["Toggle auto-accepting quests"],
get = function(info)
return CodexConfig.autoAccept
end,
set = function(info, val)
CodexConfig.autoAccept = val
end
},
autoTurnin = {
order = 201, -- row: 2, column: 1
type = "toggle",
width = 1.5, -- make two checkboxes on the same line
name = L["Auto-Turnin Quests"],
desc = L["Toggle auto-turning in quests"],
get = function(info)
return CodexConfig.autoTurnin
end,
set = function(info, val)
CodexConfig.autoTurnin = val
end
},
nameplateIcon = {
order = 301,
type = "toggle",
width = 1.5,
name = L["Nameplate Quest Icon"],
desc = L["Toggle quest icon on top of enemy nameplates"],
get = function(info)
return CodexConfig.nameplateIcon
end,
set = function(info, val)
CodexConfig.nameplateIcon = val
CodexQuest:UpdateAllNameplates()
end
},
allQuestGivers = {
order = 401,
type = "toggle",
width = 1.5,
name = L["All Questgivers"],
desc = L["If selected, this will display all questgivers on the map"],
get = function(info)
return CodexConfig.allQuestGivers
end,
set = function(info, val)
CodexConfig.allQuestGivers = val
CodexQuest:ResetAll()
end
},
currentQuestGivers = {
order = 501,
type = "toggle",
width = 1.5,
name = L["Current Questgivers"],
desc = L["If selected, current quest-ender npcs/objects will be displayed on the map for active quests"],
get = function(info)
return CodexConfig.currentQuestGivers
end,
set = function(info, val)
CodexConfig.currentQuestGivers = val
CodexQuest:ResetAll()
end
},
showLowLevel = {
order = 601,
type = "toggle",
width = 1.5,
name = L["Show Low-level Quests"],
desc = L["If selected, low-level quests will be hidden on the map"],
get = function(info)
return CodexConfig.showLowLevel
end,
set = function(info, val)
CodexConfig.showLowLevel = val
CodexQuest:ResetAll()
end
},
showHighLevel = {
order = 701,
type = "toggle",
width = 1.5,
name = L["Show High-level Quests"],
desc = L["If selected, quests with a level requirement of your level + 3 will be shown on the map"],
get = function(info)
return CodexConfig.showHighLevel
end,
set = function(info, val)
CodexConfig.showHighLevel = val
CodexQuest:ResetAll()
end
},
showFestival = {
order = 801,
type = "toggle",
width = 1.5,
name = L["Show Festival/PVP/Misc Quests"],
desc = L["If selected, quests related to WoW festive seasons or PVP or not available at the current stage will be displayed on the map"],
get = function(info)
return CodexConfig.showFestival
end,
set = function(info, val)
CodexConfig.showFestival = val
CodexQuest:ResetAll()
end
},
colorBySpawn = {
order = 901,
type = "toggle",
width = 3, -- make the next checkbox in a new line
name = L["Color By Spawn"],
desc = L["If selected, markers' colors will be set per spawn type or per quest if not selected"],
get = function(info)
return CodexConfig.colorBySpawn
end,
set = function(info, val)
CodexConfig.colorBySpawn = val
CodexQuest:ResetAll()
end
},
---------------------------------------- column 2 ----------------------------------------
alwaysShowId = {
order = 102, -- row: 1, column: 2
type = "toggle",
width = 1.5, -- make two checkboxes on the same line
name = L["Show ID in Codex Browser"],
desc = L["If selected, the item/object/unit/quest ID will be displayed when you searching something in Codex browser."],
get = function(info)
return CodexConfig.alwaysShowId
end,
set = function(info, val)
CodexConfig.alwaysShowId = val
CodexBrowser.input:Search()
end
},
minimapButton = {
order = 202, -- row: 2, column: 2
type = "toggle",
width = 1.5, -- make two checkboxes on the same line
name = L["Show Minimap Button"],
desc = L["Show a button on the edge of the minimap, click to open Codex browser"],
get = function(info)
return CodexConfig.minimapButton
end,
set = function(info, val)
CodexConfig.minimapButton = val
CodexConfigFrame:UpdateMinimapButton()
end
},
continentIcon = {
order = 302,
type = "toggle",
width = 1.5,
name = L["Show Markers on Continent Maps"],
desc = L["Show markers on the top two levels of the world map"],
get = function(info)
return CodexConfig.continentIcon
end,
set = function(info, val)
CodexConfig.continentIcon = val
if CodexConfig.continentIcon and not CodexConfig.zoneMapIcon then
CodexConfig.zoneMapIcon = true
end
CodexMap:UpdateNodes()
end
},
zoneMapIcon = {
order = 402,
type = "toggle",
width = 1.5,
name = L["Show Markers on Zone Maps"],
desc = L["Show markers on the third and subsequent levels of the world map"],
get = function(info)
return CodexConfig.zoneMapIcon
end,
set = function(info, val)
CodexConfig.zoneMapIcon = val
if not CodexConfig.zoneMapIcon and CodexConfig.continentIcon then
CodexConfig.continentIcon = false
end
CodexMap:UpdateNodes()
end
},
miniMapIcon = {
order = 502,
type = "toggle",
width = 1.5,
name = L["Show Markers on the Minimap"],
get = function(info)
return CodexConfig.miniMapIcon
end,
set = function(info, val)
CodexConfig.miniMapIcon = val
CodexMap:UpdateNodes()
end
},
showUnitTooltip = {
order = 602,
type = "toggle",
width = 1.5,
name = L["Show Quest Name in Unit Tooltip"],
desc = L["Show quest name in mouseover tooltip of units"],
get = function(info)
return CodexConfig.showUnitTooltip
end,
set = function(info, val)
CodexConfig.showUnitTooltip = val
end
},
showTrackingMethodDropdown = {
order = 702,
type = "toggle",
width = 1.5,
name = L["Show Tracking Method Dropdown on the World Map"],
get = function(info)
return CodexConfig.showTrackingMethodDropdown
end,
set = function(info, val)
CodexConfig.showTrackingMethodDropdown = val
if CodexConfig.showTrackingMethodDropdown then
CodexQuest.mapButton:Show()
else
CodexQuest.mapButton:Hide()
end
end
},
trackingMethod = {
order = 802,
type = "select",
width = 1.5,
name = L["Quest Tracking Method"],
values = {
L["All Quests"],
L["Tracked Quests"],
L["Manual Selection"],
L["Hide Quests"],
},
get = function(info)
return CodexConfig.trackingMethod
end,
set = function(info, val)
CodexConfig.trackingMethod = val
CodexQuest:ResetAll()
end
},
---------------------------------------- sliders ----------------------------------------
questMarkerSize = {
order = 1001,
type = "range",
width = 1,
name = L["Quest Marker Size"],
min = 0,
max = 300,
step = 1,
softMin = 10,
softMax = 50,
bigStep = 1,
get = function(info)
return CodexConfig.questMarkerSize
end,
set = function(info, val)
CodexConfig.questMarkerSize = tonumber(val)
CodexMap:UpdateNodes()
end
},
spawnMarkerSize = {
order = 1002,
type = "range",
width = 1,
name = L["Spawn Marker Size"],
min = 0,
max = 300,
step = 1,
softMin = 10,
softMax = 50,
bigStep = 1,
get = function(info)
return CodexConfig.spawnMarkerSize
end,
set = function(info, val)
CodexConfig.spawnMarkerSize = tonumber(val)
CodexMap:UpdateNodes()
end
},
bossMarkerSize = {
order = 1003,
type = "range",
width = 1,
name = L["Boss Marker Size"],
desc = L["Display a larger icon for the boss or a single target to help you find it"],
min = 0,
max = 300,
step = 1,
softMin = 10,
softMax = 50,
bigStep = 1,
get = function(info)
return CodexConfig.bossMarkerSize
end,
set = function(info, val)
CodexConfig.bossMarkerSize = tonumber(val)
CodexMap:UpdateNodes()
end
},
minimumDropChance = {
order = 1101,
type = "range",
width = 3,
name = L["Hide items with a drop probability less than (%)"],
min = 0,
max = 100,
step = 1,
get = function(info)
return CodexConfig.minimumDropChance
end,
set = function(info, val)
CodexConfig.minimumDropChance = tonumber(val)
CodexQuest:ResetAll()
end
},
---------------------------------------- buttons ----------------------------------------
listHiddenQuests = {
order = 1201,
type = "execute",
width = 1.5,
name = L["List Manually Hidden Quests"],
func = function(info)
if CodexBrowser then
CodexBrowser.input:SetText('!')
CodexBrowser:OpenView('quests')
end
end,
},
listCompletedQuests = {
order = 1202,
type = "execute",
width = 1.5,
name = L["List Completed Quests"],
func = function(info)
if CodexBrowser then
CodexBrowser.input:SetText('@')
CodexBrowser:OpenView('quests')
end
end,
},
showAllHiddenQuests = {
order = 1301,
type = "execute",
width = 1.5,
name = L["Show All Quests You Manually Hide Again"],
desc = L["Show all the quests you have hidden by shift + click."].."\n"..
L["Hide a quest by holding the shift key and clicking on the quest icon on the minimap or world map."],
func = function(info)
local size = Codex:tablelen(CodexHiddenQuests)
CodexHiddenQuests = {}
CodexQuest:ResetAll()
if size < 1 then
print(L["ClassicCodex: You have no manually hidden quests. You can hold the shift key and click on the quest icon on the minimap or world map to hide it."])
else
print(string.format(L["ClassicCodex: %d hidden quests will be able to show again."], size))
end
end,
},
openCodexBrowser = {
order = 1302,
type = "execute",
width = 1.5,
name = L["Open Codex Browser"],
func = function(info)
if CodexBrowser then
CodexBrowser:Show()
end
end,
},
},
}
self.registeredOptionsTable = AceConfigRegistry:RegisterOptionsTable("ClassicCodex", self.configTable)
self.blizOptions = AceConfigDialog:AddToBlizOptions("ClassicCodex", "ClassicCodex")
self.cmdOptions = AceConfigCmd:CreateChatCommand("codexcfg", "ClassicCodex")
end
function CodexConfigFrame:UpdateMinimapButton()
if not CodexBrowserIcon then return end
if CodexConfig.minimapButton then
CodexBrowserIcon:Show()
else
CodexBrowserIcon:Hide()
end
end
CodexConfigFrame:RegisterEvent("ADDON_LOADED")
CodexConfigFrame:SetScript("OnEvent", function(self, event, arg1)
if event == "ADDON_LOADED" and arg1 == "ClassicCodex" then
self:LoadConfig()
CodexConfigFrame:UnregisterEvent("ADDON_LOADED")
end
end)
|
local timestamp = require "kong.tools.timestamp"
describe("Timestamp", function()
local table_size = function(t)
local s = 0
for _ in pairs(t) do s = s + 1 end
return s
end
it("should get UTC time", function()
assert.truthy(timestamp.get_utc())
assert.are.same(13, string.len(tostring(timestamp.get_utc())))
end)
it("should get timestamps table when no timestamp is provided", function()
local timestamps = timestamp.get_timestamps()
assert.truthy(timestamps)
assert.are.same(6, table_size(timestamps))
assert.truthy(timestamps.second)
assert.truthy(timestamps.minute)
assert.truthy(timestamps.hour)
assert.truthy(timestamps.day)
assert.truthy(timestamps.month)
assert.truthy(timestamps.year)
end)
it("should get timestamps table when no timestamp is provided", function()
local timestamps = timestamp.get_timestamps(timestamp.get_utc())
assert.truthy(timestamps)
assert.are.same(6, table_size(timestamps))
assert.truthy(timestamps.second)
assert.truthy(timestamps.minute)
assert.truthy(timestamps.hour)
assert.truthy(timestamps.day)
assert.truthy(timestamps.month)
assert.truthy(timestamps.year)
end)
it("should give the same timestamps table for the same time", function()
-- Wait til the beginning of a new second before starting the test
-- to avoid ending up in an edge case when the second is about to end
local now = os.time()
while os.time() < now + 1 do
-- Nothing
end
local timestamps_one = timestamp.get_timestamps()
local timestamps_two = timestamp.get_timestamps(timestamp.get_utc())
assert.truthy(timestamps_one)
assert.truthy(timestamps_two)
assert.are.same(6, table_size(timestamps_one))
assert.are.same(6, table_size(timestamps_two))
assert.are.same(timestamps_one, timestamps_two)
end)
end)
|
require "nn"
mlp = nn.ParallelTable()
mlp:add(nn.Linear(10, 2))
mlp:add(nn.Linear(5, 3))
x = torch.randn(10)
y = torch.rand(5)
pred = mlp:forward{x, y}
-- pred = mlp:forward(x, y) error
for i, k in pairs(pred) do print(i, k) end
|
--
-- Created by IntelliJ IDEA.
-- User: romansztergbaum
-- Date: 06/08/2018
-- Time: 22:07
-- To change this template use File | Settings | File Templates.
--
local entities = {}
function update()
if (shiva.is_key_pressed(Keyboard.Z) == true) then
print("Z pressed")
end
end
function on_key_pressed(evt)
if (evt.keycode == Keyboard.Escape) then
print("should quit_game")
shiva.dispatcher:trigger_quit_game_event(1)
elseif (evt.keycode == Keyboard.Left) then
shiva.dispatcher:trigger_change_scene_event("game_scene")
end
end
function on_key_released(evt)
end
function leave()
print("leave sprite scene")
for key, value in pairs(entities) do
shiva.entity_registry:destroy(value)
entities[key] = nil
end
shiva.resource_registry:unload_all_resources("sprite_scene")
print("leaving sprite scene, nb entities: " .. shiva.entity_registry:nb_entities())
end
function on_after_load_resources(evt)
local id = shiva.entity_registry:create_game_object_with_sprite("sprite_scene/toto", 250, 250)
entities[#entities + 1] = id
shiva.entity_registry:add_layer_1_component(id)
local other_id = shiva.entity_registry:create_text("Hello from sprite_scene", "sprite_scene/kenney_future", 24)
shiva.entity_registry:add_layer_1_component(other_id)
entities[#entities + 1] = other_id
print("after_loading_resources sprite scene, nb entities: " .. shiva.entity_registry:nb_entities())
end
function enter()
print("enter sprite scene")
shiva.resource_registry:load_all_resources("sprite_scene")
end
return {
on_key_released = on_key_released,
on_key_pressed = on_key_pressed,
on_after_load_resources = on_after_load_resources,
leave = leave,
enter = enter,
update = update,
scene_active = false
}
|
--14.file
a = 3
for n in pairs(_G) do print(n) end
|
--[[
Phantom Forces Cheat
- Herrtt
Supports
* No Fall Damage
* WalkSpeed
* JumpPower
* SilentAim
* Headshot Percentage
* Wallhacks
]]
-- Default launch settings
local settings = {
silentaim = true,
nofalldamage = false,
setwalkspeed = false,
walkspeed = 55,
setjumppower = false,
jumppower = 45,
headshotchanceenabled = true,
headshotchance = 25,
--
gunVisuals = true,
deadVisuals = true,
colorEffect = true,
--
fov = 350,
fovcircle = true,
fovsides = 12,
fovthickness = 1
}
local main = {running = true}
local end_funcs = {}
local __SETTINGS__ = {}
function main:End()
main.running = false
for _,func in pairs(end_funcs) do
func()
end
if (main == shared.__main) then
shared.__main = nil -- k
end
main = nil
spawn(function()
for i,v in pairs(connections) do
pcall(function() v:Disconnect() end)
end
end)
shared.main = nil -- k
__SETTINGS__:Save()
end
if shared.__main then
pcall(shared.__main.End, shared.__main)
shared.__main = nil
end
shared.__main = main
local connections = {}
local function bindEvent(event, callback) -- Let me disconnect in peace
local con = event:Connect(callback)
table.insert(connections, con)
return con
end
table.insert(end_funcs, function()
for i,v in pairs(connections) do
v:Disconnect()
connections[i] = nil
end
end)
local servs
servs = setmetatable(
{
Get = function(self, serv)
if servs[serv] then return servs[serv] end
local s = game:GetService(serv)
if s then servs[serv] = s end
return s
end;
}, {
__index = function(self, index)
local s = game:GetService(index)
if s then servs[index] = s end
return s
end;
})
local players = servs.Players
local runservice = servs.RunService
local http = servs.HttpService
local uis = servs.UserInputService
local function jsonEncode(t)
return http:JSONEncode(t)
end
local function jsonDecode(t)
return http:JSONDecode(t)
end
local function existsFile(name)
return pcall(function()
return readfile(name)
end)
end
local function mergetab(a,b)
local c = a or {}
for i,v in pairs(b or {}) do
c[i] = v
end
return c
end
local serialize
local deserialize
do
--/ Serializer : garbage : slow as fuck
local function hex_encode(IN, len)
local B,K,OUT,I,D=16,"0123456789ABCDEF","",0,nil
while IN>0 do
I=I+1
IN,D=math.floor(IN/B), IN%B+1
OUT=string.sub(K,D,D)..OUT
end
if len then
OUT = ('0'):rep(len - #OUT) .. OUT
end
return OUT
end
local function hex_decode(IN)
return tonumber(IN, 16)
end
local types = {
["nil"] = "0";
["boolean"] = "1";
["number"] = "2";
["string"] = "3";
["table"] = "4";
["Vector3"] = "5";
["CFrame"] = "6";
["Instance"] = "7";
["Color3"] = "8";
}
local rtypes = (function()
local a = {}
for i,v in pairs(types) do
a[v] = i
end
return a
end)()
local typeof = typeof or type
local function encode(t, ...)
local type = typeof(t)
local s = types[type]
local c = ''
if type == "nil" then
c = types[type] .. "0"
elseif type == "boolean" then
local t = t == true and '1' or '0'
c = s .. t
elseif type == "number" then
local new = tostring(t)
local len = #new
c = s .. len .. "." .. new
elseif type == "string" then
local new = t
local len = #new
c = s .. len .. "." .. new
elseif type == "Vector3" then
local x,y,z = tostring(t.X), tostring(t.Y), tostring(t.Z)
local new = hex_encode(#x, 2) .. x .. hex_encode(#y, 2) .. y .. hex_encode(#z, 2) .. z
c = s .. new
elseif type == "CFrame" then
local a = {t:GetComponents()}
local new = ''
for i,v in pairs(a) do
local l = tostring(v)
new = new .. hex_encode(#l, 2) .. l
end
c = s .. new
elseif type == "Color3" then
local a = {t.R, t.G, t.B}
local new = ''
for i,v in pairs(a) do
local l = tostring(v)
new = new .. hex_encode(#l, 2) .. l
end
c = s .. new
elseif type == "table" then
return serialize(t, ...)
end
return c
end
local function decode(t, extra)
local p = 0
local function read(l)
l = l or 1
p = p + l
return t:sub(p-l + 1, p)
end
local function get(a)
local k = ""
while p < #t do
if t:sub(p+1,p+1) == a then
break
else
k = k .. read()
end
end
return k
end
local type = rtypes[read()]
local c
if type == "nil" then
read()
elseif type == "boolean" then
local d = read()
c = d == "1" and true or false
elseif type == "number" then
local length = tonumber(get("."))
local d = read(length+1):sub(2,-1)
c = tonumber(d)
elseif type == "string" then
local length = tonumber(get(".")) --read()
local d = read(length+1):sub(2,-1)
c = d
elseif type == "Vector3" then
local function getnext()
local length = hex_decode(read(2))
local a = read(tonumber(length))
return tonumber(a)
end
local x,y,z = getnext(),getnext(),getnext()
c = Vector3.new(x, y, z)
elseif type == "CFrame" then
local a = {}
for i = 1,12 do
local l = hex_decode(read(2))
local b = read(tonumber(l))
a[i] = tonumber(b)
end
c = CFrame.new(unpack(a))
elseif type == "Instance" then
local pos = hex_decode(read(2))
c = extra[tonumber(pos)]
elseif type == "Color3" then
local a = {}
for i = 1,3 do
local l = hex_decode(read(2))
local b = read(tonumber(l))
a[i] = tonumber(b)
end
c = Color3.new(unpack(a))
end
return c
end
function serialize(data, p)
if data == nil then return end
local type = typeof(data)
if type == "table" then
local extra = {}
local s = types[type]
local new = ""
local p = p or 0
for i,v in pairs(data) do
local i1,camera
local t0,t1 = typeof(i), typeof(v)
local a,b
if t0 == "Instance" then
p = p + 1
extra[p] = i
i1 = types[t0] .. hex_encode(p, 2)
else
i1, a = encode(i, p)
if a then
for i,v in pairs(a) do
extra[i] = v
end
end
end
if t1 == "Instance" then
p = p + 1
extra[p] = v
camera = types[t1] .. hex_encode(p, 2)
else
camera, b = encode(v, p)
if b then
for i,v in pairs(b) do
extra[i] = v
end
end
end
new = new .. i1 .. camera
end
return s .. #new .. "." .. new, extra
elseif type == "Instance" then
return types[type] .. hex_encode(1, 2), {data}
else
return encode(data), {}
end
end
function deserialize(data, extra)
if data == nil then return end
extra = extra or {}
local type = rtypes[data:sub(1,1)]
if type == "table" then
local p = 0
local function read(l)
l = l or 1
p = p + l
return data:sub(p-l + 1, p)
end
local function get(a)
local k = ""
while p < #data do
if data:sub(p+1,p+1) == a then
break
else
k = k .. read()
end
end
return k
end
local length = tonumber(get("."):sub(2, -1))
read()
local new = {}
local l = 0
while p <= length do
l = l + 1
local function getnext()
local i
local t = read()
local type = rtypes[t]
if type == "nil" then
i = decode(t .. read())
elseif type == "boolean" then
i = decode(t .. read())
elseif type == "number" then
local l = get(".")
local dc = t .. l .. read()
local a = read(tonumber(l))
dc = dc .. a
i = decode(dc)
elseif type == "string" then
local l = get(".")
local dc = t .. l .. read()
local a = read(tonumber(l))
dc = dc .. a
i = decode(dc)
elseif type == "Vector3" then
local function getnext()
local length = hex_decode(read(2))
local a = read(tonumber(length))
return tonumber(a)
end
local x,y,z = getnext(),getnext(),getnext()
i = Vector3.new(x, y, z)
elseif type == "CFrame" then
local a = {}
for i = 1,12 do
local l = hex_decode(read(2))
local b = read(tonumber(l)) -- why did I decide to do this
a[i] = tonumber(b)
end
i = CFrame.new(unpack(a))
elseif type == "Instance" then
local pos = hex_decode(read(2))
i = extra[tonumber(pos)]
elseif type == "Color3" then
local a = {}
for i = 1,3 do
local l = hex_decode(read(2))
local b = read(tonumber(l))
a[i] = tonumber(b)
end
i = Color3.new(unpack(a))
elseif type == "table" then
local l = get(".")
local dc = t .. l .. read() .. read(tonumber(l))
i = deserialize(dc, extra)
end
return i
end
local i = getnext()
local v = getnext()
new[(typeof(i) ~= "nil" and i or l)] = v
end
return new
elseif type == "Instance" then
local pos = tonumber(hex_decode(data:sub(2,3)))
return extra[pos]
else
return decode(data, extra)
end
end
end
local utility do
-- shit
utility = {}
local servs
servs = setmetatable({}, {
__index = function(self, index)
local s = game:GetService(index)
if s then servs[index] = s end
return s
end;
})
local game, workspace = game, workspace
local v2 = Vector2
local math, table = math, table
local v2new = v2.new
local players = servs.Players
local locpl = players.LocalPlayer
local mouse = locpl:GetMouse()
local currentcamera = workspace.CurrentCamera
local findFirstChildOfClass = game.FindFirstChildOfClass
local isDescendantOf = game.IsDescendantOf
local getPlayers = players.GetPlayers
local getPartsObscuringTarget = currentcamera.GetPartsObscuringTarget
local worldToViewportPoint = currentcamera.WorldToViewportPoint
local raynew = Ray.new
local findPartOnRayWithIgnoreList = workspace.FindPartOnRayWithIgnoreList
local findFirstChild = game.FindFirstChild
local function raycast(ray, ignore, callback)
local ignore = ignore or {}
local hit, pos, normal, material = findPartOnRayWithIgnoreList(workspace, ray, ignore)
while hit and callback do
local Continue, _ignore = callback(hit)
if not Continue then
break
end
if _ignore then
table.insert(ignore, _ignore)
else
table.insert(ignore, hit)
end
hit, pos, normal, material = findPartOnRayWithIgnoreList(workspace, ray, ignore)
end
return hit, pos, normal, material
end
local function badraycastnotevensure(pos, ignore) -- 1 ray > 1 obscuringthing | 100 rays < 1 obscuring thing
local hitparts = getPartsObscuringTarget(currentcamera, {pos}, ignore or {})
return hitparts
end
local charshit = {}
function utility.getcharacter(player) -- Change this or something if you want to add support for other games.
if (player == nil) then return end
if (charshit[player]) then return charshit[player] end
local char = player.Character
if (char == nil or isDescendantOf(char, game) == false) then
char = findFirstChild(workspace, player.Name)
end
return char
end
utility.mychar = nil
utility.myroot = nil
local rootshit = {}
function utility.getroot(player)
if (player == nil) then return end
if (rootshit[player]) then return rootshit[player] end
local char
if (player:IsA("Player")) then
char = utility.getcharacter(player)
else
char = player
end
if (char ~= nil) then
return (findFirstChild(char, "Torso") or char.PrimaryPart)
end
return
end
function utility.isalive(_1, _2)
if _1 == nil then return end
local Char, RootPart
if _2 ~= nil then
Char, RootPart = _1,_2
else
Char = utility.getcharacter(_1)
RootPart = Char and (Char:FindFirstChild("Torso") or Char.PrimaryPart)
end
if Char and RootPart then
local Human = findFirstChildOfClass(Char, "Humanoid")
if RootPart and Human then
if Human.Health > 0 then
return true
end
elseif RootPart and isDescendantOf(Char, game) then
return true
end
end
return false
end
local shit = false
function utility.isvisible(char, root, max, ...)
local pos = root.Position
if shit or max > 4 then
local parts = badraycastnotevensure(pos, {utility.mychar, ..., workspace.CurrentCamera, char, root, workspace:FindFirstChild("Ignore"), })
return parts <= max
else
local camp = currentcamera.CFrame.p
local dist = (camp - pos).Magnitude
local hitt = 0
local hit = raycast(raynew(camp, (pos - camp).unit * dist), {utility.mychar, ..., currentcamera}, function(hit)
if hit.Name == "Window" then
return true
end
if hit.CanCollide == true then-- hit.Transparency ~= 1 then
hitt = hitt + 1
return hitt < max
end
if isDescendantOf(hit, char) then
return
end
return true
end)
return hit == nil or isDescendantOf(hit, char) or hitt <= max, hitt
end
end
function utility.sameteam(player, p1)
local p0 = p1 or locpl
return (player.Team~=nil and player.Team==p0.Team) and player.Neutral == false or false
end
function utility.getDistanceFromMouse(position)
local screenpos, vis = worldToViewportPoint(currentcamera, position)
if vis and screenpos.Z > 0 then
return (v2new(mouse.X, mouse.Y) - v2new(screenpos.X, screenpos.Y)).Magnitude
end
return math.huge
end
function utility.getClosestMouseTarget(settings)
local closest, temp = nil, settings.fov or math.huge
local plr
local mychar = utility.getcharacter(locpl)
utility.mychar = mychar
local myroot = utility.getroot(mychar)
utility.myroot = myroot
for i,v in pairs(getPlayers(players)) do
if (locpl ~= v and (settings.ignoreteam==true and utility.sameteam(v)==false or settings.ignoreteam == false)) then
local character = utility.getcharacter(v)
if character then
local part = findFirstChild(character, settings.name or "Torso") or findFirstChild(character, "Torso") or character.PrimaryPart
if part and part:IsA("BasePart") then
local legal = true
local distance = utility.getDistanceFromMouse(part.CFrame.Position)
if temp <= distance then
legal = false
end
if legal and settings.checkifalive then
local isalive = utility.isalive(character, part)
if not isalive then
legal = false
end
end
if legal and settings.ignorewalls == false then
if not utility.isvisible(character, part, (settings.maxobscuringparts or 0)) then
legal = false
end
end
if legal and myroot and settings.maxdist then
if settings.maxdist < (myroot.Position - part.Position).Magnitude then
legal = false
end
end
if legal then
temp = distance
closest = part
plr = v
end
end
end
end
end -- who doesnt love 5 ends in a row?
return closest, temp, plr
end
end
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer
local RunService = game:GetService("RunService")
local function assert(a, b, ...)
if not a then
print(...)
return error(b)
end
end
local function kick(...)
LocalPlayer:Kick(...)
end
local function findFirstChild(parent,child,callback)
if parent ~= nil and callback ~= nil then
local obj = parent:FindFirstChild(tostring(child))
if obj ~= nil then
callback(obj)
end
end
end
local function map(a, f)
local b = {}
for i,v in pairs(a) do
local i2,v2 = f(i,v)
if typeof(i2) ~= nil then
b[i2] = v2
end
end
return b
end
local function findLocal(lookinfor)
local found = {}
for i,v in pairs(lookinfor.gc and getgc() or getreg()) do
if typeof(v) == "function" and islclosure(v) then
local upvals = debug.getupvalues(v)
for i2,v2 in pairs(upvals) do
if typeof(v2) == "table" then
local Correct = true
if typeof(lookinfor) == "table" then
if lookinfor.env ~= nil then
local env = getfenv(v)
for i3,v3 in pairs(lookinfor.env) do
if typeof(v3) == "string" then
if tostring(rawget(env, i3)) ~= v3 then
Correct = false
break
end
end
end
end
if Correct then
if #lookinfor == 0 and lookinfor.env == nil then
Correct = false
end
for i3,v3 in pairs(lookinfor) do
if typeof(i3) == "number" then
if rawget(v2, v3) == nil then
Correct = false
break
end
end
end
end
else
if rawget(v2, lookinfor) == nil then
Correct = false
end
end
if Correct then
if lookinfor.remove then
debug.setupvalue(v, i2, nil)
end
if lookinfor.replace then
debug.setupvalue(v, i2, lookinfor.replace)
end
table.insert(found, v2)
end
elseif typeof(v2) == "function" and islclosure(v2) then
local Correct = true
if lookinfor.constants ~= nil then
local consts = debug.getconstants(v2)
consts = map(consts, function(a,b) return b,true end)
for i3,v3 in pairs(lookinfor.constants) do
if typeof(i3) == "number" then
if not consts[v3] then
Correct = false
break
end
end
end
if Correct then
if lookinfor.remove then
debug.setupvalue(v, i2, nil)
end
if lookinfor.replace then
debug.setupvalue(v, i2, lookinfor.replace)
end
table.insert(found, v2)
end
end
end
end
end
end
return found
end
-- just so I can re-execute multiple times
local storage = shared.gamer_storage or {}
shared.gamer_storage = storage -- fuck off
storage.misc = storage.misc or {}
-- yup
local network = storage.misc.network or findLocal({
"fetch",
"send",
"ready",
"servertick"
})[1]
assert(network, kick, "Failed to find network module")
storage.misc.network = network
-- character handler
local char = storage.misc.char or findLocal({
"setsprint",
"setbasewalkspeed",
"getstate",
env = {
script = "Framework"
}
})[1]
assert(char, kick, "Failed to find char module")
storage.misc.char = char
local hudModule = storage.misc.hud or findLocal({
"firehitmarker"
})[1]
assert(hudModule, kick, "Failed to find hud module")
storage.misc.hud = hudModule
local effects = storage.misc.effects or findLocal({
"bloodhit",
"breakwindow",
gc = true,
})[1]
assert(effects, kick, "Failed to find effects module")
storage.misc.effects = effects
local sound = storage.misc.sound or findLocal({
"PlaySound",
"PlaySoundId",
gc = true,
})[1]
assert(sound, kick, "Failed to find sound module")
storage.misc.sound = sound
local gamelogic = storage.misc.gamelogic or findLocal({
"gammo",
"setsprintdisable",
"controllerstep",
gc = true,
})[1]
assert(gamelogic, kick, "Failed to find gamelogic module")
storage.misc.gamelogic = gamelogic
local particle = storage.misc.particle or findLocal({
"new",
"reset",
"step",
gc = true,
env = {
script = "Framework"
}
})[1]
assert(particle, kick, "Failed to find particle module")
storage.misc.particle = particle
local beamobject = storage.misc.beamobject or debug.getupvalue(particle.new, 1)
assert(beamobject, kick, "Failed to find beamobject module")
assert(beamobject.Destroy and beamobject.new and beamobject.step, kick, "Failed to find beamobject module")
local camera = storage.misc.camera or findLocal({
"setfixedcam",
"setmenucam",
"setmenucf",
gc = true,
env = {
script = "Framework"
}
})[1]
assert(camera, kick, "Failed to find camera module")
storage.misc.camera = camera
do -- Character shit, pf renames characters so yeah umh
local replication = storage.misc.replication or findLocal({
"removecharacterhash",
"getplayerhit",
"thickcastplayers",
env = {
script = "Framework"
}
})[1]
assert(replication, kick, "Failed to find replication module")
storage.misc.replication = replication
utility.getcharacter = function(player)
if player == LocalPlayer then
return char.rootpart and char.rootpart.Parent
end
for i,v in pairs(debug.getupvalue(replication.getplayerhit, 1)) do
if v == player then
return i
end
end
end
char.humanoid = debug.getupvalue(char.getstate, 1)
storage.char = storage.char or {}
-- Infinite jump & JumpPower
storage.char.jump = storage.char.jump or char.jump
char.jump = function(self, ...)
if (settings.setjumppower) then
char.humanoid.JumpPower = (2 * game.Workspace.Gravity * settings.jumppower) ^ 0.5
char.humanoid.Jump = true
return true
end
return storage.char.jump(self, ...)
end
-- walkspeed
storage.char.setbasewalkspeed = storage.char.setbasewalkspeed or char.setbasewalkspeed
storage.char.oldWalkspeed = 16
char.setbasewalkspeed = function(self, speed, ...)
storage.char.oldWalkspeed = speed
if (settings.setwalkspeed) then
return storage.char.setbasewalkspeed(self, settings.walkspeed)
end
return storage.char.setbasewalkspeed(self, speed, ...)
end
--[[
storage.char.loadgun = storage.char.loadgun or char.loadgun
local modifyData = storage.char.modifyData or debug.getupvalue(char.loadgun, 1)
storage.char.modifyData = modifyData
local getGunData = storage.char.getGunData or debug.getupvalue(char.loadgun, 2)
storage.char.getGunData = getGunData
char.loadgun = function(...)
local gunName, magShit, spareRounds, attachments, data, camodata, gunnumber = ...
print(gunName, magShit, spareRounds, attachments, data, camodata, gunnumber)
--local data = v33(u38(self), p296, p297);
return storage.char.loadgun(...)
end--]]
--[[for i,v in pairs(gamelogic.currentgun) do
print(i,v)
end--]]
end
do -- Workspace visuals
local color = Color3.fromRGB(175, 120, 180)
local function editInstance(v)
if v:IsA("BasePart") then
v.Material = Enum.Material.ForceField
v.Color = color
elseif v:IsA("FileMesh") then
v.TextureId = '6856098975' -- 6838365496
if v.Parent and v.Parent:IsA("BasePart") then
local c = v.Parent.Color
v.VertexColor = Vector3.new(color.r, color.g, color.b)
end
elseif v:IsA("RopeConstraint") then
v.Visible = false
elseif v:IsA("Texture") then
v.Transparency = 1
end
end
bindEvent(workspace.CurrentCamera.DescendantAdded, function(v)
if settings.gunVisuals then
editInstance(v)
end
end)
if (settings.gunVisuals) then
for i,v in pairs(workspace.CurrentCamera:GetDescendants()) do
editInstance(v)
end
end
bindEvent(workspace:WaitForChild("Ignore"):WaitForChild("DeadBody").DescendantAdded, function(v)
if settings.deadVisuals then
editInstance(v)
end
end)
if (settings.deadVisuals) then
for i,v in pairs(workspace.Ignore.DeadBody:GetDescendants()) do
editInstance(v)
end
end
local effect = storage.colorEffect or Instance.new("ColorCorrectionEffect")
effect.Enabled = settings.colorEffect
effect.Brightness = 0.4
effect.Contrast = 0.4
effect.Saturation = 0.1
effect.TintColor = color
storage.colorEffect = effect
effect.Parent = game:GetService("Lighting")
end
do -- camera
camera.shakespring.s = 0;
camera.shakespring.d = 1000;
camera.shakespring.t = Vector3.new()
camera.magspring.s = 12;
camera.magspring.d = 1;
camera.magspring.t = 0
camera.swayspring.s = 0;
camera.swayspring.d = 1000;
camera.swayspring.t = 0
camera.swayspeed.s = 0;
camera.swayspeed.d = 1000;
camera.swayspeed.t = 0;
camera.zanglespring.s = 0;
camera.offsetspring.s = 0;
end
do -- Network hook funcs
storage.network = storage.network or {}
local old_send = storage.network.send or network.send
storage.network.send = old_send
network.send = function(self, method, ...) -- hookfunction randomly broke, idk why :(
if checkcaller() then return old_send(self, method, ...) end
local args = {...}
if method == "closeconnection" then
return
end
if method == "falldamage" and settings.nofalldamage then
return -- Remove fall damage
end
if method == "bullethit" and settings.headshotchanceenabled then -- headshot %
if args[3] and typeof(args[3]) == 'string' then
local ran = math.random(1,100)
if ran <= settings.headshotchance then
args[3] = "Head"
else
args[3] = "Torso"
end
end
end
if method == "knifehit" and settings.headshotchanceenabled then -- headshot %
if args[3] and typeof(args[3]) == "Instance" then
local ran = math.random(1,100)
if ran <= settings.headshotchance then
args[3] = args[3].Parent:FindFirstChild("Head") or args[3]
else
args[3] = args[3].Parent:FindFirstChild("Torso") or args[3]
end
end
end
return old_send(self, method, unpack(args))
end
end
do -- Metatable hooks
local old_mt = storage.old_mt or {}
storage.old_mt = old_mt
local _nindex = hookmetamethod(game, "__index", function(...)
local self, index = ...
if checkcaller() then
return old_mt.__index(self, index)
end
if index == "CFrame" and settings.silentaim then -- its a meh..
local barrel = gamelogic and gamelogic.currentgun and gamelogic.currentgun.barrel
local sight = gamelogic and gamelogic.currentgun and gamelogic.currentgun.aimsightdata and gamelogic.currentgun.aimsightdata[1] and gamelogic.currentgun.aimsightdata[1].sightpart
if barrel and (self == barrel or self == sight) then
local Head, dist, plr = utility.getClosestMouseTarget({
ignoreteam = true,
ignorewalls = false,
maxobscuringparts = 0,
name = 'Head',
fov = settings.fov,
maxdist = 3000,
checkifalive = false
})
if Head then
local bulletspeed = gamelogic.currentgun.data and gamelogic.currentgun.data.bulletspeed or dist * 10
--dist = (bulletspeed ^ 2 * dist + 196.2 * dist) / bulletspeed ^ 2
local t = (bulletspeed * dist + 196.2 * dist) / bulletspeed ^ 2
local Dir = Vector3.new(
Head.Position.X,
Head.Position.Y + (((196.2 ^ t) / 2) - (t * 2)),
Head.Position.Z
)
Dir = Dir + (Head.Parent.Torso.Velocity * (t * 2.1))
return CFrame.new(barrel.Position, Dir)
end
end
end
return old_mt.__index(self, index)
end)
old_mt.__index = old_mt.__index or _nindex
local _neindex = hookmetamethod(game, "__newindex", function(...)
local self, index, value = ...
if checkcaller() then
return old_mt.__newindex(self, index, value)
end
if index == "FieldOfView" then
return old_mt.__newindex(self, index, value * 3)
end
return old_mt.__newindex(self, index, value)
end)
old_mt.__newindex = old_mt.__newindex or _neindex
end
local clearDrawn, newdrawing
do
--/ Drawing extra functions
local insert = table.insert
local newd = Drawing.new
local drawn = {}
function clearDrawn() -- who doesnt love drawing library
for i,v in pairs(drawn) do
pcall(function() v:Remove() end)
drawn[i] = nil
end
drawn = {}
end
function newdrawing(class, props)
--if visuals.enabled ~= true then
-- return
--end
local new = newd(class)
for i,v in pairs(props) do
new[i] = v
end
insert(drawn, new)
return new
end
end
local sett_2 = settings
local settings = __SETTINGS__
do
--/ Settings
-- TODO: Other datatypes.
settings.fileName = "PFHax_settings.txt" -- Lovely
settings.saved = {}
function settings:Get(name, default)
local self = {}
local value = settings.saved[name]
if value == nil and default ~= nil then
value = default
settings.saved[name] = value
end
self.Value = value
function self:Set(val)
self.Value = val
settings.saved[name] = val
end
return self --value or default
end
function settings:Set(name, value)
local r = settings.saved[name]
settings.saved[name] = value
return r
end
function settings:Save()
local savesettings = settings:GetAll() or {}
local new = mergetab(savesettings, settings.saved)
local js = serialize(new)
writefile(settings.fileName, js)
end
function settings:GetAll()
if not existsFile(settings.fileName) then
return
end
local fileContents = readfile(settings.fileName)
local data
pcall(function()
data = deserialize(fileContents)
end)
return data
end
function settings:Load()
if not existsFile(settings.fileName) then
return
end
local fileContents = readfile(settings.fileName)
local data
pcall(function()
data = deserialize(fileContents)
end)
if data then
data = mergetab(settings.saved, data)
end
settings.saved = data
return data
end
---settings:Load()
spawn(function()
while main and main.enabled do
settings:Save()
wait(5)
end
end)
end
local esp = {} do
local esp_settings = {}
esp_settings.enabled = settings:Get("esp.enabled", true)
esp_settings.showteam = settings:Get("esp.showteam", false)
esp_settings.teamcolor = Color3.fromRGB(155, 114, 170) -- 121,255,97, 57,255,20
esp_settings.enemycolor = Color3.fromRGB(234, 234, 234) -- 238,38,37, 255,0,13, 255,7,58
esp_settings.visiblecolor = Color3.fromRGB(234, 234, 234) -- 0, 141, 255
esp_settings.size = settings:Get("esp.size", 16)
esp_settings.centertext = settings:Get("esp.centertext", true)
esp_settings.outline = settings:Get("esp.outline", true)
esp_settings.transparency = settings:Get("esp.transparency", 0.1)
esp_settings.drawdistance = settings:Get("esp.drawdistance", 1500)
esp_settings.showvisible = settings:Get("esp.showvisible", true)
esp_settings.yoffset = settings:Get("esp.yoffset", 4)
esp_settings.showhealth = settings:Get("esp.showhealth", true)
esp_settings.showdistance = settings:Get("esp.showdistance", true)
setmetatable(esp, {
__index = function(self, index)
if esp_settings[index] ~= nil then
local Value = esp_settings[index]
if typeof(Value) == "table" then
return typeof(Value) == "table" and Value.Value
else
return Value
end
end
warn(("EspSettings : Tried to index %s"):format(tostring(index)))
end;
__newindex = function(self, index, value)
if typeof(value) ~= "function" then
if esp_settings[index] ~= nil then
local v = esp_settings[index]
if typeof(v) ~= "table" then
esp_settings[index] = value
return
elseif v.Set then
v:Set(value)
return
end
end
end
rawset(self, index, value)
end;
})
local currentcamera = workspace.CurrentCamera
local worldToViewportPoint = currentcamera.WorldToViewportPoint
local floor = math.floor
local insert = table.insert
local concat = table.concat
local v2new = Vector2.new
local drawn = {}
local completeStop = false
local function drawTemplate(player)
if completeStop then return end
if drawn[player] then return drawn[player] end
local obj = newdrawing("Text", {
Text = "n/a",
Size = esp.size,
Color = esp.enemycolor,
Center = esp.centertext,
Outline = esp.outline,
Transparency = (1 - esp.transparency),
})
return obj
end
function esp:Draw(player, character, root, humanoid, onscreen, isteam, dist)
if completeStop then return end
if character == nil then return esp:Remove(player) end
if root == nil then return esp:Remove(player) end
if not esp.showteam and isteam then
return esp:Remove(player)
end
if dist then
if dist > esp.drawdistance then
return esp:Remove(player)
end
end
local where, isvis = worldToViewportPoint(currentcamera, (root.CFrame * esp.offset).p);
--if not isvis then return esp:Remove(player) end
local oesp = drawn[player]
if oesp == nil then
oesp = drawTemplate(player)
drawn[player] = oesp
end
if oesp then
oesp.Visible = isvis
if isvis then
oesp.Position = v2new(where.X, where.Y)
local color
if isteam == false and esp.showvisible then
if utility.isvisible(character, root, 0) then
color = esp.visiblecolor
else
color = isteam and esp.teamcolor or esp.enemycolor
end
else
color = isteam and esp.teamcolor or esp.enemycolor
end
oesp.Color = color
oesp.Center = esp.centertext
oesp.Size = esp.size
oesp.Outline = esp.outline
oesp.Transparency = (1 - esp.transparency)
local texts = {
player.Name,
}
local b = humanoid and esp.showhealth and ("%s/%s"):format(floor(humanoid.Health + .5), floor(humanoid.MaxHealth + .5))
if b then
insert(texts, b)
end
local c = dist and esp.showdistance and ("%s"):format(floor(dist + .5))
if c then
insert(texts, c)
end
local text = "[ " .. concat(texts, " | ") .. " ]"
oesp.Text = text
end
end
end
function esp:Remove(player)
local data = drawn[player]
if data ~= nil then
data:Remove()
drawn[player] = nil
end
end
function esp:RemoveAll()
for i,v in pairs(drawn) do
pcall(function() v:Remove() end)
drawn[i] = nil
end
end
function esp:End()
completeStop = true
esp:RemoveAll()
end
end
local boxes = {} do
--/ Boxes
local boxes_settings = {}
boxes_settings.enabled = settings:Get("boxes.enabled", true)
boxes_settings.transparency = settings:Get("boxes.transparency", .2)
boxes_settings.thickness = settings:Get("boxes.thickness", 1.5)
boxes_settings.showteam = settings:Get("boxes.showteam", false)
boxes_settings.teamcolor = Color3.fromRGB(155, 114, 170) -- 121,255,97, 57,255,20
boxes_settings.enemycolor = Color3.fromRGB(220,20,60) -- 238,38,37, 255,0,13, 255,7,58
boxes_settings.visiblecolor = Color3.fromRGB(234, 234, 234)
boxes_settings.thirddimension = settings:Get("boxes.thirddimension", true)
boxes_settings.showvisible = settings:Get("boxes.showvisible", true)
boxes_settings.dist3d = settings:Get("boxes.dist3d", 1000)
boxes_settings.drawdistance = settings:Get("boxes.drawdistance", 4000)
boxes_settings.color = Color3.fromRGB(255, 50, 50)
setmetatable(boxes, {
__index = function(self, index)
if boxes_settings[index] ~= nil then
local Value = boxes_settings[index]
if typeof(Value) == "table" then
return typeof(Value) == "table" and Value.Value
else
return Value
end
end
warn(("BoxesSettings : Tried to index %s"):format(tostring(index)))
end;
__newindex = function(self, index, value)
if typeof(value) ~= "function" then
if boxes_settings[index] then
local v = boxes_settings[index]
if typeof(v) ~= "table" then
boxes_settings[index] = value
return
elseif v.Set then
v:Set(value)
return
end
end
end
rawset(self, index, value)
end;
})
local currentcamera = workspace.CurrentCamera
local unpack = unpack
local worldToViewportPoint = currentcamera.WorldToViewportPoint
local v2new = Vector2.new
local cfnew = CFrame.new
local completeStop = false
local drawn = {}
local function drawTemplate(player, amount)
if completeStop then return end
if drawn[player] then
if #drawn[player] == amount then
return drawn[player]
end
boxes:Remove(player)
end
local props = {
Visible = true;
Transparency = 1 - boxes.transparency;
Thickness = boxes.thickness;
Color = boxes.color;
}
local a = {}
for i = 1,amount or 4 do
a[i] = newdrawing("Line", props)
end
drawn[player] = {unpack(a)}
return unpack(a)
end
local function updateLine(line, from, to, vis, color)
if line == nil then return end
line.Visible = vis
if vis then
line.From = from
line.To = to
line.Color = color
end
end
function boxes:Draw(player, character, root, humanoid, onscreen, isteam, dist) -- No skid plox
if completeStop then return end
if character == nil then return boxes:Remove(player) end
if root == nil then return boxes:Remove(player) end
if not onscreen then return boxes:Remove(player) end
if not boxes.showteam and isteam then
return boxes:Remove(player)
end
local _3dimension = boxes.thirddimension
if dist ~= nil then
if dist > boxes.drawdistance then
return boxes:Remove(player)
elseif _3dimension and dist > boxes.dist3d then
_3dimension = false
end
end
local color
if isteam == false and boxes.showvisible then
if utility.isvisible(character, root, 0) then
color = boxes.visiblecolor
else
color = isteam and boxes.teamcolor or boxes.enemycolor
end
else
color = isteam and boxes.teamcolor or boxes.enemycolor
end
--size = ... lastsize--, v3new(5,8,0) --getBoundingBox(character)--]] root.CFrame, getExtentsSize(character)--]] -- Might change this later idk + idc
if _3dimension then
local tlb, trb, blb, brb, tlf, trf, blf, brf, tlf0, trf0, blf0, brf0
if drawn[player] == nil or #drawn[player] ~= 12 then
tlb, trb, blb, brb, tlf, trf ,blf, brf, tlf0, trf0, blf0, brf0 = drawTemplate(player, 12)
else
tlb, trb, blb, brb, tlf, trf ,blf, brf, tlf0, trf0, blf0, brf0 = unpack(drawn[player])
end
local pos, size = root.CFrame, root.Size--lastsize--, v3new(5,8,0)
local topleftback, topleftbackvisible = worldToViewportPoint(currentcamera, (pos * cfnew(-size.X, size.Y, size.Z)).p);
local toprightback, toprightbackvisible = worldToViewportPoint(currentcamera, (pos * cfnew(size.X, size.Y, size.Z)).p);
local btmleftback, btmleftbackvisible = worldToViewportPoint(currentcamera, (pos * cfnew(-size.X, -size.Y, size.Z)).p);
local btmrightback, btmrightbackvisible = worldToViewportPoint(currentcamera, (pos * cfnew(size.X, -size.Y, size.Z)).p);
local topleftfront, topleftfrontvisible = worldToViewportPoint(currentcamera, (pos * cfnew(-size.X, size.Y, -size.Z)).p);
local toprightfront, toprightfrontvisible = worldToViewportPoint(currentcamera, (pos * cfnew(size.X, size.Y, -size.Z)).p);
local btmleftfront, btmleftfrontvisible = worldToViewportPoint(currentcamera, (pos * cfnew(-size.X, -size.Y, -size.Z)).p);
local btmrightfront, btmrightfrontvisible = worldToViewportPoint(currentcamera, (pos * cfnew(size.X, -size.Y, -size.Z)).p);
local topleftback = v2new(topleftback.X, topleftback.Y)
local toprightback = v2new(toprightback.X, toprightback.Y)
local btmleftback = v2new(btmleftback.X, btmleftback.Y)
local btmrightback = v2new(btmrightback.X, btmrightback.Y)
local topleftfront = v2new(topleftfront.X, topleftfront.Y)
local toprightfront = v2new(toprightfront.X, toprightfront.Y)
local btmleftfront = v2new(btmleftfront.X, btmleftfront.Y)
local btmrightfront = v2new(btmrightfront.X, btmrightfront.Y)
-- pls don't copy this bad code
updateLine(tlb, topleftback, toprightback, topleftbackvisible, color)
updateLine(trb, toprightback, btmrightback, toprightbackvisible, color)
updateLine(blb, btmleftback, topleftback, btmleftbackvisible, color)
updateLine(brb, btmleftback, btmrightback, btmrightbackvisible, color)
--
updateLine(brf, btmrightfront, btmleftfront, btmrightfrontvisible, color)
updateLine(tlf, topleftfront, toprightfront, topleftfrontvisible, color)
updateLine(trf, toprightfront, btmrightfront, toprightfrontvisible, color)
updateLine(blf, btmleftfront, topleftfront, btmleftfrontvisible, color)
--
updateLine(brf0, btmrightfront, btmrightback, btmrightfrontvisible, color)
updateLine(tlf0, topleftfront, topleftback, topleftfrontvisible, color)
updateLine(trf0, toprightfront, toprightback, toprightfrontvisible, color)
updateLine(blf0, btmleftfront, btmleftback, btmleftfrontvisible, color)
return
else
local tl, tr, bl, br
if drawn[player] == nil or #drawn[player] ~= 4 then
tl, tr, bl, br = drawTemplate(player, 4)
else
tl, tr, bl, br = unpack(drawn[player])
end
local pos, size = root.CFrame, root.Size
local topleft, topleftvisible = worldToViewportPoint(currentcamera, (pos * cfnew(-size.X, size.Y, 0)).p);
local topright, toprightvisible = worldToViewportPoint(currentcamera, (pos * cfnew(size.X, size.Y, 0)).p);
local btmleft, btmleftvisible = worldToViewportPoint(currentcamera, (pos * cfnew(-size.X, -size.Y, 0)).p);
local btmright, btmrightvisible = worldToViewportPoint(currentcamera, (pos * cfnew(size.X, -size.Y, 0)).p);
local topleft = v2new(topleft.X, topleft.Y)
local topright = v2new(topright.X, topright.Y)
local btmleft = v2new(btmleft.X, btmleft.Y)
local btmright = v2new(btmright.X, btmright.Y)
updateLine(tl, topleft, topright, topleftvisible, color)
updateLine(tr, topright, btmright, toprightvisible, color)
updateLine(bl, btmleft, topleft, btmleftvisible, color)
updateLine(br, btmleft, btmright, btmrightvisible, color)
return
end
-- I have never been more bored when doing 3d boxes.
end
function boxes:Remove(player)
local data = drawn[player]
if data == nil then return end
if data then
for i,v in pairs(data) do
v:Remove()
data[i] = nil
end
end
drawn[player] = nil
end
function boxes:RemoveAll()
for i,v in pairs(drawn) do
pcall(function()
for i2,v2 in pairs(v) do
v2:Remove()
v[i] = nil
end
end)
drawn[i] = nil
end
drawn = {}
end
function boxes:End()
completeStop = true
for i,v in pairs(drawn) do
for i2,v2 in pairs(v) do
pcall(function()
v2:Remove()
v[i2] = nil
end)
end
drawn[i] = nil
end
drawn = {}
end
end
local visuals = {} do
--/ Visuals
visuals.enabled = settings:Get("visuals.enabled", true).Value
local players = game:GetService("Players")
local locpl = players.LocalPlayer
local mouse = locpl:GetMouse()
local isDescendantOf = game.IsDescendantOf
local getPlayers = players.GetPlayers
local findFirstChildOfClass = game.FindFirstChildOfClass
local cfnew = CFrame.new
local completeStop = false
bindEvent(players.PlayerRemoving, function(p)
if completeStop then return end
boxes:Remove(p)
esp:Remove(p)
end)
local currentcamera = workspace.CurrentCamera
local worldToViewportPoint = currentcamera.WorldToViewportPoint
local function remove(p)
esp:Remove(p)
boxes:Remove(p)
end
local circle = newdrawing("Circle", {
Position = Vector2.new(mouse.X, mouse.Y+36),
Radius = sett_2.fov,
Color = Color3.fromRGB(240,240,240),
Thickness = sett_2.fovthickness,
Filled = false,
Transparency = 0,
NumSides = sett_2.fovsides,
Visible = sett_2.fovcircle;
})
function visuals.step()
--if visuals.enabled ~= true then return clearDrawn() end
if completeStop then return end
if (visuals.enabled and (sett_2.fovcircle)) then
circle.Position = Vector2.new(mouse.X, mouse.Y+36)
circle.Radius = sett_2.fov
circle.NumSides = sett_2.fovsides
circle.Thickness = sett_2.fovthickness
circle.Transparency = .8
else
circle.Transparency = 0
end
if visuals.enabled and (esp.enabled or boxes.enabled) then
if esp.enabled then
esp.offset = cfnew(0, esp.yoffset, 0)
end
for i,v in pairs(getPlayers(players)) do
if (v ~= locpl) then
local character = utility.getcharacter(v)
if character and isDescendantOf(character, game) == true then
local root = utility.getroot(character)
local humanoid = findFirstChildOfClass(character, "Humanoid")
if root and isDescendantOf(character, game) == true then
local screenpos, onscreen = worldToViewportPoint(currentcamera, root.Position)
local dist = utility.myroot and (utility.myroot.Position - root.Position).Magnitude
local isteam = (v.Team~=nil and v.Team==locpl.Team) and not v.Neutral or false
if not boxes.showteam and not esp.showteam and isteam then
remove(v)
continue
end
if boxes.enabled then -- Profilebegin is life
boxes:Draw(v, character, root, humanoid, onscreen, isteam, dist)
else
boxes:Remove(v)
end
if esp.enabled then
esp:Draw(v, character, root, humanoid, onscreen, isteam, dist)
else
esp:Remove(v)
end
else
remove(v)
end
else
remove(v)
end
end
end
else
-- mhm
boxes:RemoveAll()
esp:RemoveAll()
end
end
function visuals:End()
completeStop = true
boxes:End()
esp:End()
clearDrawn()
end
table.insert(end_funcs, visuals.End)
end
-- Ok yes
local run = {} do
--/ Run
local tostring = tostring;
local warn = warn;
local debug = debug;
local runservice = game:GetService("RunService")
local renderstep = runservice.RenderStepped
local heartbeat = runservice.Heartbeat
local stepped = runservice.Stepped
local wait = renderstep.wait
local function Warn(a, ...) -- ok frosty get to bed
warn(tostring(a):format(...))
end
run.dt = 0
run.time = tick()
local engine = {
{
name = 'visuals.step',
func = visuals.step
};
}
local heartengine = {
}
local whilerender = {
}
run.onstep = {}
run.onthink = {}
run.onrender = {}
function run.wait()
wait(renderstep)
end
local rstname = "Renderstep"
bindEvent(renderstep, function(delta)
local ntime = tick()
run.dt = ntime - run.time
run.time = ntime
for i,v in pairs(engine) do
xpcall(v.func, function(err)
Warn("Failed to run %s! %s | %s", v.name, tostring(err), debug.traceback())
engine[i] = nil
end, run.dt)
end
end)
bindEvent(heartbeat, function(delta)
for i,v in pairs(heartengine) do
xpcall(v.func, function(err)
Warn("Failed to run %s! %s | %s", v.name, tostring(err), debug.traceback())
heartengine[i] = nil
end, delta)
end
end)
bindEvent(stepped, function(delta)
for i,v in pairs(whilerender) do
xpcall(v.func, function(err)
Warn("Failed to run %s! %s | %s", v.name, tostring(err), debug.traceback())
heartengine[i] = nil
end, delta)
end
end)
end
local uid = tick() .. math.random(1,100000) .. math.random(1,100000)
if shared.main and shared.main.close and shared.main.uid~=uid then shared.main:close() end
local hud = loadstring(game:HttpGet("https://pastebin.com/raw/3hREvLEU", true))()[1]
table.insert(end_funcs, hud.End)
do
--/ Main or something I am not sure what I am writing anymore
settings:Save()
main.enabled = true
main.visible = hud.Visible
function main:show()
hud:show()
main.visible = hud.Visible
end
function main:hide()
hud:hide()
main.visible = hud.Visible
end
setmetatable(main, { -- ok safazi be happy now
__newindex = function(self, index, value)
if (index == "Keybind") then
settings:Set("hud.keybind", value)
hud.Keybind = value
return
end
end;
})
shared.main = main
local players = game:GetService("Players")
local loc = players.LocalPlayer
bindEvent(players.PlayerRemoving, function(p)
if p == loc then
settings:Save()
end
end)
end
local shais = sett_2
-- I didn't think this ui lib through
local Aiming = hud:AddTab({
Text = "silent aim",
})
Aiming:AddToggle({
Text = "enable silent aim",
State = shais.silentaim,
}, function(new)
shais.silentaim = new
end)
Aiming:AddSlider({
Text = "headshot chance",
Current = shais.headshotchance,
}, {0, 100, 1}, function(new)
shais.headshotchance = new
end)
local FieldOfView = Aiming:AddToggleCategory({
Text = "fov",
State = shais.fovcircle,
}, function(state)
shais.fovcircle = state
end)
FieldOfView:AddSlider({
Text = "Radius",
Current = shais.fov,
}, {1, 1000, 1}, function(new)
shais.fov = new
end)
FieldOfView:AddSlider({
Text = "Sides",
Current = shais.fovsides,
}, {6, 40, 1}, function(new)
shais.fovsides = new
end)
FieldOfView:AddSlider({
Text = "Thickness",
Current = shais.fovthickness,
}, {0.1, 50, 0.1}, function(new)
shais.fovthickness = new
end)
local Character = hud:AddTab({
Text = "character",
})
Character:AddToggle({
Text = "no fall damage",
State = shais.nofalldamage,
}, function(new)
shais.nofalldamage = new
end)
Character:AddToggle({
Text = "enable speed",
State = shais.setwalkspeed,
}, function(new)
shais.setwalkspeed = new
if (not new) then
storage.char.setbasewalkspeed(char, storage.char.oldWalkspeed)
else
storage.char.setbasewalkspeed(char, shais.walkspeed)
end
end)
Character:AddSlider({
Text = "speed",
Current = shais.walkspeed,
}, {1, 100, 1}, function(new)
shais.walkspeed = new
storage.char.setbasewalkspeed(char, new)
end)
Character:AddToggle({
Text = "enable jump",
State = shais.setjumppower,
}, function(new)
shais.setjumppower = new
end)
Character:AddSlider({
Text = "jumppower",
Current = shais.jumppower,
}, {1, 50, 1}, function(new)
shais.jumppower = new
end)
local Visuals = hud:AddTab({
Text = "Visuals",
})
Visuals:AddLabel({Text = "Gun visuals will update when you respawn"})
Visuals:AddToggle({
Text = "Color effect",
State = shais.colorEffect,
}, function(new)
shais.colorEffect = new
storage.colorEffect.Enabled = new
end)
Visuals:AddToggle({
Text = "Gun visuals",
State = shais.gunVisuals,
}, function(new)
shais.gunVisuals = new
end)
Visuals:AddToggle({
Text = "Dead visuals",
State = shais.deadVisuals,
}, function(new)
shais.deadVisuals = new
end)
local Hud = hud:AddTab({
Text = "Hud",
})
hud.Keybind = settings:Get("hud.keybind", "RightAlt").Value
Hud:AddKeybind({
Text = "Toggle",
Current = hud.Keybind,
}, function(new)
settings:Set("hud.keybind", new.Name)
hud.Keybind = new.Name
end)
Hud:AddButton({
Text = "Exit"
}, function()
main:End()
end)
|
-- Called OnSpellStart
function MysticBoltSpendMana(event)
local caster = event.caster
local ability = event.ability
-- Storing current mana into a local variable
local current_caster_mana = caster:GetMana()
-- If the table is nil or empty, create a new one with same name and insert one element into it
if caster.mana_spent_at_cast_time == nil or next(caster.mana_spent_at_cast_time) == nil then
-- Create or reset the table
caster.mana_spent_at_cast_time = {}
-- Create or reset the counter
caster.mystic_bolt_counter = 1
-- Store the current mana at the moment of cast in the table
caster.mana_spent_at_cast_time[1] = current_caster_mana
else
-- Increment the counter
caster.mystic_bolt_counter = caster.mystic_bolt_counter + 1
-- Store the current mana at the moment of cast in the table
caster.mana_spent_at_cast_time[caster.mystic_bolt_counter] = current_caster_mana
end
-- Spending current mana
caster:SpendMana(current_caster_mana, ability)
end
-- Called OnProjectileHitUnit
function MysticBoltHit(event)
local target = event.target
local caster = event.caster
local ability = event.ability
-- Find correct mana_at_that_time
local mana_at_that_time
for i, mana in pairs(caster.mana_spent_at_cast_time) do
if mana then
mana_at_that_time = mana
caster.mana_spent_at_cast_time[i] = nil
break
end
end
-- if the 'for loop' doesn't work for some reason then define mana_at_that_time
if mana_at_that_time == nil then
mana_at_that_time = 0
end
-- Checking if target has spell block, if target has spell block, there is no need to execute the spell
if not target:TriggerSpellAbsorb(ability) then
local ability_level = ability:GetLevel() - 1
local base_damage = ability:GetLevelSpecialValueFor("base_damage", ability_level)
local damage_per_mana = ability:GetLevelSpecialValueFor("damage_per_mana", ability_level)
local damage_table = {}
damage_table.attacker = caster
damage_table.damage_type = ability:GetAbilityDamageType()
damage_table.ability = ability
damage_table.victim = target
damage_table.damage = base_damage + mana_at_that_time*damage_per_mana
if target:HasModifier("modifier_anti_magic_field_buff") then
damage_table.damage_type = DAMAGE_TYPE_PHYSICAL
damage_table.damage_flags = DOTA_DAMAGE_FLAG_BYPASSES_BLOCK
end
-- Applying the damage
ApplyDamage(damage_table)
end
-- Stop Sounds
StopSoundOn("Hero_SkywrathMage.ArcaneBolt.Cast", caster)
StopSoundOn("Hero_SkywrathMage.ArcaneBolt.Impact", target)
end |
-----------------------------------
-- Area: The Sanctuary of Zitah
-- NPC: ???
-- Finishes Quest: Lovers in the Dusk
-- !zone 121
-----------------------------------
local ID = require("scripts/zones/The_Sanctuary_of_ZiTah/IDs")
require("scripts/globals/npc_util")
require("scripts/globals/weather")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
if player:getQuestStatus(BASTOK, tpz.quest.id.bastok.LOVERS_IN_THE_DUSK) == QUEST_ACCEPTED and VanadielTOTD() == tpz.time.DUSK then
player:startEvent(204)
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 204 then
npcUtil.completeQuest(player, BASTOK, tpz.quest.id.bastok.LOVERS_IN_THE_DUSK, {item = 17346, fame = 120})
end
end |
local uv = require "lluv"
local iconv = require "iconv"
local json = require "dkjson"
local NULL = require "null".null
local utils = {}
utils.json = json
utils.NULL = NULL
utils.STATUS = {
SENDING = 'sending',
SUCCESS = 'success',
FAIL = 'fail',
}
function utils.coalesce(v, ...)
if v == NULL then return utils.coalesce(...) end
return v
end
local unpack = unpack or table.unpack -- luacheck: ignore unpack
utils.unpack = unpack
do -- is_uuid
local pattern = '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$'
function utils.is_uuid(s)
return s and string.match(s, pattern)
end
end
function utils.is_2xx(c) return c and (c >= 200) and (c <= 299) and c end
function utils.delay_call(timeout, cb, ...)
local argv, argc = {...}, select('#', ...)
uv.timer():start(timeout, function(timer)
timer:close()
cb(unpack(argv, 1, argc))
end)
end
local function pass(msg) return msg end
function utils.iconv_converter(src, dst)
if dst == src then return pass end
local conv = iconv.new(dst, src)
if not conv then return pass end
return function(msg)
return msg and conv:iconv(msg) or msg
end
end
do -- pgerr_tostring
local conv = utils.iconv_converter('utf-8', 'cp866')
function utils.pgerr_tostring(err)
if err and err.cat and err:cat() == "PostgreSQL" then
err = conv(tostring(err))
end
return tostring(err)
end
end
function utils.render(str, params, ...)
for k, v in pairs(params) do
str = string.gsub(str, '${' .. k .. '}', v)
end
if ... then return utils.render(str, ...) end
return str
end
function utils.deep_render(t, ...)
if type(t) == 'string' then
return utils.render(t, ...)
end
local res = {}
for k, v in pairs(t) do
res[k] = utils.deep_render(v, ...)
end
return res
end
function utils.append(t, v)
t[#t + 1] = v
return t
end
function utils.pg_apply_names(rs, no_null)
local colnames = rs.header and rs.header[1]
for rowid = 1, #rs do
local row = rs[rowid]
for i = 1, #row do
local name = colnames[i]
local value = row[i]
print(value, NULL)
if value == NULL then
print("::", name, value, no_null)
if no_null then value = nil end
end
row[name] = value
end
end
return rs
end
function utils.pg_named_cb(no_null, cb)
if not cb then cb, no_null = no_null, nil end
return function(self, err, ...)
if ... then utils.pg_apply_names(..., no_null) end
return cb(self, err, ...)
end
end
utils.is = setmetatable ({}, {
__index = function (self, TYPE)
local fn = function (VALUE)
if type(VALUE) ~= TYPE then
local msg = string.format('Invalid value type. Expected `%s` but got `%s`',
TYPE, type(VALUE)
)
return error(msg, 2)
end
return VALUE
end
self[TYPE] = fn
return fn
end
})
return utils |
--- A western style swinging door with key.
Door = {
-- specifies whether it is in the closed or opened state
open = nil,
-- specifies whether the key is turned or not
locked = nil
}
function Door.new( map, x, y, dir )
local door = Object.new( map, x, y, 0, dir )
door.opened = false
door.locked = false
door.interaction = interaction.open
door.isDoor = true
door.render = Door.render
door.isOpen = Door.isOpen
door.isLocked = Door.isLocked
door.open = Door.open
door.close = Door.close
door.lock = Door.lock
door.unlock = Door.unlock
return door
end
function Door:isOpen()
return self.opened
end
function Door:isLocked()
return self.locked
end
function Door:open()
if not self.opened and not self.locked then
self.opened = true
end
end
function Door:close()
if not self.locked then
self.opened = false
end
end
function Door:lock()
-- if key in door
self.locked = true
end
function Door:unlock()
-- if key in door
self.locked = false
end
function Door:render( x, y )
local x = self.x * world.tileSize
local y = self.y * world.tileSize
local w = world.tileSize
local h = world.tileSize
if self.opened then
love.graphics.setColor( 255, 255, 255 )
else
love.graphics.setColor( 0, 0, 0 )
end
love.graphics.rectangle( "fill", x, y, w, h )
end
|
-- Copyright (c) 2019 Redfern, Trevor <trevorredfern@gmail.com>
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
describe("Alignment", function()
local align = require "moonpie.ui.alignment"
it("align left uses the smallest value possible", function()
local x = align("left", 10, 50, 5)
assert.equals(10, x)
end)
it("align right returns the maximum minus the width", function()
local x = align("right", 10, 50, 5)
assert.equals(45, x)
end)
it("takes the difference when aligning to the center", function()
local x = align("center", 10, 50, 5)
assert.equals(17.5, x)
end)
it("align top uses the smallest value possible", function()
local y = align("top", 10, 50, 5)
assert.equals(10, y)
end)
it("aligns bottom to the maximum minus the height", function()
local y = align("bottom", 10, 50, 5)
assert.equals(45, y)
end)
it("aligns middle to the difference and half left over", function()
local y = align("middle", 10, 50, 5)
assert.equals(17.5, y)
end)
end)
|
local config = require "formatter.config"
local M = {}
function M.setup(o)
config.set_defaults(o)
end
return M
|
object_building_player_construction_construction_player_tcg_relaxation_pool = object_building_player_construction_shared_construction_player_tcg_relaxation_pool:new {
}
ObjectTemplates:addTemplate(object_building_player_construction_construction_player_tcg_relaxation_pool, "object/building/player/construction/construction_player_tcg_relaxation_pool.iff")
|
return {
["LOP_NOP"]= 1,
["LOP_BREAK"]= 2,
["LOP_LOADNIL"]= 3,
["LOP_LOADB"]= 4,
["LOP_LOADN"]= 5,
["LOP_LOADK"]= 6,
["LOP_MOVE"]= 7,
["LOP_GETGLOBAL"]= 8,
["LOP_SETGLOBAL"]= 9,
["LOP_GETUPVAL"]= 10,
["LOP_SETUPVAL"]= 11,
["LOP_CLOSEUPVALS"]= 12,
["LOP_GETIMPORT"]= 13,
["LOP_GETTABLE"]= 14,
["LOP_SETTABLE"]= 15,
["LOP_GETTABLEKS"]= 16,
["LOP_SETTABLEKS"]= 17,
["LOP_GETTABLEN"]= 18,
["LOP_SETTABLEN"]= 19,
["LOP_NEWCLOSURE"]= 20,
["LOP_NAMECALL"]= 21,
["LOP_CALL"]= 22,
["LOP_RETURN"]= 23,
["LOP_JUMP"]= 24,
["LOP_JUMPBACK"]= 25,
["LOP_JUMPIF"]= 26,
["LOP_JUMPIFNOT"]= 27,
["LOP_JUMPIFEQ"]= 28,
["LOP_JUMPIFLE"]= 29,
["LOP_JUMPIFLT"]= 30,
["LOP_JUMPIFNOTEQ"]= 31,
["LOP_JUMPIFNOTLE"]= 32,
["LOP_JUMPIFNOTLT"]= 33,
["LOP_ADD"]= 34,
["LOP_SUB"]= 35,
["LOP_MUL"]= 36,
["LOP_DIV"]= 37,
["LOP_MOD"]= 38,
["LOP_POW"]= 39,
["LOP_ADDK"]= 40,
["LOP_SUBK"]= 41,
["LOP_MULK"]= 42,
["LOP_DIVK"]= 43,
["LOP_MODK"]= 44,
["LOP_POWK"]= 45,
["LOP_AND"]= 46,
["LOP_OR"]= 47,
["LOP_ANDK"]= 48,
["LOP_ORK"]= 49,
["LOP_CONCAT"]= 50,
["LOP_NOT"]= 51,
["LOP_MINUS"]= 52,
["LOP_LENGTH"]= 53,
["LOP_NEWTABLE"]= 54,
["LOP_DUPTABLE"]= 55,
["LOP_SETLIST"]= 56,
["LOP_FORNPREP"]= 57,
["LOP_FORNLOOP"]= 58,
["LOP_FORGLOOP"]= 59,
["LOP_FORGPREP_INEXT"]= 60,
["LOP_FORGLOOP_INEXT"]= 61,
["LOP_FORGPREP_NEXT"]= 62,
["LOP_FORGLOOP_NEXT"]= 63,
["LOP_GETVARARGS"]= 64,
["LOP_DUPCLOSURE"]= 65,
["LOP_PREPVARARGS"]= 66,
["LOP_LOADKX"]= 67,
["LOP_JUMPX"]= 68,
["LOP_FASTCALL"]= 69,
["LOP_COVERAGE"]= 70,
["LOP_CAPTURE"]= 71,
["LOP_JUMPIFEQK"]= 72,
["LOP_JUMPIFNOTEQK"]= 73,
["LOP_FASTCALL1"]= 74,
["LOP_FASTCALL2"]= 75,
["LOP_FASTCALL2K"]= 76,
["LOP__COUNT"]= 77
} |
skills = {001}
-- 범위에서 몹을 대상으로 가장 가까운 대상을 타겟으로 삼아 공격
local me = Client.myPlayerUnit
local target = nil
local range = 249
-- 내 위치로부터 238 범위가 사거리, 초과할 시 보는 방향으로 나감
local skillID = 001
-- 발사될 스킬 번호 1번
target = Client.field.FindNearUnit(me.x, me.y, range, 2, me)
if (target ~= nil) then
local dist = (me.x - target.x)^2 + (me.y - target.y)^2
if dist < range^2 then
me.UseSkill(skillID, Point(target.x - me.x, target.y - me.y))
end
else
me.UseSkill(001)
end
end |
local GuidLibary = { }
function GuidLibary:Hexidecimal(Size)
local HexValues = { }
for Index = 1, Size do
local HexValue = ("%x"):format((Index == Size and math.random(8, 11)) or math.random(0, 15))
table.insert(HexValues, HexValue)
end
return table.concat(HexValues)
end
function GuidLibary:GenerateShort()
return ("%s-%s"):format(
self:Hexidecimal(16), self:Hexidecimal(5)
)
end
function GuidLibary:GenerateLong()
return ("%s-%s-4%s-%s%s-%s"):format(
self:Hexidecimal(8), self:Hexidecimal(4),
self:Hexidecimal(3), self:Hexidecimal(1),
self:Hexidecimal(3), self:Hexidecimal(12)
)
end
function GuidLibary.new()
return GuidLibary:GenerateLong()
end
return GuidLibary |
mysql = exports.mysql
function leader_check (accountName, password)
local leader = tonumber( getElementData(source, "factionleader") )
if not (tonumber(leader)==1) then -- If the player is not the leader
triggerClientEvent("notLeader",source)
else
register_email(accountName, password)
end
end
addEvent("leaderCheck",true)
addEventHandler("leaderCheck",getRootElement(),leader_check)
function register_email(accountName, password)
local result = mysql:query("SELECT username FROM emailaccounts WHERE username='" .. mysql:escape_string(accountName) .."'")
if (mysql:num_rows(result)>0) then
mysql:free_result(result)
triggerClientEvent("name_in_use", source) -- Error Message
else
mysql:free_result(result)
triggerClientEvent("closeEmailLogin",source)
local dbid = getElementData(source, "dbid")
mysql:query_free("INSERT INTO emailaccounts SET username='" .. mysql:escape_string(accountName) .. "', password=MD5('" .. mysql:escape_string(password) .. "'), creator='"..dbid.."'") -- Create the account.
mysql:query_free("INSERT INTO emails SET date= NOW(), sender='Customer Services', receiver='" .. mysql:escape_string(accountName) .. "', subject='Welcome', inbox='1',outbox='0', message='Welcome,\
\
Your email account has been registered.\
\
Now you are online you are ableto receive email on the move.\
\
Username: " ..mysql:escape_string(accountName).."\
Password: " ..mysql:escape_string(password).."\
\
Rest assured your private details are secure with us and our arbitarary third party advertisers.\
\
Thank you for registering.'")
get_inbox(accountName)
get_outbox(accountName)
end
end
addEvent("registerEmail", true)
addEventHandler("registerEmail", getRootElement(),register_email)
function login_email(accountName, password)
local result = mysql:query("SELECT * FROM emailaccounts WHERE username='" .. mysql:escape_string(accountName) .."' AND password=MD5('" .. mysql:escape_string(password) .. "')")
if (mysql:num_rows(result)==0) then
mysql:free_result(result)
triggerClientEvent("loginError", source) -- Error Message
else
mysql:free_result(result)
triggerClientEvent("closeEmailLogin",source)
get_inbox(accountName)
get_outbox(accountName)
end
end
addEvent("loginEmail", true)
addEventHandler("loginEmail", getRootElement(),login_email)
function get_inbox(accountName)
-- `date` - INTERVAL 1 hour as 'newtime'
-- hour correction
local result = mysql:query("SELECT id, `date` - INTERVAL 1 hour as 'newdate', sender, subject, message FROM emails WHERE receiver='".. mysql:escape_string(accountName) .."' AND inbox='1' ORDER BY date DESC")
if (result) then
inbox_table = { }
local key = 1
local continue = true
while continue do
local row = mysql:fetch_assoc(result)
if not row then break end
inbox_table[key] = { }
inbox_table[key][1] = row["id"]
inbox_table[key][2] = row["newdate"]
inbox_table[key][3] = row["sender"]
inbox_table[key][4] = row["subject"]
inbox_table[key][5] = row["message"]
key = key + 1
end
if(key==1)then
inbox_table = {
{ "","","","","Inbox is empty" },
}
end
mysql:free_result(result)
triggerClientEvent("showInbox",source,inbox_table, accountName)
end
end
addEvent("s_getInbox",true)
addEventHandler("s_getInbox",getRootElement(),get_inbox)
function get_outbox(accountName)
local result = mysql:query("SELECT id, `date` - INTERVAL 1 hour as 'newdate', receiver, subject, message FROM emails WHERE sender='".. mysql:escape_string(accountName) .."' AND outbox='1' ORDER BY date DESC")
if (result) then
outbox_table = { }
local key = 1
local continue = true
while continue do
local row = mysql:fetch_assoc(result)
if not row then break end
outbox_table[key] = { }
outbox_table[key][1] = row["id"]
outbox_table[key][2] = row["newdate"]
outbox_table[key][3] = row["receiver"]
outbox_table[key][4] = row["subject"]
outbox_table[key][5] = row["message"]
key = key + 1
end
if(key==1)then
outbox_table = {
{ "","","","","Outbox is empty" },
}
end
mysql:free_result(result)
triggerClientEvent("showOutbox",source,outbox_table, accountName)
end
end
addEvent("s_getOutbox",true)
addEventHandler("s_getOutbox",getRootElement(),get_outbox)
function send_message(accountName,to,subject,message)
local result = mysql:query("SELECT username FROM emailaccounts WHERE username='" .. mysql:escape_string(to) .."'")
if (mysql:num_rows(result)==0) then
mysql:free_result(result)
triggerClientEvent("invalidAddress", source) -- Error Message
else
mysql:free_result(result)
mysql:query_free("INSERT INTO emails SET date= NOW(), sender='".. mysql:escape_string(accountName) .."', receiver='" .. mysql:escape_string(to) .. "', subject='" .. mysql:escape_string(subject) .. "', message='" .. mysql:escape_string(message) .. "', inbox='1', outbox='1'")
get_outbox(accountName)
triggerClientEvent("c_sendMessage",source)
end
end
addEvent("sendMessage",true)
addEventHandler("sendMessage", getRootElement(),send_message)
function delete_inbox_message(id,accountName)
mysql:query_free("UPDATE emails SET inbox=0 WHERE id='" .. mysql:escape_string(id) .."'")
mysql:query_free("DELETE FROM emails WHERE inbox='0' AND outbox='0'")
get_inbox(accountName)
end
addEvent("deleteInboxMessage",true)
addEventHandler("deleteInboxMessage", getRootElement(),delete_inbox_message)
function delete_outbox_message(id, accountName)
mysql:query_free("UPDATE emails SET outbox=0 WHERE id='" .. mysql:escape_string(id) .."'")
mysql:query_free("DELETE FROM emails WHERE inbox='0' AND outbox='0'")
get_outbox(accountName)
end
addEvent("deleteOutboxMessage",true)
addEventHandler("deleteOutboxMessage", getRootElement(),delete_outbox_message) |
--------------------------------------------- How to populate the lookup table --------------------------------------------------------------
--
--The lookup table is indexed by a string, which should match the DialogueKey value on the corresponding trigger
--The values for the lookup table are lists of tables. Each element of the list represents a line of dialogue
---Example, lookup["key"] = {line1, line2, line3}
--The supported values for the tables in the list are as follows:
--- speaker (required): Which character is speaking this line? 0 for the character on the left, 1 for the character on the right, -1 for a dialogue choice
--- text (required): A string representing the text that will be displayed as the dialogue
--- name (optional): A string representing the name we want displayed for this character.
----This only needs to be used if we want to change the name to something other than what is currently displayed
--- image (optional): A reference to the UI image asset we want to use for this character
----This only needs to be used when we want to change the image to something other than what is currently displayed
----This value also supports passing a player, in which case it will use their profile picture
--- optionA (optional): A table used when the speaker is -1, and represents the first dialogue option.
---- The corresponding button will not be displayed if this value is not set
--- optionB (optional): A table used when the speaker is -1, and represents the second dialogue option
---- The corresponding button will not be displayed if this value is not set
--- optionC (optional): A table used when the speaker is -1, and represents the third dialogue option
---- The corresponding button will not be displayed if this value is not set
--- setFlag (optional): A table used when we want to set a variable on the player for later access
---- The values for this table are:
----- flag (required): A string representing the name of the flag to set
----- value (required): An integer representing the value to set this flag to
----- addValue (required): A boolean. Set to true when you want to add to the existing value, or false when you want to overwrite any existing value
--- flagCheck (optional): A table used when we want to conditionally display the line of dialogue.
---- The values for this table are:
----- comparison (required): A function that performs a comparison on two values and returns true or false.
----- lValueKey (required): A string representing the name of the flag to use. The value of the flag will be passed as the first parameter to the comparison function
----- rValue (optional): A variable that represents a value (or values if it's a table) to compare the flag with.
------ The type of this variable should match the expected type for the second parameter in the comparison function
--The optionA, optionB, and optionC tables support the following values:
--- text (required): A string representing the text to display on the button
--- path (optional): Any branching dialogue that is specific to this option, set up the same as a normal dialogue table.
----Once this path has been traversed, the dialogue will continue along the original dialogue path
--- flagCheck (optional): A table used when we want to conditionally display certain dialogue options
----This structure should be set up the same way as the flagCheck parameter above
--------------------------------------------------------------------------------------------------------------------------------------------
lookup = {}
----------------------- Helper data structures -----------------------
----------------------------------------------------------------------
local portraitImages = {
taco = script:GetCustomProperty("TacoImage"),
bird = script:GetCustomProperty("BirdImage"),
monkey = script:GetCustomProperty("MonkeyImage"),
player = Game.GetLocalPlayer()
}
local names = {
taco = "Timmy the Taco",
bird = "Bird Boi",
monkey = "Toy Monkey",
player = "You"
}
----------------------------------------------------------------------
----------------------------------------------------------------------
------------------------ Comparison Functions ------------------------
----------------------------------------------------------------------
function GreaterThanComparison(lValue, rValue)
return lValue > rValue
end
function LessThanComparison(lValue, rValue)
return lValue < rValue
end
function GreaterThanOrEqualToComparison(lValue, rValue)
return lValue >= rValue
end
function LessThanOrEqualToComparison(lValue, rValue)
return lValue <= rValue
end
function EqualsComparison(lValue, rValue)
return lValue == rValue
end
function NotEqualsComparison(lValue, rValue)
return lValue ~= rValue
end
----------------------------------------------------------------------
----------------------------------------------------------------------
------------------------ Dialogue Tables -----------------------------
----------------------------------------------------------------------
local tacoDialogue = {
{speaker = 0, name = names.taco, image = portraitImages.taco, text = "They call me Timmy the tiny taco. Can you guess why?"},
{speaker = 1, name = names.player, image = portraitImages.player, text = "It's probably because you're a tiny taco"}
}
local birdDialogue = {
{speaker = 0, setFlag = {flag = "SpokeToBird", value = 1, addValue = false}, name = names.bird, image = portraitImages.bird,
text = "I'm a bird. I do a lot of tweeting and retweeting"
},
{speaker = 1, name = names.player, image = portraitImages.player, text = "What's your Twitter?"},
{speaker = 0, text = "@Twitter of course!"},
{speaker = -1,
optionA = {text = "...",
path = {
{speaker = 0, text = "Hello? You there?"},
{speaker = 1, text = "Why is my life like this? WHY?"},
{speaker = 0, text = "Well ok then. Bye"}
}
},
optionB = {flagCheck = {comparison = NotEqualsComparison, lValueKey = "SpokeToMonkey", rValue = 1}, text = "That's hilarious!",
path = {
{speaker = 0, text = "But I wasn't joking. The profile picture is a selfie I took after all"}
}
},
optionC = {text="Oh I already follow you",
path = {
{speaker = 0, text = "What was your favorite tweet of mine?"},
{speaker = 1, text = "Probably the one from a few weeks ago."},
{speaker = 0, text = "Oh yeah. That one was pretty great."}
}
}
},
{speaker = 1, text = "I'm glad I said that"}
}
local monkeyDialogue = {
{speaker = 1, setFlag = {flag = "SpokeToMonkey", value = 1, addValue = false}, name = names.player, image = portraitImages.player, text = "Please no monkey business from you."},
{speaker = 0, flagCheck = {comparison = EqualsComparison, lValueKey = "SpokeToBird", rValue = 1}, name = names.monkey, image = portraitImages.monkey,
text = "I see you've spoken to Bird Boi."
},
{speaker = 0, name = names.monkey, image = portraitImages.monkey, text = "I make no promises."},
{speaker = 0, text = "How do monkeys get down the stairs? They slide down the banana-ster!"}
}
----------------------------------------------------------------------
----------------------------------------------------------------------
--Here is where we actually set the values in the lookup table
lookup["Taco"] = tacoDialogue
lookup["Bird"] = birdDialogue
lookup["Monkey"] = monkeyDialogue
|
Config = {}
Config.Locale = 'fr' -- Localisation
Config.CurrencyPrefix = '$' -- Ex. $ for USD - will be in front of the price
Config.CurrencySuffix = '' -- Ex. DKK for Danish Kroner - will be behind the price, remember a space in the start.
Config.Zones = {
BikeRental = {
Enable = true, -- Enable/Disable Bike Rental
Name = _U('bikerental_blip'), -- Blip Name
DrawDistance = 10.0, -- DrawDistance lower is better! (controles how fare away you should be before the marker on the ground is drawn)
MarkerType = 25, -- Marker Type https://forum.fivem.net/t/drawmarker-pictures-for-dev/99136
ZoneSize = {x = 2.0, y = 2.0, z = 2.0}, -- Zone Size (How large the ring is)
MarkerColor = {r = 0, g = 255, b = 255}, -- Marker Color RGB
RentetMarkerColor = {r = 255, g = 0, b = 0}, -- Marker Color when bike is rentet
BlipSprite = 162, -- Map Marker Icon http://gtaxscripting.blogspot.com/2016/05/gta-v-blips-id-and-image.html
BlipScale = 0.8, -- Size of Map Marker
BlipColor = 15, -- Map Marker Color
EnableBlips = true, -- Enable/Disable Map Markers
Free = false, -- Controle if bike rental is free
Multiplier = 5, -- Multiplie the renting price, if bike is not returned (Bike Rental resets on server restart)
MenuTitle = _U('menu_title_bikerental'), -- Menu Title
ItemType = 'vehicle', -- Item Type (This one is not used currently, but is intended to be used if script is expanded)
MenuActions = {
MenuTrigger = 'bikerental_menu', -- Menu Trigger
MenuMessage = _U('press_bikerental_menu'), -- Menu Help Text
},
Items = { -- Item, label, and price used for the menu
{item = 'BMX', label = 'BMX Cykel', price = 10},
{item = 'CRUISER', label = 'Cruiser Cykel', price = 10},
{item = 'FIXTER', label = 'Racercykel', price = 10},
{item = 'SCORCHER', label = 'Mountainbike', price = 10},
{item = 'TRIBIKE', label = 'Triathlon Cykel 1', price = 10},
{item = 'TRIBIKE2', label = 'Triathlon Cykel 2', price = 10},
{item = 'TRIBIKE3', label = 'Triathlon Cykel 3', price = 10},
},
Pos = { -- Zone positions
{x = -246.980, y = -339.820, z = 29.000},
{x = -1085.78, y = -263.01, z = 36.80},
{x = -1262.36, y = -1438.98, z = 3.45},
{x = -248.95, y = -1528.82, z = 30.62},
{x = 1808.5, y = 3676.96, z = 33.31},
{x = -839.99, y = 5402.05, z = 33.64}
}
},
Basejumping = {
Enable = true, -- Enable/Disable Basejumping
Name = _U('basejumping_blip'), -- Blip Name
DrawDistance = 10.0, -- DrawDistance lower is better! (controles how fare away you should be before the marker on the ground is drawn)
MarkerType = 25, -- Marker Type https://forum.fivem.net/t/drawmarker-pictures-for-dev/99136
ZoneSize = {x = 2.0, y = 2.0, z = 2.0}, -- Zone Size (How large the ring is)
MarkerColor = {r = 255, g = 168, b = 0}, -- Marker Color RGB
BlipSprite = 94, -- Map Marker Icon http://gtaxscripting.blogspot.com/2016/05/gta-v-blips-id-and-image.html
BlipScale = 0.8, -- Size of Map Marker
BlipColor = 81, -- Map Marker Color
EnableBlips = true, -- Enable/Disable Map Markers
Free = false, -- Controle if bike rental is free
MenuTitle = _U('menu_title_basejumping'), -- Menu Title
ItemType = 'weapon', -- Item Type (Is in use dont change or it will break)
MenuActions = {
MenuTrigger = 'basejumping_menu', -- Menu Trigger
MenuMessage = _U('press_basejumping_menu'), -- Menu Help Text
},
Items = { -- Item, label, and price used for the menu
{item = 'GADGET_PARACHUTE', label = 'Faldskærm', price = 75},
},
Pos = { -- Zone positions
{x = 451.45, y = 5587.85, z = 780.23},
{x = -1136.27, y = 4659.88, z = 243.02},
{x = 1665.17, y = -28.0, z = 195.97},
{x = -119.97, y = -977.51, z = 303.41},
{x = -543.86, y = -2226.02, z = 121.44},
},
TelePos = { -- Basejump TP locations (used to launch the player for basejumping)
{x = 446.74, y = 5587.83, z = 791.2, h = 85.5},
{x = -1146.22, y = 4660.92, z = 243.89, h = 88.5},
{x = 1659.71, y = -29.39, z = 196.93, h = 103.5},
{x = -118.81, y = -979.88, z = 304.24, h = 207.5},
{x = -539.62, y = -2228.61, z = 122.36, h = 237.5},
}
}
}
|
--点晴大兽-Cyclogic
local m=14000043
local cm=_G["c"..m]
cm.named_with_another=1
function cm.initial_effect(c)
--SpecialSummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(m,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_REMOVE)
e1:SetRange(LOCATION_REMOVED)
e1:SetCondition(cm.spcon)
e1:SetTarget(cm.sptg)
e1:SetOperation(cm.spop)
c:RegisterEffect(e1)
--lp Recover
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(m,1))
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetRange(LOCATION_REMOVED)
e2:SetCondition(cm.lpcon)
e2:SetOperation(cm.lpop)
c:RegisterEffect(e2)
end
function cm.ANOTHER(c)
local m=_G["c"..c:GetCode()]
return m and m.named_with_another
end
function cm.rfilter(c)
return cm.ANOTHER(c) and c:IsFaceup() and not c:IsCode(m)
end
function cm.spcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(cm.rfilter,1,nil,tp)
end
function cm.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function cm.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
if Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)~=0 then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_REDIRECT)
e1:SetValue(LOCATION_REMOVED)
c:RegisterEffect(e1,true)
Duel.BreakEffect()
local g1=Duel.GetMatchingGroup(cm.cfilter,tp,LOCATION_REMOVED,0,nil)
local ct=g1:GetCount()
if ct>0 then
Duel.SetLP(tp,Duel.GetLP(tp)-ct*800)
end
end
end
end
function cm.cfilter(c)
return cm.ANOTHER(c) and c:IsFaceup()
end
function cm.lpcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFlagEffect(tp,14000041)==0 and e:GetHandler():IsFaceup()
end
function cm.lpop(e,tp,eg,ep,ev,re,r,rp)
Duel.RegisterFlagEffect(tp,14000041,RESET_PHASE+PHASE_END,0,1)
Duel.Hint(HINT_CARD,0,m)
local g=Duel.GetFieldGroup(tp,LOCATION_REMOVED,0)
local ct=Duel.SendtoDeck(g,nil,2,REASON_EFFECT)
if ct>0 then
Duel.Recover(tp,ct*400,REASON_EFFECT)
end
end |
local M = {}
local selector = require 'lumen.tasks.selector'
local sched = require 'lumen.sched'
local log = require 'lumen.log'
local function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
M.new = function(conf)
local encoder_lib = require( conf.encoder or 'lumen.lib.dkjson')
conf.encode_f = conf.encode_f or encoder_lib.encode
conf.decode_f = conf.decode_f or encoder_lib.decode
local encode_f = conf.encode_f
local decode_f = conf.decode_f
local ivs = assert(loadfile (script_path()..'lib/inventory_view_sets.lua'))()
--M.conf = conf
local rong = setmetatable({
conf = conf,
signals = loadfile (script_path()..'lib/signals.lua')(),
inv = ivs.inv,
view = ivs.view,
}, {
__index = M,
})
local messages = assert(require ('rong.messages.'..conf.protocol)).new(rong)
rong.messages = messages
local incomming_handler = function (data, err)
if data then
--log('RONG', 'DEBUG', 'Incomming: %s', tostring(data))
local m = assert(decode_f(data))
for k, v in pairs(m) do
if messages.incomming[k] then
--log('RONG', 'DEBUG', ' Incomming found: %s', tostring(k))
messages.incomming[k] (rong, v)
else
log('RONG', 'WARN', ' Incomming unknown: %s', tostring(k))
end
end
--[[
if m.view then
process_incoming_view(rong, m)
elseif m.messages then
elseif m.subscribe then
elseif m.subrequest then
end
--]]
else
log('RONG', 'WARN', 'Incomming error: %s', tostring(err))
end
return true
end
rong.net = require 'rong.lib.networking'.new(rong, incomming_handler)
rong.pending = require 'rong.lib.pending'.new(rong)
-- start tasks
--rong.broadcast_listener_task = sched.sigrun(
-- { rong.signals.broadcast_view },
-- function() messages:broadcast_view() end
--)
rong.broadcast_view_task = sched.run(
function ()
local timeout = conf.send_views_timeout
local spread = 0.1
local spread_2 = spread / 2
while true do
--sched.signal( rong.signals.broadcast_view )
messages:broadcast_view()
sched.sleep( timeout + (spread*math.random()-spread_2)*timeout )
end
end
)
M.subscribe = function (rong, sid, filter)
sid = sid or 'sid:'..math.random(2^31)
--subscriptions:add(sid,{subscription_id=sid, filter=s.filter, p_encounter=p_encounter,
--last_seen=t, ts=t, cached_template=parser.build_subscription_template(s),own=skt})
log('RONG', 'INFO', 'Publishing subscription: "%s"',
tostring(sid))
rong.view:add(sid, filter, true)
messages.init_subscription(sid)
if messages.message_scan_for_delivery then
messages.message_scan_for_delivery()
end
log('RONG', 'INFO', ' subscriptions: %i', rong.view:len())
return rong.view[sid]
end
M.update_subscription = function (rong, sid, filter)
if not sid then return nil, 'Missing sid for update' end
log('RONG', 'INFO', 'Updating subscription: "%s"',
tostring(sid))
rong.view:update(sid, filter, true)
--messages.init_subscription(sid)
if messages.message_scan_for_delivery then
messages.message_scan_for_delivery()
end
return rong.view[sid]
end
M.notificate = function (rong, nid, data)
nid = nid or 'nid:'..math.random(2^31)
log('RONG', 'INFO', 'Publishing notification: "%s"',
tostring(nid))
rong.inv:add(nid, data, true)
local entry = messages.init_notification(nid)
if messages.message_scan_for_delivery then
messages.message_scan_for_delivery()
end
log('RONG', 'INFO', ' notifications: %i', rong.inv:len())
return entry
end
log('RONG', 'INFO', 'Library instance initialized: %s', tostring(rong))
return rong
end
return M |
local Tools={
CurrentSortItem = nil,
}
AAH.Tools=Tools
function AAHDebug(msg)
--[===[@alpha@
DEFAULT_CHAT_FRAME:AddMessage(msg)
--@end-alpha@]===]
end
function Tools.SortBidLess(item1, item2)
if item1.bidPrice == item2.bidPrice then
return item1.auctionid < item2.auctionid
end
return item1.bidPrice < item2.bidPrice
end
function Tools.SortBidMore(item1, item2)
return not Tools.SortBidLess(item1, item2)
end
function Tools.SortBuyoutLess(item1, item2)
if item1.buyoutPrice == 0 then
if item2.buyoutPrice == 0 then
return Tools.SortBidLess(item1, item2)
end
return false
elseif item2.buyoutPrice == 0 then
return true
else
if item1.buyoutPrice == item2.buyoutPrice then
return item1.auctionid < item2.auctionid
end
return item1.buyoutPrice < item2.buyoutPrice
end
end
function Tools.SortBuyoutMore(item1, item2)
return Tools.SortBuyoutLess(item2, item1)
end
function Tools.SortBidPPULess(item1, item2)
local white1 = Tools.GetWhiteValue(item1.name)
local white2 = Tools.GetWhiteValue(item2.name)
local PPU1 = item1.bidppu or (item1.bidPrice / item1.count)
local PPU2 = item2.bidppu or (item2.bidPrice / item2.count)
local v1 = PPU1/white1
local v2 = PPU2/white2
if v1==v2 then
return item1.auctionid < item2.auctionid
end
return v1 < v2
end
function Tools.SortBidPPUMore(item1, item2)
return not Tools.SortBidPPULess(item1, item2)
end
function Tools.SortBuyoutPPULess(item1, item2)
if item1.buyoutPrice == 0 then
if item2.buyoutPrice == 0 then
return Tools.SortBidLess(item1, item2)
end
return false
elseif item2.buyoutPrice == 0 then
return true
else
local white1 = Tools.GetWhiteValue(item1.name)
local white2 = Tools.GetWhiteValue(item2.name)
local PPU1 = item1.buyppu or (item1.buyoutPrice / item1.count)
local PPU2 = item2.buyppu or (item2.buyoutPrice / item2.count)
local v1 = PPU1/white1
local v2 = PPU2/white2
if v1==v2 then
return item1.auctionid < item2.auctionid
end
return v1 < v2
end
end
function Tools.SortBuyoutPPUMore(item1, item2)
return Tools.SortBuyoutPPULess(item2, item1)
end
function Tools.SortLess(item1, item2)
if Tools.CurrentSortItem == "status" then
if item1[Tools.CurrentSortItem] == false and item2[Tools.CurrentSortItem] == true then
return true
else
return false
end
elseif Tools.CurrentSortItem == "seller" or Tools.CurrentSortItem == "bidder" then
return Tools.StringLower(item1[Tools.CurrentSortItem]) < Tools.StringLower(item2[Tools.CurrentSortItem])
elseif Tools.CurrentSortItem == "name" then
for _, id in pairs({200000, 200003}) do
local count1, name1 = item1[Tools.CurrentSortItem]:gsub("%"..COMMA, ""):match("(%d*) "..TEXT("Sys"..id.."_name_plural").."$")
local count2, name2 = item2[Tools.CurrentSortItem]:gsub("%"..COMMA, ""):match("(%d*) "..TEXT("Sys"..id.."_name_plural").."$")
if count1 and count2 then
return tonumber(count1) < tonumber(count2)
end
end
return item1[Tools.CurrentSortItem]:gsub("%"..COMMA, "") < item2[Tools.CurrentSortItem]:gsub("%"..COMMA, "")
else
return item1[Tools.CurrentSortItem] < item2[Tools.CurrentSortItem]
end
end
function Tools.SortMore(item1, item2)
if Tools.CurrentSortItem == "status" then
if item1[Tools.CurrentSortItem] == true and item2[Tools.CurrentSortItem] == false then
return true
else
return false
end
elseif Tools.CurrentSortItem == "seller" or Tools.CurrentSortItem == "bidder" then
return Tools.StringLower(item1[Tools.CurrentSortItem]) > Tools.StringLower(item2[Tools.CurrentSortItem])
elseif Tools.CurrentSortItem == "name" then
for _, id in pairs({200000, 200003}) do
local count1, name1 = item1[Tools.CurrentSortItem]:gsub("%"..COMMA, ""):match("(%d*) "..TEXT("Sys"..id.."_name_plural").."$")
local count2, name2 = item2[Tools.CurrentSortItem]:gsub("%"..COMMA, ""):match("(%d*) "..TEXT("Sys"..id.."_name_plural").."$")
if count1 and count2 then
return tonumber(count1) > tonumber(count2)
end
end
return item1[Tools.CurrentSortItem]:gsub("%"..COMMA, "") > item2[Tools.CurrentSortItem]:gsub("%"..COMMA, "")
else
return item1[Tools.CurrentSortItem] > item2[Tools.CurrentSortItem]
end
end
function Tools.CalcBidPrice(money)
local price = math.floor(money * 1.05)
if price == money then
price = price + 1
end
return price
end
function Tools.LunaReceive(Name, Message)
--@non-alpha@
if string.find(Message, "Build: [%d]+") then
if AAH.Manifest.Build < tonumber(string.match(Message, "[%d]+")) and not AAH.Updated then
DEFAULT_CHAT_FRAME:AddMessage(AAHLocale.Messages.LUNA_NEW_VERSION_FOUND)
AAH.Updated = true
end
end
--@end-non-alpha@
end
function Tools.LocalTimeString(leftTime)
local days, hours, minutes
local temptime
days = math.floor(leftTime / 1440)
temptime = leftTime - (days * 1440)
hours = string.format("%2s", math.floor(temptime / 60))
temptime = temptime - (hours * 60)
minutes = string.format("%02s", temptime)
if days == 0 then
days = " "
else
hours = string.format("%02d", hours)
days = days..AAHLocale.Messages.TOOLS_DAY_ABV
end
if days == " " and hours == 0 then
hours = " "
else
hours = hours..AAHLocale.Messages.TOOLS_HOUR_ABV
end
return days.." "..hours.." "..minutes..AAHLocale.Messages.TOOLS_MIN_ABV
end
function Tools.EvaluateString(str)
str = string.gsub(str, ",", ".")
local func, _error = loadstring("return " .. str, str)
if _error then return _error end
local _,result = pcall( func, str )
return result
end
function Tools.ChatEdit_AddItemLink(ItemLink, insert_in_self)
if ItemLink == nil then
return
end
if ITEMLINK_EDITBOX ~= nil then
ITEMLINK_EDITBOX:InsertText(ItemLink)
return true
elseif insert_in_self and AAH_AuctionFrame:IsVisible() and AAH_BrowseFrame:IsVisible() then
local _type, _data, _name = ParseHyperlink(ItemLink)
AAH_BrowseNameEditBox:SetText(_name)
return true
else
local editbox = GetKeyboardFocus()
if editbox then
local _type, _data, _name = ParseHyperlink(ItemLink)
editbox:InsertText(_name)
return true
end
end
return false
end
function Tools.GetVendorPrice()
local temp
for i = 1, 40 do
local label = getglobal("AAH_TooltipTextLeft"..i)
if label:IsVisible() then
temp = label:GetText()
if temp and string.find(temp, TEXT("SYS_ITEM_COST")) then
temp = string.gsub(temp, COMMA, "")
return tonumber(string.match(temp, "%d+"))
end
end
end
return nil
end
function Tools.SetDropDown(frame, id, name, color)
if name then
getglobal(frame:GetName().."Text"):SetText(name)
if color then
getglobal(frame:GetName().."Text"):SetColor(color[1], color[2], color[3])
end
end
if id then
frame.selectedID = id
end
end
function Tools.ParseLink(link)
local data, name
if link and link ~= "" then
_, data, name = ParseHyperlink(link)
if data then
return tonumber(string.sub(data, 1, 5), 16), name
else
AAHDebug("ToolsParseLink: Bad Link: link = "..link)
end
end
return nil, nil
end
function Tools.ClickPlayerName(this, key)
local Seller = this:GetText()
if Seller == nil or Seller == "" then return end
Hyperlink_Assign(string.format("|Hplayer:%s|h[%s]|h", Seller, Seller), key)
end
function Tools.FormatDynDecimals(number)
if type(number) ~= "number" then
AAHDebug("ToolsDynamicDecimalPlaces: Bad number")
return 0
elseif number < 0 then
return 0
elseif number < 0.001 then
return tonumber(string.format("%.6f", number))
elseif number < 0.01 then
return tonumber(string.format("%.5f", number))
elseif number < 0.1 then
return tonumber(string.format("%.4f", number))
elseif number < 1 then
return tonumber(string.format("%.3f", number))
elseif number < 10 then
return tonumber(string.format("%.2f", number))
elseif number < 100 then
return tonumber(string.format("%.1f", number))
else
return tonumber(string.format("%.0f", number))
end
end
function Tools.FormatNumber(num)
if num < 1 and num > -1 and num ~= 0 then
return string.format("%.15f",num):gsub("0+$",""):gsub("%.",AAHLocale.Messages.GENERAL_DECIMAL_POINT)
end
local n = Tools.FormatDynDecimals(num)
return Tools.FormatThousands(n)
end
function Tools.FormatForceDecimals(num)
if num < 1 and num > -1 and num ~= 0 then
return string.format("%.15f",num):gsub("0+$","")
end
return num
end
function Tools.FormatThousands(number)
local left,num,right = string.match(tostring(number),'^([^%d]*%d)(%d*)(.-)$')
num = num:reverse():gsub('(%d%d%d)','%1'..COMMA)
right = right:gsub("^%.",AAHLocale.Messages.GENERAL_DECIMAL_POINT)
return left..(num:reverse())..right
end
function Tools.ParseMoney(t)
t = string.gsub(t,"%"..COMMA,"")
t = string.gsub(t,"%"..AAHLocale.Messages.GENERAL_DECIMAL_POINT,".")
if string.find(t,"e[%+%-%d]*$") then
return tonumber(t)
end
local _,_,v,k = string.find(t,"^(.-)([kK]+)$")
if k then
t=v * math.pow(10, k:len()*3)
end
local _,_,v,k = string.find(t,"^(.-)([mM]+)$")
if k then
t=v * math.pow(10, k:len()*6)
end
return tonumber(t)
end
function Tools.IsValidMoneyFormat(t)
t = string.match(t,"^%s*(.*)%s*$")
-- misplaced thousend point
if string.find(t,"%"..COMMA.."%d[^%d]") or
string.find(t,"%"..COMMA.."%d%d[^%d]") or
string.find(t,"%"..COMMA.."%d$") or
string.find(t,"%"..COMMA.."%d%d$") then return false end
-- illegal ending
if string.find(t,"[^%d^k^K^m^M]$") then return false end
-- multiple decimal points
if string.find(t,"%"..AAHLocale.Messages.GENERAL_DECIMAL_POINT..".*[%"..AAHLocale.Messages.GENERAL_DECIMAL_POINT.."%"..COMMA.."]") then return false end
return Tools.ParseMoney(t)
end
function Tools.SetSortIcon(frame, icon)
if icon == 0 then
frame:SetFile("Interface\\AddOns\\AdvancedAuctionhouse\\Textures\\full_arrow_up")
elseif icon== 1 then
frame:SetFile("Interface\\AddOns\\AdvancedAuctionhouse\\Textures\\full_arrow_down")
elseif icon == 2 then
frame:SetFile("Interface\\AddOns\\AdvancedAuctionhouse\\Textures\\hollow_arrow_up")
elseif icon == 3 then
frame:SetFile("Interface\\AddOns\\AdvancedAuctionhouse\\Textures\\hollow_arrow_down")
else
frame:SetFile("")
end
end
function Tools.GetWhiteValue(itemid)
if AAH_SavedSettings.UseMatWhiteValue then
return AAH.Data.MatWhiteValue[itemid] or 1
else
return 1
end
end
local Gradient = {
-- value r g b a
{0.50, 0.0, 1.0, 0.5, 1.0},
{0.75, 0.0, 1.0, 0.0, 1.0},
{1.00, 1.0, 1.0, 1.0, 1.0},
{1.50, 1.0, 1.0, 0.0, 1.0},
{2.00, 1.0, 0.0, 0.0, 1.0},
}
local InvGradient = {
-- value r g b a
{2.00, 0.0, 1.0, 0.5, 1.0},
{1.50, 0.0, 1.0, 0.0, 1.0},
{1.00, 1.0, 1.0, 1.0, 1.0},
{0.75, 1.0, 1.0, 0.0, 1.0},
{0.50, 1.0, 0.0, 0.0, 1.0},
}
function Tools.GetAvgPriceColorNew(price, average, widget, inverse)
if inverse then
getglobal(widget):SetColor(Tools.ColFromGradient(price/average, InvGradient))
else
getglobal(widget):SetColor(Tools.ColFromGradient(price/average, Gradient))
end
end
function Tools.GetAvgPriceColorOld(price, average, widget, inverse)
local buyPPUColor = 0
if inverse then
if price / average < 1 then
buyPPUColor = price / average
getglobal(widget):SetColor(1,buyPPUColor,buyPPUColor)
else
buyPPUColor = 2 - math.min(price / average, 2)
getglobal(widget):SetColor(buyPPUColor,1,buyPPUColor)
end
else
if price / average < 1 then
buyPPUColor = price / average
getglobal(widget):SetColor(buyPPUColor,1,buyPPUColor)
else
buyPPUColor = 2 - math.min(price / average, 2)
getglobal(widget):SetColor(1,buyPPUColor,buyPPUColor)
end
end
end
--Make new function the working one (A config option to activate the old one might follow if people don't like it)
Tools.GetAvgPriceColor = Tools.GetAvgPriceColorNew
function Tools.FindColorType(r, g, b)
if r == 1 and g == 1 and b == 1 then
return "white"
elseif r == 0 and g == 1 and b == 0 then
return "green"
elseif r == 1 and g == 1 and b == 0 then
return "yellow"
elseif r == 1 and g == 0 and b == 0 then
return "red"
elseif string.format("%.2f", r) == "0.94" and string.format("%.2f", g) == "0.38" and string.format("%.2f", b) == "0.05" then
return "orange"
elseif string.format("%.2f", r) == "0.74" and string.format("%.2f", g) == "0.18" and string.format("%.2f", b) == "1.00" then
return "rune"
elseif string.format("%.2f", r) == "0.62" and string.format("%.2f", g) == "0.46" and string.format("%.2f", b) == "0.30" then
return "set"
else
return "other"
end
end
-- Copyright notice: This function has been copied BY NOGUAI! from ZZLibrary.
function Tools.ColFromGradient(val, gradient)
--Return white on missing parameter
if not val or not gradient then return 1, 1, 1, 1 end
--Sort gradient table
table.sort(gradient, function(a,b) return a[1] < b[1] end)
--Return color on gradients border if value exceeds one
if val <= gradient[1][1] then return gradient[1][2], gradient[1][3], gradient[1][4], gradient[1][5] end
if val >= gradient[#gradient][1] then return gradient[#gradient][2], gradient[#gradient][3], gradient[#gradient][4], gradient[#gradient][5] end
for i = 1, #gradient-1 do
--find nearest gradient points
if val >= gradient[i][1] and val <= gradient[i+1][1] then
--load differences
local temp = {}
for j = 1, 5 do
temp[j] = gradient[i+1][j] - gradient[i][j]
end
--calculate relative position
local pct = (val - gradient[i][1]) / temp[1]
--calculate new color
for j = 2, 5 do
temp[j] = gradient[i][j] + (temp[j] * pct)
end
--return color
return temp[2], temp[3], temp[4], temp[5]
end
end
end
function Tools.StringLower(text)
local convert = {
["Ä"] = "ä",
["Ö"] = "ö",
["Ü"] = "ü",
}
text = string.lower(text)
for u, l in pairs(convert) do
text = string.gsub(text, u, l)
end
return text
end |
module 'belua' {
lib {
define 'BE_BELUA_IMPL',
link_project 'luaxx',
link_project 'core'
}
}
|
function love.load()
auth = require "lib/auth"
login = require "bin/login"
process = require "lib/process"
sha256 = require "lib/sha256"
end
function love.update()
process.update()
end
function love.draw()
windowCanvases = process.renderCanvases()
window.drawWindows(windowCanvases)
end
|
local Prop = {}
Prop.Name = "Nº401 Rua do Trabalhador"
Prop.Cat = "House"
Prop.Price = 340
Prop.Doors = {
Vector(-818, -1363, -142),
}
GM.Property:Register( Prop ) |
require 'torch'
left = torch.FloatTensor(torch.FloatStorage('../left.bin')):view(1, 70, 370, 1226)
right = torch.FloatTensor(torch.FloatStorage('../right.bin')):view(1, 70, 370, 1226)
disp = torch.FloatTensor(torch.FloatStorage('../disp.bin')):view(1, 1, 370, 1226)
|
local lshift = bit32.lshift
local band = bit32.band
function apply(opcodes, opcode_cycles, z80, memory)
local reg = z80.registers
local flags = reg.flags
local read_byte = memory.read_byte
local write_byte = memory.write_byte
set_inc_flags = function(value)
flags.z = value == 0
flags.h = value % 0x10 == 0x0
flags.n = false
end
set_dec_flags = function(value)
flags.z = value == 0
flags.h = value % 0x10 == 0xF
flags.n = true
end
-- inc r
opcodes[0x04] = function() reg.b = band(reg.b + 1, 0xFF); set_inc_flags(reg.b) end
opcodes[0x0C] = function() reg.c = band(reg.c + 1, 0xFF); set_inc_flags(reg.c) end
opcodes[0x14] = function() reg.d = band(reg.d + 1, 0xFF); set_inc_flags(reg.d) end
opcodes[0x1C] = function() reg.e = band(reg.e + 1, 0xFF); set_inc_flags(reg.e) end
opcodes[0x24] = function() reg.h = band(reg.h + 1, 0xFF); set_inc_flags(reg.h) end
opcodes[0x2C] = function() reg.l = band(reg.l + 1, 0xFF); set_inc_flags(reg.l) end
opcode_cycles[0x34] = 12
opcodes[0x34] = function()
write_byte(reg.hl(), band(read_byte(reg.hl()) + 1, 0xFF))
set_inc_flags(read_byte(reg.hl()))
end
opcodes[0x3C] = function() reg.a = band(reg.a + 1, 0xFF); set_inc_flags(reg.a) end
-- dec r
opcodes[0x05] = function() reg.b = band(reg.b - 1, 0xFF); set_dec_flags(reg.b) end
opcodes[0x0D] = function() reg.c = band(reg.c - 1, 0xFF); set_dec_flags(reg.c) end
opcodes[0x15] = function() reg.d = band(reg.d - 1, 0xFF); set_dec_flags(reg.d) end
opcodes[0x1D] = function() reg.e = band(reg.e - 1, 0xFF); set_dec_flags(reg.e) end
opcodes[0x25] = function() reg.h = band(reg.h - 1, 0xFF); set_dec_flags(reg.h) end
opcodes[0x2D] = function() reg.l = band(reg.l - 1, 0xFF); set_dec_flags(reg.l) end
opcode_cycles[0x35] = 12
opcodes[0x35] = function()
write_byte(reg.hl(), band(read_byte(reg.hl()) - 1, 0xFF))
set_dec_flags(read_byte(reg.hl()))
end
opcodes[0x3D] = function() reg.a = band(reg.a - 1, 0xFF); set_dec_flags(reg.a) end
end
return apply
|
-- loading.lua
-- Copyright (c) 2018 Jon Thysell
local game = require "game"
local Splash = game.Game:new({
id = "splash",
title = "RetroLove 1.0.0",
caption = "Made with LÖVE",
timeRemaining = 2.0,
})
function Splash:initGame()
self.logo = love.graphics.newImage("logo.png")
end
function Splash:updateGame(dt, input)
self.timeRemaining = self.timeRemaining - dt
if self.timeRemaining <= 0 then
self:exit()
end
end
function Splash:drawGame(dt, input)
local font = love.graphics.getFont()
love.graphics.setColor({255, 255, 255, 255})
local logoImage = self.logo
love.graphics.draw(logoImage, (self.resWidth - logoImage:getWidth()) / 2, (self.resHeight - logoImage:getHeight()) * 0.5)
local titleText = tostring(self.title)
love.graphics.print(titleText, (self.resWidth - font:getWidth(titleText)) / 2, (self.resHeight - font:getHeight(titleText)) * 0.1)
local captionText = tostring(self.caption)
love.graphics.print(captionText, (self.resWidth - font:getWidth(captionText)) / 2, (self.resHeight - font:getHeight(captionText)) * 0.9)
-- Draw Debug Info
if self.debugMode then
local fpsText = "FPS: "..tostring(love.timer.getFPS())
love.graphics.print(fpsText, self.resWidth - (font:getWidth(fpsText) + self.margin / 4), self.resHeight - self.margin + ((self.margin - font:getHeight(fpsText)) / 2))
end
end
function Splash:exitGame()
return self.nextGame
end
return {
Splash = Splash
} |
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3
local class = require("class")
require("kaitaistruct")
local enum = require("enum")
local stringstream = require("string_stream")
local str_decode = require("string_decode")
--
-- Python interpreter runs .py files in 2 step process: first, it
-- produces bytecode, which it then executes. Translation of .py source
-- into bytecode is time-consuming, so Python dumps compiled bytecode
-- into .pyc files, to be reused from cache at later time if possible.
--
-- .pyc file is essentially a raw dump of `py_object` (see `body`) with
-- a simple header prepended.
PythonPyc27 = class.class(KaitaiStruct)
PythonPyc27.Version = enum.Enum {
v15 = 20121,
v16 = 50428,
v20 = 50823,
v21 = 60202,
v22 = 60717,
v23_a0 = 62011,
v23_a0b = 62021,
v24_a0 = 62041,
v24_a3 = 62051,
v24_b1 = 62061,
v25_a0 = 62071,
v25_a0b = 62081,
v25_a0c = 62091,
v25_a0d = 62092,
v25_b3 = 62101,
v25_b3b = 62111,
v25_c1 = 62121,
v25_c2 = 62131,
v26_a0 = 62151,
v26_a1 = 62161,
v27_a0 = 62171,
v27_a0b = 62181,
v27_a0c = 62191,
v27_a0d = 62201,
v27_a0e = 62211,
}
function PythonPyc27:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27:_read()
self.version_magic = PythonPyc27.Version(self._io:read_u2le())
self.crlf = self._io:read_u2le()
self.modification_timestamp = self._io:read_u4le()
self.body = PythonPyc27.PyObject(self._io, self, self._root)
end
PythonPyc27.CodeObject = class.class(KaitaiStruct)
PythonPyc27.CodeObject.FlagsEnum = enum.Enum {
has_args = 4,
has_kwargs = 8,
generator = 32,
}
function PythonPyc27.CodeObject:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.CodeObject:_read()
self.arg_count = self._io:read_u4le()
self.local_count = self._io:read_u4le()
self.stack_size = self._io:read_u4le()
self.flags = PythonPyc27.CodeObject.FlagsEnum(self._io:read_u4le())
self.code = PythonPyc27.Assembly(self._io, self, self._root)
self.consts = PythonPyc27.PyObject(self._io, self, self._root)
self.names = PythonPyc27.PyObject(self._io, self, self._root)
self.var_names = PythonPyc27.PyObject(self._io, self, self._root)
self.free_vars = PythonPyc27.PyObject(self._io, self, self._root)
self.cell_vars = PythonPyc27.PyObject(self._io, self, self._root)
self.filename = PythonPyc27.PyObject(self._io, self, self._root)
self.name = PythonPyc27.PyObject(self._io, self, self._root)
self.first_line_no = self._io:read_u4le()
self.lnotab = PythonPyc27.PyObject(self._io, self, self._root)
end
PythonPyc27.Assembly = class.class(KaitaiStruct)
function PythonPyc27.Assembly:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.Assembly:_read()
self.string_magic = self._io:read_bytes(1)
if not(self.string_magic == "\115") then
error("not equal, expected " .. "\115" .. ", but got " .. self.string_magic)
end
self.length = self._io:read_u4le()
self._raw_items = self._io:read_bytes(self.length)
local _io = KaitaiStream(stringstream(self._raw_items))
self.items = PythonPyc27.OpArgs(_io, self, self._root)
end
PythonPyc27.OpArg = class.class(KaitaiStruct)
PythonPyc27.OpArg.OpCodeEnum = enum.Enum {
stop_code = 0,
pop_top = 1,
rot_two = 2,
rot_three = 3,
dup_top = 4,
rot_four = 5,
nop = 9,
unary_positive = 10,
unary_negative = 11,
unary_not = 12,
unary_convert = 13,
unary_invert = 15,
binary_power = 19,
binary_multiply = 20,
binary_divide = 21,
binary_modulo = 22,
binary_add = 23,
binary_subtract = 24,
binary_subscr = 25,
binary_floor_divide = 26,
binary_true_divide = 27,
inplace_floor_divide = 28,
inplace_true_divide = 29,
slice_0 = 30,
slice_1 = 31,
slice_2 = 32,
slice_3 = 33,
store_slice_0 = 40,
store_slice_1 = 41,
store_slice_2 = 42,
store_slice_3 = 43,
delete_slice_0 = 50,
delete_slice_1 = 51,
delete_slice_2 = 52,
delete_slice_3 = 53,
store_map = 54,
inplace_add = 55,
inplace_subtract = 56,
inplace_multiply = 57,
inplace_divide = 58,
inplace_modulo = 59,
store_subscr = 60,
delete_subscr = 61,
binary_lshift = 62,
binary_rshift = 63,
binary_and = 64,
binary_xor = 65,
binary_or = 66,
inplace_power = 67,
get_iter = 68,
print_expr = 70,
print_item = 71,
print_newline = 72,
print_item_to = 73,
print_newline_to = 74,
inplace_lshift = 75,
inplace_rshift = 76,
inplace_and = 77,
inplace_xor = 78,
inplace_or = 79,
break_loop = 80,
with_cleanup = 81,
load_locals = 82,
return_value = 83,
import_star = 84,
exec_stmt = 85,
yield_value = 86,
pop_block = 87,
end_finally = 88,
build_class = 89,
store_name = 90,
delete_name = 91,
unpack_sequence = 92,
for_iter = 93,
list_append = 94,
store_attr = 95,
delete_attr = 96,
store_global = 97,
delete_global = 98,
dup_topx = 99,
load_const = 100,
load_name = 101,
build_tuple = 102,
build_list = 103,
build_set = 104,
build_map = 105,
load_attr = 106,
compare_op = 107,
import_name = 108,
import_from = 109,
jump_forward = 110,
jump_if_false_or_pop = 111,
jump_if_true_or_pop = 112,
jump_absolute = 113,
pop_jump_if_false = 114,
pop_jump_if_true = 115,
load_global = 116,
continue_loop = 119,
setup_loop = 120,
setup_except = 121,
setup_finally = 122,
load_fast = 124,
store_fast = 125,
delete_fast = 126,
raise_varargs = 130,
call_function = 131,
make_function = 132,
build_slice = 133,
make_closure = 134,
load_closure = 135,
load_deref = 136,
store_deref = 137,
call_function_var = 140,
call_function_kw = 141,
call_function_var_kw = 142,
setup_with = 143,
extended_arg = 145,
set_add = 146,
map_add = 147,
}
function PythonPyc27.OpArg:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.OpArg:_read()
self.op_code = PythonPyc27.OpArg.OpCodeEnum(self._io:read_u1())
if self.op_code.value >= PythonPyc27.OpArg.OpCodeEnum.store_name.value then
self.arg = self._io:read_u2le()
end
end
PythonPyc27.PyObject = class.class(KaitaiStruct)
PythonPyc27.PyObject.ObjectType = enum.Enum {
tuple = 40,
py_false = 70,
none = 78,
string_ref = 82,
py_true = 84,
code_object = 99,
int = 105,
string = 115,
interned = 116,
unicode_string = 117,
}
function PythonPyc27.PyObject:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.PyObject:_read()
self.type = PythonPyc27.PyObject.ObjectType(self._io:read_u1())
local _on = self.type
if _on == PythonPyc27.PyObject.ObjectType.string then
self.value = PythonPyc27.PyObject.PyString(self._io, self, self._root)
elseif _on == PythonPyc27.PyObject.ObjectType.tuple then
self.value = PythonPyc27.PyObject.Tuple(self._io, self, self._root)
elseif _on == PythonPyc27.PyObject.ObjectType.int then
self.value = self._io:read_u4le()
elseif _on == PythonPyc27.PyObject.ObjectType.py_true then
self.value = PythonPyc27.PyObject.PyTrue(self._io, self, self._root)
elseif _on == PythonPyc27.PyObject.ObjectType.py_false then
self.value = PythonPyc27.PyObject.PyFalse(self._io, self, self._root)
elseif _on == PythonPyc27.PyObject.ObjectType.none then
self.value = PythonPyc27.PyObject.PyNone(self._io, self, self._root)
elseif _on == PythonPyc27.PyObject.ObjectType.string_ref then
self.value = PythonPyc27.PyObject.StringRef(self._io, self, self._root)
elseif _on == PythonPyc27.PyObject.ObjectType.code_object then
self.value = PythonPyc27.CodeObject(self._io, self, self._root)
elseif _on == PythonPyc27.PyObject.ObjectType.interned then
self.value = PythonPyc27.PyObject.InternedString(self._io, self, self._root)
end
end
PythonPyc27.PyObject.PyNone = class.class(KaitaiStruct)
function PythonPyc27.PyObject.PyNone:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.PyObject.PyNone:_read()
end
PythonPyc27.PyObject.PyFalse = class.class(KaitaiStruct)
function PythonPyc27.PyObject.PyFalse:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.PyObject.PyFalse:_read()
end
PythonPyc27.PyObject.StringRef = class.class(KaitaiStruct)
function PythonPyc27.PyObject.StringRef:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.PyObject.StringRef:_read()
self.interned_list_index = self._io:read_u4le()
end
PythonPyc27.PyObject.PyTrue = class.class(KaitaiStruct)
function PythonPyc27.PyObject.PyTrue:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.PyObject.PyTrue:_read()
end
PythonPyc27.PyObject.Tuple = class.class(KaitaiStruct)
function PythonPyc27.PyObject.Tuple:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.PyObject.Tuple:_read()
self.count = self._io:read_u4le()
self.items = {}
for i = 0, self.count - 1 do
self.items[i + 1] = PythonPyc27.PyObject(self._io, self, self._root)
end
end
PythonPyc27.PyObject.UnicodeString = class.class(KaitaiStruct)
function PythonPyc27.PyObject.UnicodeString:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.PyObject.UnicodeString:_read()
self.length = self._io:read_u4le()
self.data = str_decode.decode(self._io:read_bytes(self.length), "utf-8")
end
PythonPyc27.PyObject.InternedString = class.class(KaitaiStruct)
function PythonPyc27.PyObject.InternedString:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.PyObject.InternedString:_read()
self.length = self._io:read_u4le()
self.data = str_decode.decode(self._io:read_bytes(self.length), "utf-8")
end
PythonPyc27.PyObject.PyString = class.class(KaitaiStruct)
function PythonPyc27.PyObject.PyString:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.PyObject.PyString:_read()
self.length = self._io:read_u4le()
self.data = self._io:read_bytes(self.length)
end
PythonPyc27.OpArgs = class.class(KaitaiStruct)
function PythonPyc27.OpArgs:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function PythonPyc27.OpArgs:_read()
self.items = {}
local i = 0
while not self._io:is_eof() do
self.items[i + 1] = PythonPyc27.OpArg(self._io, self, self._root)
i = i + 1
end
end
|
Cfg = {}
Cfg.ped = true
Cfg.pos = {x = -1985.80, y = -232.253, z = 28.611, h = 241.65}
KCDD = {
['Heavy'] = {
inform = {
label = "Heavy 3xGövde,1xNamlu,1x Sarjör,1xKabza,2xYay ", -- Menüde gözükecek olan isim
value = "pistol", -- Bir değer girin özel harf olmasın.
CraftedItem = "WEAPON_HEAVYPISTOL", -- Craftlayınca vericek item
count = 1, -- Craftlayınca kaç tane verilsin
Craft = { -- Maksimum 5 eşya arttırabilirsiniz !
[1] = {
reqitem = "gunbody", -- Craftlamak için gerekli item
count = 3,
},
[2] = {
reqitem = "gunbarrel",
count = 1,
},
[3] = {
reqitem = "gunmagazine",
count = 1,
},
[4] = { -- Maksimum 5 !
reqitem = "gunkabza",
count = 1,
},
[5] = {
reqitem = "yay",
count = 2,
}
}
}
},
['Glock'] = {
inform = {
label = "Glock 2xGövde,1xNamlu,1xSarjör,1xKabza,3xYay", -- Menüde gözükecek olan isim
value = "pistol", -- Bir değer girin özel harf olmasın.
CraftedItem = "WEAPON_COMBATPISTOL", -- Craftlayınca vericek item
count = 1, -- Craftlayınca kaç tane verilsin
Craft = { -- Maksimum 5 eşya arttırabilirsiniz !
[1] = {
reqitem = "gunbody", -- Craftlamak için gerekli item
count = 2,
},
[2] = {
reqitem = "gunbarrel",
count = 1,
},
[3] = {
reqitem = "gunmagazine",
count = 1,
},
[4] = { -- Maksimum 5 !
reqitem = "gunkabza",
count = 1,
},
[5] = {
reqitem = "yay",
count = 3,
}
}
}
},
['Pistol Mermi'] = {
inform = {
label = "Pistol Mermi 1xKovan,1xAliminyum", -- Menüde gözükecek olan isim
value = "Mermi", -- Bir değer girin özel harf olmasın.
CraftedItem = "disc_ammo_pistol", -- Craftlayınca vericek item
count = 5, -- Craftlayınca kaç tane verilsin
Craft = { -- Maksimum 5 eşya arttırabilirsiniz !
[1] = {
reqitem = "kovan", -- Craftlamak için gerekli item
count = 1,
},
[2] = {
reqitem = "aluminium",
count = 1,
}
}
}
},
['SMG Mermi'] = {
inform = {
label = "SMG Mermi 2xKovan,2xAliminyum", -- Menüde gözükecek olan isim
value = "Mermi", -- Bir değer girin özel harf olmasın.
CraftedItem = "disc_ammo_smg", -- Craftlayınca vericek item
count = 5, -- Craftlayınca kaç tane verilsin
Craft = { -- Maksimum 5 eşya arttırabilirsiniz !
[1] = {
reqitem = "kovan", -- Craftlamak için gerekli item
count = 2,
},
[2] = {
reqitem = "aluminium",
count = 1,
}
}
}
},
['Rifle Mermi'] = {
inform = {
label = "Rifle Mermi 3xKovan,3xAliminyum", -- Menüde gözükecek olan isim
value = "Mermi", -- Bir değer girin özel harf olmasın.
CraftedItem = "disc_ammo_rifle", -- Craftlayınca vericek item
count = 5, -- Craftlayınca kaç tane verilsin
Craft = { -- Maksimum 5 eşya arttırabilirsiniz !
[1] = {
reqitem = "kovan", -- Craftlamak için gerekli item
count = 3,
},
[2] = {
reqitem = "aluminium",
count = 3,
}
}
}
},
['Zırh'] = {
inform = {
label = "Zırh craftla",
value = "armor",
CraftedItem = "fullarmor",
count = 5,
Craft = {
[1] = {
reqitem = "kevlar",
count = 2,
}
}
}
}
}
Cfg.WaitingTime = 180000
Cfg.Locations = {
craft = {
process = {
body = vector3(-1973.25, -220.380, 27.864),
body2 = vector3(-1973.07, -222.721, 27.864),
body3 = vector3(-1975.61, -220.966, 27.864),
barrel = vector3(-1965.73, -224.398, 27.864),
kabza = vector3(-1968.98, -223.101, 27.864),
kabza2 = vector3(-1970.21, -224.940, 27.864),
yay = vector3(-1977.07, -226.869, 27.864),
yay2 = vector3(-1975.04, -224.209, 27.864),
kovan = vector3(-1974.69, -231.431, 27.864),
sarjor = vector3(-1969.83, -228.148, 27.549),
kevlar = vector3(-1976.19, -223.477, 27.864),
kevlar2 = vector3(-1977.52, -225.061, 27.864),
kevlar3 = vector3(-1978.31, -226.401, 27.864)
}
}
} |
local msgpack = require("omgameserver.msgpack")
local buffer = require("omgameserver.buffer")
local function create_buffer_from_byte_array(array)
local b = buffer.create_empty()
for i = 1, #array do buffer.write_unsigned_byte(b, array[i]) end
return b
end
local function compare_table(t1, t2)
for k, v in pairs(t1) do
if type(t1[k]) == "table" then
if (not compare_table(t1[k], t2[k])) then return false end
else
if (t1[k] ~= t2[k]) then return false end
end
end
return true
end
-- To prepare data was used this tool - https://kawanet.github.io/msgpack-lite/
local test_data = {
boolean = {
lua_table = { key1 = true, key2 = false },
msgpack_buffer = create_buffer_from_byte_array({130, 164, 107, 101, 121, 49, 195, 164, 107, 101, 121, 50, 194}),
},
integer = {
lua_table = {
positive_fixint = 64, unit8 = 160, unit16 = 1024, uint32 = 1048575,
negative_fixint = -16, int8 = -64, int16 = -4095, int32 = -268435455
},
msgpack_buffer = create_buffer_from_byte_array({136, 175, 112, 111, 115, 105, 116, 105, 118, 101, 95, 102, 105, 120, 105, 110, 116, 64, 165, 117, 110, 105, 116, 56, 204, 160, 166, 117, 110, 105, 116, 49, 54, 205, 4, 0, 166, 117, 105, 110, 116, 51, 50, 206, 0, 15, 255, 255, 175, 110, 101, 103, 97, 116, 105, 118, 101, 95, 102, 105, 120, 105, 110, 116, 240, 164, 105, 110, 116, 56, 208, 192, 165, 105, 110, 116, 49, 54, 209, 240, 1, 165, 105, 110, 116, 51, 50, 210, 240, 0, 0, 1}),
},
big_integer = {
lua_table = {
uint64 = 12345678901,
int64 = 98765432109,
},
msgpack_buffer = create_buffer_from_byte_array({130, 166, 117, 105, 110, 116, 54, 52, 207, 66, 6, 254, 224, 225, 168, 0, 0, 165, 105, 110, 116, 54, 52, 211, 66, 54, 254, 224, 229, 45, 0, 0}),
},
strings = {
lua_table = {
fixstr = "Fixstr",
str8 = "Str8str8str8str8str8str8str8str8str8str8",
str16 = "Str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16str16",
ключ = "значение"
},
msgpack_buffer = create_buffer_from_byte_array({132, 166, 102, 105, 120, 115, 116, 114, 166, 70, 105, 120, 115, 116, 114, 164, 115, 116, 114, 56, 217, 40, 83, 116, 114, 56, 115, 116, 114, 56, 115, 116, 114, 56, 115, 116, 114, 56, 115, 116, 114, 56, 115, 116, 114, 56, 115, 116, 114, 56, 115, 116, 114, 56, 115, 116, 114, 56, 115, 116, 114, 56, 165, 115, 116, 114, 49, 54, 218, 1, 9, 83, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 115, 116, 114, 49, 54, 168, 208, 186, 208, 187, 209, 142, 209, 135, 176, 208, 183, 208, 189, 208, 176, 209, 135, 208, 181, 208, 189, 208, 184, 208, 181})
},
arrays = {
lua_table = {
fixarray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
array16 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }
},
msgpack_buffer = create_buffer_from_byte_array({130, 168, 102, 105, 120, 97, 114, 114, 97, 121, 153, 1, 2, 3, 4, 5, 6, 7, 8, 9, 167, 97, 114, 114, 97, 121, 49, 54, 220, 0, 32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32})
},
maps = {
lua_table = {
fixmap = {
["1"] = 1, ["2"] = 2, ["4"] = 4, ["8"] = 8
},
map16 = {
["1"] = 1, ["2"] = 2, ["4"] = 4, ["8"] = 8, ["16"] = 16, ["32"] = 32, ["64"] = 64, ["128"] = 128, ["256"] = 256, ["512"] = 512,
["1024"] = 1024, ["2048"] = 2048, ["4096"] = 4096, ["8192"] = 8192, ["16384"] = 16384, ["32768"] = 32768, ["65536"] = 65536
}
},
msgpack_buffer = create_buffer_from_byte_array({130, 166, 102, 105, 120, 109, 97, 112, 132, 161, 49, 1, 161, 50, 2, 161, 52, 4, 161, 56, 8, 165, 109, 97, 112, 49, 54, 222, 0, 17, 161, 49, 1, 161, 50, 2, 161, 52, 4, 161, 56, 8, 162, 49, 54, 16, 162, 51, 50, 32, 162, 54, 52, 64, 163, 49, 50, 56, 204, 128, 163, 50, 53, 54, 205, 1, 0, 163, 53, 49, 50, 205, 2, 0, 164, 49, 48, 50, 52, 205, 4, 0, 164, 50, 48, 52, 56, 205, 8, 0, 164, 52, 48, 57, 54, 205, 16, 0, 164, 56, 49, 57, 50, 205, 32, 0, 165, 49, 54, 51, 56, 52, 205, 64, 0, 165, 51, 50, 55, 54, 56, 205, 128, 0, 165, 54, 53, 53, 51, 54, 206, 0, 1, 0, 0})
}
}
local function test_msgpack_simpletest()
assert(msgpack.decode(msgpack.encode({ payload = "helloworld" })).payload == "helloworld")
end
local function test_msgpack_boolean()
assert(compare_table(test_data.boolean.lua_table, msgpack.decode(test_data.boolean.msgpack_buffer)) == true)
assert(compare_table(test_data.boolean.lua_table, msgpack.decode(msgpack.encode(test_data.boolean.lua_table))) == true)
end
local function test_msgpack_integer()
assert(compare_table(test_data.integer.lua_table, msgpack.decode(test_data.integer.msgpack_buffer)) == true)
assert(compare_table(test_data.integer.lua_table, msgpack.decode(msgpack.encode(test_data.integer.lua_table))) == true)
end
local function test_msgpack_big_integer()
assert(compare_table(test_data.big_integer.lua_table, msgpack.decode(test_data.big_integer.msgpack_buffer)) == true)
assert(compare_table(test_data.big_integer.lua_table, msgpack.decode(msgpack.encode(test_data.big_integer.lua_table))) == true)
end
local function test_msgpack_strings()
assert(compare_table(test_data.strings.lua_table, msgpack.decode(test_data.strings.msgpack_buffer)) == true)
assert(compare_table(test_data.strings.lua_table, msgpack.decode(msgpack.encode(test_data.strings.lua_table))) == true)
end
local function test_msgpack_array()
assert(compare_table(test_data.arrays.lua_table, msgpack.decode(test_data.arrays.msgpack_buffer)) == true)
assert(compare_table(test_data.arrays.lua_table, msgpack.decode(msgpack.encode(test_data.arrays.lua_table))) == true)
end
local function test_msgpack_map()
assert(compare_table(test_data.maps.lua_table, msgpack.decode(test_data.maps.msgpack_buffer)) == true)
assert(compare_table(test_data.maps.lua_table, msgpack.decode(msgpack.encode(test_data.maps.lua_table))) == true)
end
local msgpack_test_suite = function()
print("[OMGS/MSGPACK] test suite for msgpack: started")
test_msgpack_simpletest()
test_msgpack_boolean()
test_msgpack_integer()
test_msgpack_big_integer()
test_msgpack_strings()
test_msgpack_array()
test_msgpack_map()
print("[OMGS/MSGPACK] test suite for msgpack: passed")
end
return msgpack_test_suite |
-- license:MIT
-- copyright-holders:Gavin Kistner
local exports = {}
exports.name = "SLAXML"
exports.version = "0.8"
exports.homepage = "http://github.com/Phrogz/SLAXML"
exports.description = "Lua SLAX XML parser"
exports.tags = {"xml"}
exports.license = "MIT"
exports.author = {
name = "Gavin Kistner",
}
local SLAXML = exports
--[=====================================================================[
v0.8 Copyright © 2013-2018 Gavin Kistner <!@phrogz.net>; MIT Licensed
See http://github.com/Phrogz/SLAXML for details.
--]=====================================================================]
SLAXML.VERSION = "0.8"
SLAXML._call = {
pi = function(target,content)
print(string.format("<?%s %s?>",target,content))
end,
comment = function(content)
print(string.format("<!-- %s -->",content))
end,
startElement = function(name,nsURI,nsPrefix)
io.write("<")
if nsPrefix then io.write(nsPrefix,":") end
io.write(name)
if nsURI then io.write(" (ns='",nsURI,"')") end
print(">")
end,
attribute = function(name,value,nsURI,nsPrefix)
io.write(' ')
if nsPrefix then io.write(nsPrefix,":") end
io.write(name,'=',string.format('%q',value))
if nsURI then io.write(" (ns='",nsURI,"')") end
io.write("\n")
end,
text = function(text,cdata)
print(string.format(" %s: %q",cdata and 'cdata' or 'text',text))
end,
closeElement = function(name,nsURI,nsPrefix)
io.write("</")
if nsPrefix then io.write(nsPrefix,":") end
print(name..">")
end,
}
function SLAXML:parser(callbacks)
return { _call=callbacks or self._call, parse=SLAXML.parse }
end
function SLAXML:parse(xml,options)
if not options then options = { stripWhitespace=false } end
-- Cache references for maximum speed
local find, sub, gsub, char, push, pop, concat = string.find, string.sub, string.gsub, string.char, table.insert, table.remove, table.concat
local first, last, match1, match2, match3, pos2, nsURI
local unpack = unpack or table.unpack
local pos = 1
local state = "text"
local textStart = 1
local currentElement={}
local currentAttributes={}
local currentAttributeCt -- manually track length since the table is re-used
local nsStack = {}
local anyElement = false
local utf8markers = { {0x7FF,192}, {0xFFFF,224}, {0x1FFFFF,240} }
local function utf8(decimal) -- convert unicode code point to utf-8 encoded character string
if decimal<128 then return char(decimal) end
local charbytes = {}
for bytes,vals in ipairs(utf8markers) do
if decimal<=vals[1] then
for b=bytes+1,2,-1 do
local mod = decimal%64
decimal = (decimal-mod)/64
charbytes[b] = char(128+mod)
end
charbytes[1] = char(vals[2]+decimal)
return concat(charbytes)
end
end
end
local entityMap = { ["lt"]="<", ["gt"]=">", ["amp"]="&", ["quot"]='"', ["apos"]="'" }
local entitySwap = function(orig,n,s) return entityMap[s] or n=="#" and utf8(tonumber('0'..s)) or orig end
local function unescape(str) return gsub( str, '(&(#?)([%d%a]+);)', entitySwap ) end
local function finishText()
if first>textStart and self._call.text then
local text = sub(xml,textStart,first-1)
if options.stripWhitespace then
text = gsub(text,'^%s+','')
text = gsub(text,'%s+$','')
if #text==0 then text=nil end
end
if text then self._call.text(unescape(text),false) end
end
end
local function findPI()
first, last, match1, match2 = find( xml, '^<%?([:%a_][:%w_.-]*) ?(.-)%?>', pos )
if first then
finishText()
if self._call.pi then self._call.pi(match1,match2) end
pos = last+1
textStart = pos
return true
end
end
local function findComment()
first, last, match1 = find( xml, '^<!%-%-(.-)%-%->', pos )
if first then
finishText()
if self._call.comment then self._call.comment(match1) end
pos = last+1
textStart = pos
return true
end
end
local function nsForPrefix(prefix)
if prefix=='xml' then return 'http://www.w3.org/XML/1998/namespace' end -- http://www.w3.org/TR/xml-names/#ns-decl
for i=#nsStack,1,-1 do if nsStack[i][prefix] then return nsStack[i][prefix] end end
error(("Cannot find namespace for prefix %s"):format(prefix))
end
local function startElement()
anyElement = true
first, last, match1 = find( xml, '^<([%a_][%w_.-]*)', pos )
if first then
currentElement[2] = nil -- reset the nsURI, since this table is re-used
currentElement[3] = nil -- reset the nsPrefix, since this table is re-used
finishText()
pos = last+1
first,last,match2 = find(xml, '^:([%a_][%w_.-]*)', pos )
if first then
currentElement[1] = match2
currentElement[3] = match1 -- Save the prefix for later resolution
match1 = match2
pos = last+1
else
currentElement[1] = match1
for i=#nsStack,1,-1 do if nsStack[i]['!'] then currentElement[2] = nsStack[i]['!']; break end end
end
currentAttributeCt = 0
push(nsStack,{})
return true
end
end
local function findAttribute()
first, last, match1 = find( xml, '^%s+([:%a_][:%w_.-]*)%s*=%s*', pos )
if first then
pos2 = last+1
first, last, match2 = find( xml, '^"([^<"]*)"', pos2 ) -- FIXME: disallow non-entity ampersands
if first then
pos = last+1
match2 = unescape(match2)
else
first, last, match2 = find( xml, "^'([^<']*)'", pos2 ) -- FIXME: disallow non-entity ampersands
if first then
pos = last+1
match2 = unescape(match2)
end
end
end
if match1 and match2 then
local currentAttribute = {match1,match2}
local prefix,name = string.match(match1,'^([^:]+):([^:]+)$')
if prefix then
if prefix=='xmlns' then
nsStack[#nsStack][name] = match2
else
currentAttribute[1] = name
currentAttribute[4] = prefix
end
else
if match1=='xmlns' then
nsStack[#nsStack]['!'] = match2
currentElement[2] = match2
end
end
currentAttributeCt = currentAttributeCt + 1
currentAttributes[currentAttributeCt] = currentAttribute
return true
end
end
local function findCDATA()
first, last, match1 = find( xml, '^<!%[CDATA%[(.-)%]%]>', pos )
if first then
finishText()
if self._call.text then self._call.text(match1,true) end
pos = last+1
textStart = pos
return true
end
end
local function closeElement()
first, last, match1 = find( xml, '^%s*(/?)>', pos )
if first then
state = "text"
pos = last+1
textStart = pos
-- Resolve namespace prefixes AFTER all new/redefined prefixes have been parsed
if currentElement[3] then currentElement[2] = nsForPrefix(currentElement[3]) end
if self._call.startElement then self._call.startElement(unpack(currentElement)) end
if self._call.attribute then
for i=1,currentAttributeCt do
if currentAttributes[i][4] then currentAttributes[i][3] = nsForPrefix(currentAttributes[i][4]) end
self._call.attribute(unpack(currentAttributes[i]))
end
end
if match1=="/" then
pop(nsStack)
if self._call.closeElement then self._call.closeElement(unpack(currentElement)) end
end
return true
end
end
local function findElementClose()
first, last, match1, match2 = find( xml, '^</([%a_][%w_.-]*)%s*>', pos )
if first then
nsURI = nil
for i=#nsStack,1,-1 do if nsStack[i]['!'] then nsURI = nsStack[i]['!']; break end end
else
first, last, match2, match1 = find( xml, '^</([%a_][%w_.-]*):([%a_][%w_.-]*)%s*>', pos )
if first then nsURI = nsForPrefix(match2) end
end
if first then
finishText()
if self._call.closeElement then self._call.closeElement(match1,nsURI) end
pos = last+1
textStart = pos
pop(nsStack)
return true
end
end
while pos<#xml do
if state=="text" then
if not (findPI() or findComment() or findCDATA() or findElementClose()) then
if startElement() then
state = "attributes"
else
first, last = find( xml, '^[^<]+', pos )
pos = (first and last or pos) + 1
end
end
elseif state=="attributes" then
if not findAttribute() then
if not closeElement() then
error("Was in an element and couldn't find attributes or the close.")
end
end
end
end
if not anyElement then error("Parsing did not discover any elements") end
if #nsStack > 0 then error("Parsing ended with unclosed elements") end
end
-- Optional parser that creates a flat DOM from parsing
function SLAXML:dom(xml,opts)
if not opts then opts={} end
local rich = not opts.simple
local push, pop = table.insert, table.remove
local doc = {type="document", name="#doc", kids={}}
local current,stack = doc, {doc}
local builder = SLAXML:parser{
startElement = function(name,nsURI,nsPrefix)
local el = { type="element", name=name, kids={}, el=rich and {} or nil, attr={}, nsURI=nsURI, nsPrefix=nsPrefix, parent=rich and current or nil }
if current==doc then
if doc.root then error(("Encountered element '%s' when the document already has a root '%s' element"):format(name,doc.root.name)) end
doc.root = rich and el or nil
end
push(current.kids,el)
if current.el then push(current.el,el) end
current = el
push(stack,el)
end,
attribute = function(name,value,nsURI,nsPrefix)
if not current or current.type~="element" then error(("Encountered an attribute %s=%s but I wasn't inside an element"):format(name,value)) end
local attr = {type='attribute',name=name,nsURI=nsURI,nsPrefix=nsPrefix,value=value,parent=rich and current or nil}
if rich then current.attr[name] = value end
push(current.attr,attr)
end,
closeElement = function(name)
if current.name~=name or current.type~="element" then error(("Received a close element notification for '%s' but was inside a '%s' %s"):format(name,current.name,current.type)) end
pop(stack)
current = stack[#stack]
end,
text = function(value,cdata)
-- documents may only have text node children that are whitespace: https://www.w3.org/TR/xml/#NT-Misc
if current.type=='document' and not value:find('^%s+$') then error(("Document has non-whitespace text at root: '%s'"):format(value:gsub('[\r\n\t]',{['\r']='\\r', ['\n']='\\n', ['\t']='\\t'}))) end
push(current.kids,{type='text',name='#text',cdata=cdata and true or nil,value=value,parent=rich and current or nil})
end,
comment = function(value)
push(current.kids,{type='comment',name='#comment',value=value,parent=rich and current or nil})
end,
pi = function(name,value)
push(current.kids,{type='pi',name=name,value=value,parent=rich and current or nil})
end
}
builder:parse(xml,opts)
return doc
end
local escmap = {["<"]="<", [">"]=">", ["&"]="&", ['"']=""", ["'"]="'"}
local function esc(s) return s:gsub('[<>&"]', escmap) end
-- opts.indent: number of spaces, or string
function SLAXML:xml(n,opts)
opts = opts or {}
local out = {}
local tab = opts.indent and (type(opts.indent)=="number" and string.rep(" ",opts.indent) or opts.indent) or ""
local ser = {}
local omit = {}
if opts.omit then for _,s in ipairs(opts.omit) do omit[s]=true end end
function ser.document(n)
for _,kid in ipairs(n.kids) do
if ser[kid.type] then ser[kid.type](kid,0) end
end
end
function ser.pi(n,depth)
depth = depth or 0
table.insert(out, tab:rep(depth)..'<?'..n.name..' '..n.value..'?>')
end
function ser.element(n,depth)
if n.nsURI and omit[n.nsURI] then return end
depth = depth or 0
local indent = tab:rep(depth)
local name = n.nsPrefix and n.nsPrefix..':'..n.name or n.name
local result = indent..'<'..name
if n.attr and n.attr[1] then
local sorted = n.attr
if opts.sort then
sorted = {}
for i,a in ipairs(n.attr) do sorted[i]=a end
table.sort(sorted,function(a,b)
if a.nsPrefix and b.nsPrefix then
return a.nsPrefix==b.nsPrefix and a.name<b.name or a.nsPrefix<b.nsPrefix
elseif not (a.nsPrefix or b.nsPrefix) then
return a.name<b.name
elseif b.nsPrefix then
return true
else
return false
end
end)
end
local attrs = {}
for _,a in ipairs(sorted) do
if (not a.nsURI or not omit[a.nsURI]) and not (omit[a.value] and a.name:find('^xmlns:')) then
attrs[#attrs+1] = ' '..(a.nsPrefix and (a.nsPrefix..':') or '')..a.name..'="'..esc(a.value)..'"'
end
end
result = result..table.concat(attrs,'')
end
result = result .. (n.kids and n.kids[1] and '>' or '/>')
table.insert(out, result)
if n.kids and n.kids[1] then
for _,kid in ipairs(n.kids) do
if ser[kid.type] then ser[kid.type](kid,depth+1) end
end
table.insert(out, indent..'</'..name..'>')
end
end
function ser.text(n,depth)
if n.cdata then
table.insert(out, tab:rep(depth)..'<![CDATA['..n.value..']]>')
else
table.insert(out, tab:rep(depth)..esc(n.value))
end
end
function ser.comment(n,depth)
table.insert(out, tab:rep(depth)..'<!--'..n.value..'-->')
end
ser[n.type](n,0)
return table.concat(out, opts.indent and '\n' or '')
end
return SLAXML
|
local BulletChar = require "bosses/lekkerchat/projectiles/bulletchar"
local BulletCharGT = BulletChar:extend("BulletCharGT")
function BulletCharGT:new(x, y, part)
BulletCharGT.super.new(self, x, y)
if part then
self.isPart = true
self:setImage("bosses/lekkerchat/char_gt_part")
if part == "up" then
self.velocity.y = -100
else
self.flip.y = true
self.velocity.y = 100
end
else
self:setImage("bosses/lekkerchat/char_gt")
end
self.velocity.x = -BulletChar.xSpeed
self.timer = 0
end
function BulletCharGT:update(dt)
if not self.isPart then
self.timer = self.timer + dt
if self.timer > 0.6 then
self.scene:addEntity(BulletCharGT(self.x, self.y, "up"))
self.scene:addEntity(BulletCharGT(self.x, self.y, "down"))
self:destroy()
end
end
BulletCharGT.super.update(self, dt)
end
function BulletCharGT:draw()
BulletCharGT.super.draw(self)
end
return BulletCharGT |
project "Lumi"
kind "StaticLib"
language "C++"
cppdialect "C++20"
staticruntime "on"
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
pchheader "pch.h"
pchsource "src/pch.cpp"
files
{
"src/**.h",
"src/**.hpp",
"src/**.cpp",
"src/**.inl"
}
defines
{
"_CRT_SECURE_NO_WARNINGS"
}
includedirs
{
"%{wks.location}/%{prj.name}/src",
"%{wks.location}/%{prj.name}/include",
"%{IncludeDir.entt}",
"%{IncludeDir.glad}",
"%{IncludeDir.GLFW}",
"%{IncludeDir.glm}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.spdlog}",
"%{IncludeDir.stb}",
"%{IncludeDir.yaml}",
"%{wks.location}/LumiEditor/src"
}
links
{
"opengl32.lib",
"entt",
"glad",
"GLFW",
"glm",
"ImGui",
"spdlog",
"stb",
"yaml"
}
filter "system:windows"
systemversion "latest"
defines
{
"_LM_WINDOWS_",
"LM_DLL_EXPORTS"
}
filter "configurations:Debug"
defines "LUMI_DEBUG"
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines "LUMI_RELEASE"
runtime "RELEASE"
optimize "on"
filter "configurations:Dist"
defines "LUMI_DIST"
runtime "RELEASE"
optimize "on"
filter "configurations:RelWithDebInfo"
defines "LUMI_RELEASE"
defines "LM_PROFILE"
runtime "RELEASE"
optimize "on" |
local test_cache = ngx.shared.test_cache0
local key = {}
test_cache:set('key', 100, 10)
ngx.say(type(test_cache))
ngx.say(ngx.shared)
|
-- NOTE that the standard is to pass/return signal and block NAMES, not tables, to/from functions. This shd save on overheads
-- Initial setup; all three of these are dictionaries
local Signals = require(script.SignalData)
local Config = require(script.Config)
local Blocks = {}
local Reservations = {} -- Sorted by hitter.
local RunService = game:GetService('RunService')
-- Functions --
local Functions = {}
-- Wait a bit between operations.
Functions.Wait2 = function()
--RunService.Heartbeat:Wait()
end
-- Set a signal's state
Functions.SetState = function(SignalName, State)
local Signal = Signals[SignalName]
if Signal.State == State then
return -- Not worth our time
end
Signal.State = State
-- Now set its color
local LowerColor = Config.States[State][1]
local UpperColor = Config.States[State][2]
Signal.Model[Config.Organisation.Names.SignalUpper].Color = LowerColor
Signal.LowerLight.Enabled = LowerColor == Color3.new() -- If it's 0, 0, 0
Signal.LowerLight.Color = LowerColor
Signal.Model[Config.Organisation.Names.SignalLower].Color = UpperColor
Signal.UpperLight.Enabled = UpperColor == Color3.new()
Signal.UpperLight.Color = UpperColor
end
-- Check a signal's state
Functions.CheckState = function(SignalName)
local Signal = Signals[SignalName]
if Blocks[Signal.Block].HitterCount > 0 then
return 1 -- Set to red unconditionally
end
local State = #Config.States -- Start at the highest state and go down through each next signal
for _, NextSignal in ipairs(Signal.NextSignals) do -- Check every signal ahead for 'low' aspects requiring advance
State = math.min(State, Signals[NextSignal].State + 1) -- It's still 1 more permissive
end
return State
end
-- Get the next signals or next blocks after a signal, a certain distance away.
-- This is a tree shape, but it doesn't return any 'tree' data structure, which is bad
-- (reserving shd only bother with the last layer, as the other layers shd already be reserved)
Functions.GetNextSignals = function() end
Functions.GetNextSignals = function(SignalName, Count, IncludeStarting)
local NextSignals = IncludeStarting and { SignalName } or {}
if Count == 0 then
return NextSignals -- Not useful to do anything else.
end
local Signal = Signals[SignalName]
for _, NextSignal in ipairs(Signal.NextSignals) do
-- Add this signal, and its next signals (with 1 less count to prevent it going on forever)
for _, NextSignal1 in ipairs(Functions.GetNextSignals(NextSignal, Count - 1, true)) do
table.insert(NextSignals, NextSignal1)
end
end
return NextSignals
end
-- When a signal changes, update advance aspects behind it.
Functions.UpdatePrevSignals = function() end -- Allow for recursion.
Functions.UpdatePrevSignals = function(SignalName)
local Signal = Signals[SignalName]
for _, PrevSignal in ipairs(Signal.PrevSignals) do
local OldState = Signals[PrevSignal].State
local NewState = Functions.CheckState(PrevSignal)
-- Check if we're actually changing - if not, stop bothering
if NewState ~= OldState then
Functions.SetState(PrevSignal, NewState)
Functions.UpdatePrevSignals(PrevSignal) -- Move it back one
end
end
end
-- Reserve and unreserve blocks.
Functions.ActivateReservation = function(BlockName)
-- Fetch some variables
local Block = Blocks[BlockName]
local SignalName = Block.ReservationQueue[1] -- Reserve from the signal at the front of the queue
if SignalName == nil then
return -- Nothing to reserve (we're all caught up!)
end
for _, OtherSignalName in ipairs(Block.InSignals) do
if OtherSignalName == SignalName then
-- Make it as permissive as we can
local NewState = Functions.CheckState(OtherSignalName)
if NewState ~= Signals[OtherSignalName].State then
Functions.SetState(OtherSignalName, NewState)
Functions.UpdatePrevSignals(OtherSignalName)
end
else
-- Set this signal to danger, as it's conflicting with our path
Functions.SetState(OtherSignalName, 1)
Functions.UpdatePrevSignals(OtherSignalName)
end
end
end
Functions.ReserveBlock = function(Hitter, BlockName, SignalName)
local Block = Blocks[BlockName]
-- Join the queue, if we're not already in it
if table.find(Block.ReservationQueue, SignalName) ~= nil then
return -- We're wasting time here
end
-- Otherwise, queue us up
table.insert(Block.ReservationQueue, SignalName)
Reservations[Hitter][BlockName] = SignalName
-- If we're up the front, update the system to actually let us in.
if #Block.ReservationQueue == 1 then
Functions.ActivateReservation(BlockName)
end
end
Functions.UnreserveBlock = function(Hitter, BlockName, SignalName)
local Block = Blocks[BlockName]
-- Unqueue this signal, if it's queued at all
local SignalIndex = table.find(Block.ReservationQueue, SignalName)
if SignalIndex ~= nil then
table.remove(Block.ReservationQueue, SignalIndex)
if SignalIndex == 1 then
Functions.ActivateReservation(BlockName) -- The front was removed and thus changed
end
-- Update the Reservations table
Reservations[Hitter][BlockName] = nil
end
end
-- Main two functions: detect and act upon changes
Functions.BlockChanged = function(BlockName)
local Block = Blocks[BlockName]
if Block.HitterCount > 0 then
-- This block is occupied: set its signals to danger
for _, SignalName in ipairs(Block.InSignals) do
Functions.SetState(SignalName, 1) -- 1 is the least permissive, NOT ZERO as in 2.4
-- Now check for signals behind that need to be changed as well
Functions.UpdatePrevSignals(SignalName)
end
else
-- Free this block up
for _, SignalName in ipairs(Block.InSignals) do
-- Set the state based on what it should be
Functions.SetState(SignalName, Functions.CheckState(SignalName))
Functions.UpdatePrevSignals(SignalName)
end
end
end
Functions.DetectorTouched = function(Detector, Hitter, IsForward)
-- We needn't check if it's a hitter, as only hitters are connected (see below)
-- We needn't check that Detector is a detector either
-- Change the part's current block, and update other block data
local SignalName = Detector.Parent.Name -- This assumes detectors are directly parented to the signal!
local OldBlockName = Hitter:GetAttribute('SignalBlock')
local OldBlock = Blocks[OldBlockName]
local NewBlockName
local NewBlock
-- Decide new block based on direction
if IsForward == true then
NewBlockName = Signals[SignalName].Block
NewBlock = Blocks[NewBlockName]
else
-- Get the new block from the previous signal
local PrevSignalName = Signals[SignalName].PrevSignals[1]
if PrevSignalName ~= nil then -- If it's nil, our 'new block' doesn't exist!
NewBlockName = Signals[PrevSignalName].Block
NewBlock = Blocks[NewBlockName]
end
end
if OldBlockName == NewBlockName then
return
end
Hitter:SetAttribute('SignalBlock', NewBlockName)
if OldBlock ~= nil then -- In case the train just spawned
OldBlock.HitterCount -= 1 -- A hitter has left the block
if OldBlock.HitterCount == 0 then
-- The block has become empty
Functions.BlockChanged(OldBlockName)
Functions.Wait2()
-- Don't unreserve the block we just left, as it was unreserved when we entered it
-- Unreserve all blocks from signals we didn't go through
for _, UnpassedSignalName in ipairs(OldBlock.OutSignals) do
if UnpassedSignalName ~= SignalName then -- Don't unreserve the signal we did pass
-- We need to find all the SIGNALS ahead of here, and then unreserve from them.
-- BlocksAhead - 1 as we're one ahead of where we were, so didn't reserve quite that far
for _, SignalName in ipairs(Functions.GetNextSignals(UnpassedSignalName, Config.Reservation.BlocksAhead - 1, true)) do
Functions.UnreserveBlock(Hitter, Signals[SignalName].Block, SignalName) -- Unreserve this signal's block from the signal.
end
end
end
end
end
Functions.Wait2()
if NewBlock ~= nil then
NewBlock.HitterCount += 1 -- A hitter has entered the block
if NewBlock.HitterCount == 1 then
-- The block has just become full (it was 0 before)
Functions.BlockChanged(NewBlockName)
Functions.Wait2()
-- Reserve blocks from this signal
local NextSignals = Functions.GetNextSignals(SignalName, Config.Reservation.BlocksAhead, false)
local ReservedBlocks = {} -- Dictionary!
for _, SignalToReserve in ipairs(NextSignals) do
local Block = Signals[SignalToReserve].Block
if ReservedBlocks[Block] ~= nil then
table.insert(ReservedBlocks[Block], SignalToReserve) -- It's full now anyway
else
ReservedBlocks[Block] = { SignalToReserve }
end
end
-- Now, reserve every block with EXACTLY ONE signal
for BlockToReserve, SignalsToReserve in pairs(ReservedBlocks) do
if #SignalsToReserve == 1 then
Functions.ReserveBlock(Hitter, BlockToReserve, SignalsToReserve[1]) -- Reserve it!
end
end
Functions.Wait2()
-- Unreserve the block we just entered (we don't need it reserved anymore)
-- It's easiest to do this now, because we know which signal we had reserved from
Functions.UnreserveBlock(Hitter, NewBlockName, SignalName)
end
end
end
-- The AWS system
Functions.AWSDetectorTouched = function(Detector, Hitter)
-- Before anything else, check we're enabled and we're not on debounce
if Config.AWS.GetAWSEnabled(Hitter) ~= true then -- On the off chance it returns nil
return
end
if tick() - (Detector:GetAttribute('LastDetection') or 0) < Config.AWS.DetectionDebounce then
Detector:SetAttribute('LastDetection', tick()) -- Maybe bad practice, but makes more sense for long trains with more cars
return
end
Detector:SetAttribute('LastDetection', tick()) -- We still need to set it!
-- Get its signal
local SignalName = Detector.Parent.Name
local Signal = Signals[SignalName]
local State = Signals[SignalName].State
if State == #Config.States then
-- Clear - play ding
local Eminator = Config.AWS.GetSoundEminator(Hitter)
local Sound = Eminator:FindFirstChild('AWSClear')
if Sound == nil then -- Create it if it doesn't already exist
Sound = Instance.new('Sound')
Sound.Name = 'AWSClear'
Sound.Parent = Config.AWS.GetSoundEminator(Hitter)
Sound.SoundId = 'rbxassetid://' .. tostring(Config.AWS.ClearSoundID)
end
Sound:Play()
-- Destroy it when it's finished using a connection (could've used a coroutine)
local Connection
Connection = Sound.Ended:Connect(function()
Connection:Disconnect() -- Clean it up
end)
else
-- Not clear - play beep repeatedly until silenced
local Eminator = Config.AWS.GetSoundEminator(Hitter)
local Sound = Eminator:FindFirstChild('AWSNotClear')
if Sound == nil then -- Create it if it doesn't already exist
Sound = Instance.new('Sound')
Sound.Name = 'AWSNotClear'
Sound.Parent = Config.AWS.GetSoundEminator(Hitter)
Sound.SoundId = 'rbxassetid://' .. tostring(Config.AWS.NotClearSoundID)
end
Sound:Play()
if Config.AWS.NotClearIsLooped == true then
Sound.Looped = true -- Loop it
local Connection -- Connect its deletion to a keypress event
local RequiredPlayer = Config.AWS.GetPlayer(Hitter)
if RequiredPlayer ~= nil then
local Pressed = false
Connection = Config.AWS.KeypressEvent.OnServerEvent:Connect(function(Player, InputType)
if Player == RequiredPlayer and InputType == 'AWS' then
if Connection ~= nil then Connection:Disconnect() end -- idk why it's sometimes nil
Sound:Stop()
Pressed = true
end
end)
-- Time out if needed
if Config.AWS.NotClearTimeout ~= nil then
delay(Config.AWS.NotClearTimeout, function()
if Pressed == false then
Config.AWS.TimedOut(Hitter)
Connection:Disconnect()
Sound:Stop()
end
end)
end
end
else
-- As above - sorry about code duplication
local Connection
Connection = Sound.Ended:Connect(function()
Connection:Disconnect() -- Clean it up
Sound:Stop()
end)
end
end
end
-- Setup --
Functions.Setup = function()
-- Connect train hitters to the above
local IsForward = function(Detector, Hitter)
local DetectorDirection = Detector.CFrame.LookVector
local HitterDirection = Hitter.Velocity.Unit
-- Check which is closer: the same direction or opposite direction
local ForwardMagnitude = (DetectorDirection - HitterDirection).Magnitude
local BackwardMagnitude = (DetectorDirection - (HitterDirection * -1)).Magnitude
return ForwardMagnitude < BackwardMagnitude
end
local NewPart = function(Hitter)
-- The second clause prevent welds named to the welded part being picked up.
if Hitter.Name == Config.Organisation.Names.TrainHitter and Hitter:IsA('BasePart') then
-- It's a hitter
Hitter.TouchEnded:Connect(function(OtherPart) -- TouchEnded in case it drives onto one then back off it
if OtherPart.Name == Config.Organisation.Names.SignalDetector then
-- It's a detector, so call the above function
Functions.DetectorTouched(OtherPart, Hitter, IsForward(OtherPart, Hitter))
elseif OtherPart.Name == Config.Organisation.Names.AWSDetector then
Functions.AWSDetectorTouched(OtherPart, Hitter)
end
end)
-- Give it a reservations array
Reservations[Hitter] = {}
-- And listen for it being deleted
local Connection = Hitter.AncestryChanged:Connect(function(Ancestor, NewParent)
if Ancestor == Hitter and NewParent ~= workspace then
-- It's been deleted - clear the array
for BlockName, SignalName in pairs(Reservations[Hitter]) do
Functions.UnreserveBlock(Hitter, BlockName, SignalName)
end
Reservations[Hitter] = nil -- We don't need this anymore
-- Clear its block
local BlockName = Hitter:GetAttribute('SignalBlock')
local Block = Blocks[BlockName]
if Block ~= nil then -- Otherwise, don't bother (it causes errors anyway)
Block.HitterCount -= 1
if Block.HitterCount == 0 then
Functions.BlockChanged(BlockName)
end
end
end
end)
end
end
workspace.DescendantAdded:Connect(NewPart)
for _, Part in ipairs(workspace:GetDescendants()) do
NewPart(Part) -- In case any were here before this ran
end
-- Set up blocks and signals
-- Find the model for each signal
for _, d in ipairs(Config.Organisation.Folders.Signals:GetDescendants()) do
local Signal = Signals[d.Name]
if Signal ~= nil then
-- Set the model key
Signal.Model = d
-- Give it lights
local Lower = d[Config.Organisation.Names.SignalLower]
local Upper = d[Config.Organisation.Names.SignalUpper]
Signal.LowerLight = Lower:FindFirstChildWhichIsA('Light') or Config.NewLight(Lower)
Signal.UpperLight = Upper:FindFirstChildWhichIsA('Light') or Config.NewLight(Upper)
end
end
for Name, Data in pairs(Signals) do
-- Initialise the signal
Functions.SetState(Name, 1) -- Initialise to red
-- Fill in the Blocks table
if Blocks[Data.Block] == nil then
Blocks[Data.Block] = {
HitterCount = 0, -- Number of hitters in the block
InSignals = { Name }, -- Start listing all the signals
OutSignals = {},
ReservationQueue = {}
}
else
table.insert(Blocks[Data.Block].InSignals, Name) -- Keep the above list up to date
end
-- Give it a PrevSignals table, if it hasn't already been given one by another signal
Data.PrevSignals = Data.PrevSignals or {}
-- Add to the PrevSignals array from every next signal
for _, NextSignal in ipairs(Data.NextSignals) do
-- PrevSignals in this signal (NextSignal) that should point back to us
if Signals[NextSignal].PrevSignals ~= nil then -- In case it doesn't exist yet
table.insert(Signals[NextSignal].PrevSignals, Name) -- Add us!
else
-- Create the table first
Signals[NextSignal].PrevSignals = { Name }
end
-- Now, add this signal to the OutSignals of our block - if it's not there already
if table.find(Blocks[Data.Block].OutSignals, NextSignal) == nil then
table.insert(Blocks[Data.Block].OutSignals, NextSignal)
end
end
-- Check it has a model
if Data.Model == nil then
error('Signal \'' .. Name .. '\' does not have a model in the folder referenced in Config. (1)')
end
end
-- Update every block a few times to get signals off red (which they start as)
for i = 1, #Config.States do
for Block, _ in pairs(Blocks) do
Functions.BlockChanged(Block)
end
end
end
-- Initialise plugins
local Plugins = {}
for _, c in ipairs(script.Plugins:GetChildren()) do
table.insert(Plugins, { ['Plugin'] = require(c), ['Priority'] = c:GetAttribute('Priority') })
end
-- Sort them to put lower priority (higher number) ones first
-- The higher priority ones are then put over the top
table.sort(Plugins, function(a, b) return a.Priority > b.Priority end)
for _, Plugin in ipairs(Plugins) do
Plugin = Plugin.Plugin -- We don't care about priority anymore
local PluginFunctions = {} -- Pre-looping prevents weirdness due to modification of the dictionary inside the loop.
for Name, _ in pairs(Plugin) do
table.insert(PluginFunctions, Name)
end
for _, Name in ipairs(PluginFunctions) do
-- Overwrite the existing function with this function, making the existing function this plugin's 'base' function.
-- Obviously, if this function IS a base function, we don't want anything to do with it.
-- (Plugin designers may make dummy base functions to make Lua stop complaining about unknown globals)
if string.sub(Name, #Name - 4, #Name) == '_Base' then
continue
end
Plugin[Name .. '_Base'] = Functions[Name] -- Note this isn't necessarily THE base function, as others may have written here
Functions[Name] = Plugin[Name] -- When higher priority plugins write their base functions, that'll include our function
end
end
Functions.Setup()
|
--------------------------------------------------------------------------------
-- single-BROKEN-with-decorator-suite.lua: suite used for full suite tests
-- This file is a part of lua-nucleo library
-- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license)
--------------------------------------------------------------------------------
local make_suite = select(1, ...)
local test = make_suite("single-BROKEN-unstrict-mode-suite", { })
test:set_strict_mode(false)
local decorator = function(test_func)
return function(test_env)
return test_func(test_env)
end
end
test:BROKEN "to_test" :with(decorator) (function()
local counter = suite_tests_results + 1
end)
|
-- This file has dependencies to BOTH, the TeX part of pgfplots and the LUA part.
-- It is the only LUA component with this property.
--
-- Its purpose is to encapsulate the communication between TeX and LUA in a central LUA file
local pgfplotsmath = pgfplots.pgfplotsmath
local error=error
local table=table
local string=string
local tostring=tostring
local type=type
local io=io
local mathfloor=math.floor
local mathceil=math.ceil
local pgfmathparse = pgfplots.pgfluamathparser.pgfmathparse
do
-- all globals will be read from/defined in pgfplots:
local _ENV = pgfplots
local pgftonumber =pgfluamathfunctions.tonumber
function texBoxPlotSurveyPoint(data)
gca.currentPlotHandler:semiSurveyedValue(data)
end
-------------------------------------------------------
PercentileEstimator = newClass()
function PercentileEstimator:constructor()
end
function PercentileEstimator:getIndex(data, i)
local idx = i
if idx < 1 then idx = 1 end
if idx > #data then idx = #data end
local result = data[idx]
if not result then
error("Box plot percentile estimator '" .. tostring(self) .." accessed illegal array index " .. tostring(idx) .. " in array of length " .. tostring(#data))
end
return result
end
-- @param percentile the requested percentile. Use 0.5 for the median, 0.25 for the first quartile, 0.95 for the 95% percentile etc.
function PercentileEstimator:getValue(percentile, data)
error("Use implementation of PercentileEstimator, not interface")
end
-- LegacyPgfplotsPercentileEstimator is a minimally repaired percentile estimator as it has been shipped with pgfplots.10 .
-- I decided to mark it as deprecated because it is non-standard and not comparable with other programs.
LegacyPgfplotsPercentileEstimator = newClassExtends(PercentileEstimator)
function LegacyPgfplotsPercentileEstimator:constructor()
end
function LegacyPgfplotsPercentileEstimator:__tostring()
return "estimator=legacy";
end
function LegacyPgfplotsPercentileEstimator:getValue(percentile, data)
if not percentile or not data then error("Arguments must not be nil") end
local numCoords = #data
local h = numCoords * percentile
local offset_low = mathfloor(h)
local isInt = ( h==offset_low )
local offset_high = offset_low+1
local x_low = self:getIndex(data, offset_low)
local x_up = self:getIndex(data, offset_high)
local res = x_low
if not isInt then
res = 0.5 * (res + x_up)
end
return res
end
-- LegacyBadPgfplotsPercentileEstimator is _the_ percentile estimator as it has been shipped with pgfplots 1.10.
-- It has bugs and is non-standard. Don't use it.
LegacyBadPgfplotsPercentileEstimator = newClassExtends(PercentileEstimator)
function LegacyBadPgfplotsPercentileEstimator:constructor()
end
function LegacyBadPgfplotsPercentileEstimator:__tostring()
return "estimator=legacy*";
end
function LegacyBadPgfplotsPercentileEstimator:getValue(percentile, data)
if not percentile or not data then error("Arguments must not be nil") end
local numCoords = #data
local h = (numCoords-1) * percentile
local offset_low = mathfloor(h)
local isInt = ( h==offset_low )
local offset_high = offset_low+1
local x_low = self:getIndex(data, offset_low+1)
local x_up = self:getIndex(data, offset_high+1)
local res = x_low
if not isInt then
res = 0.5 * (res + x_up)
end
return res
end
----------------
ParameterizedPercentileEstimator = newClassExtends(PercentileEstimator)
function ParameterizedPercentileEstimator:__tostring()
return "estimator=" .. tostring(self.typeFlag) ;
end
function ParameterizedPercentileEstimator:constructor( typeFlag )
-- http://en.wikipedia.org/wiki/Quantile
self.typeFlag = typeFlag
local getIndex = self.getIndex
local stdLookup = function(data, h )
local h_low = mathfloor(h)
local x_low = getIndex(self, data, h_low )
local x_up = getIndex(self, data, h_low +1 )
return x_low + (h - h_low) * (x_up - x_low)
end
if typeFlag == 1 then
-- R1
self.getValue = function(self, percentile, data)
local h= #data * percentile
return getIndex(self, data, mathceil(h) )
end
elseif typeFlag == 2 then
-- R2
self.getValue = function(self, percentile, data)
local h= #data * percentile + 0.5
return 0.5*(getIndex(self, data, mathceil(h-0.5)) + getIndex(self, data, mathfloor(h+0.5) ) )
end
elseif typeFlag == 3 then
-- R3
self.getValue = function(self, percentile, data)
local h= #data * percentile
return getIndex(self, data, pgfluamathfunctions.round(h) )
end
elseif typeFlag == 4 then
-- R4
self.getValue = function(self, percentile, data)
local h= #data * percentile
return stdLookup(data,h)
end
elseif typeFlag == 5 then
-- R5
self.getValue = function(self, percentile, data)
local h= #data * percentile + 0.5
return stdLookup(data,h)
end
elseif typeFlag == 6 then
-- R6
self.getValue = function(self, percentile, data)
local h= (#data +1) * percentile
return stdLookup(data,h)
end
elseif typeFlag == 7 then
-- R7 (Excel)
self.getValue = function(self, percentile, data)
local h= (#data -1) * percentile + 1
return stdLookup(data,h)
end
elseif typeFlag == 8 then
-- R8
self.getValue = function(self, percentile, data)
local h= (#data + 1/3) * percentile + 1/3
return stdLookup(data,h)
end
elseif typeFlag == 9 then
-- R9
self.getValue = function(self, percentile, data)
local h= (#data + 1/4) * percentile + 3/8
return stdLookup(data,h)
end
else
error("Got unsupported type '" .. tostring(typeFlag) .. "'")
end
end
getPercentileEstimator = function(estimatorName)
if estimatorName == "legacy" then
return LegacyPgfplotsPercentileEstimator.new()
elseif estimatorName == "legacy*" then
return LegacyBadPgfplotsPercentileEstimator.new()
elseif estimatorName == "R1" then
return ParameterizedPercentileEstimator.new(1)
elseif estimatorName == "R2" then
return ParameterizedPercentileEstimator.new(2)
elseif estimatorName == "R3" then
return ParameterizedPercentileEstimator.new(3)
elseif estimatorName == "R4" then
return ParameterizedPercentileEstimator.new(4)
elseif estimatorName == "R5" then
return ParameterizedPercentileEstimator.new(5)
elseif estimatorName == "R6" then
return ParameterizedPercentileEstimator.new(6)
elseif estimatorName == "R7" then
return ParameterizedPercentileEstimator.new(7)
elseif estimatorName == "R8" then
return ParameterizedPercentileEstimator.new(8)
elseif estimatorName == "R9" then
return ParameterizedPercentileEstimator.new(9)
end
error("Unknown estimator '" .. tostring(estimatorName) .. "'")
end
BoxPlotRequest = newClass()
-- @param lowerQuartialPercent: typically 0.25
-- @param upperQuartialPercent: typically 0.75
-- @param whiskerRange: typically 1.5
-- @param estimator: an instance of PercentileEstimator
-- @param morePercentiles: either nil or an array of percentiles to compute
function BoxPlotRequest:constructor(lowerQuartialPercent, upperQuartialPercent, whiskerRange, estimator, morePercentiles)
if not lowerQuartialPercent or not upperQuartialPercent or not whiskerRange or not estimator then error("Arguments must not be nil") end
self.lowerQuartialPercent = pgftonumber(lowerQuartialPercent)
self.upperQuartialPercent = pgftonumber(upperQuartialPercent)
self.whiskerRange = pgftonumber(whiskerRange)
self.estimator = estimator
if not morePercentiles then
self.morePercentiles = {}
else
self.morePercentiles = morePercentiles
end
end
-------------------------------------------------------
BoxPlotResponse = newClass()
function BoxPlotResponse:constructor()
self.lowerWhisker = nil
self.lowerQuartile = nil
self.median = nil
self.upperQuartile = nil
self.upperWhisker = nil
self.average = nil
self.morePercentiles = {}
self.outliers = {}
end
-- @param boxPlotRequest an instance of BoxPlotRequest
-- @param data an indexed array with float values
-- @return an instance of BoxPlotResponse
function boxPlotCompute(boxPlotRequest, data)
if not boxPlotRequest or not data then error("Arguments must not be nil") end
for i = 1,#data do
local data_i = data[i]
if data_i == nil or type(data_i) ~= "number" then
error("Illegal input array at index " .. tostring(i) .. ": " .. tostring(data_i))
end
end
table.sort(data)
local sum = 0
for i = 1,#data do
sum = sum + data[i]
end
local numCoords = #data
local lowerWhisker
local lowerQuartile = boxPlotRequest.estimator:getValue(boxPlotRequest.lowerQuartialPercent, data)
local median = boxPlotRequest.estimator:getValue(0.5, data)
local upperQuartile = boxPlotRequest.estimator:getValue(boxPlotRequest.upperQuartialPercent, data)
local morePercentileValues = {}
for i = 1,#boxPlotRequest.morePercentiles do
morePercentileValues[i] = boxPlotRequest.estimator:getValue(boxPlotRequest.morePercentiles[i], data)
end
local upperWhisker
local average = sum / numCoords
local whiskerRange = boxPlotRequest.whiskerRange
local whiskerWidth = whiskerRange*(upperQuartile - lowerQuartile)
local upperWhiskerValue = upperQuartile + whiskerWidth
local lowerWhiskerValue = lowerQuartile - whiskerWidth
local outliers = {}
for i = 1,numCoords do
local current = data[i]
if current < lowerWhiskerValue then
table.insert(outliers, current)
else
lowerWhisker = current
break
end
end
for i = numCoords,1,-1 do
local current = data[i]
if upperWhiskerValue < current then
table.insert(outliers, current)
else
upperWhisker = current
break
end
end
local result = BoxPlotResponse.new()
result.lowerWhisker = lowerWhisker
result.lowerQuartile = lowerQuartile
result.median = median
result.upperQuartile = upperQuartile
result.upperWhisker = upperWhisker
result.average = average
result.morePercentiles = morePercentileValues
result.outliers = outliers
return result
end
-------------------------------------------------------
-- Replicates the survey phase of \pgfplotsplothandlerboxplot
BoxPlotPlothandler = newClassExtends(Plothandler)
-- drawDirection : either "x" or "y".
function BoxPlotPlothandler:constructor(boxPlotRequest, drawDirection, drawPosition, axis, pointmetainputhandler)
if not boxPlotRequest or not drawDirection or not drawPosition then error("Arguments must not be nil") end
Plothandler.constructor(self,"boxplot", axis, pointmetainputhandler)
self.boxPlotRequest = boxPlotRequest
local function evaluateDrawPosition()
local result = pgfmathparse(drawPosition)
return result
end
if drawDirection == "x" then
self.boxplotsetxy = function (a,b) return a,evaluateDrawPosition() + b end
elseif drawDirection == "y" then
self.boxplotsetxy = function (a,b) return evaluateDrawPosition() + b,a end
else
error("Illegal argument drawDirection="..tostring(drawDirection) )
end
end
function BoxPlotPlothandler:surveystart()
self.boxplotInput = {}
self.boxplotSurveyMode = true
end
function BoxPlotPlothandler:surveyend()
self.boxplotSurveyMode = false
local computed = boxPlotCompute( self.boxPlotRequest, self.boxplotInput )
local texResult =
"\\pgfplotsplothandlersurveyend@boxplot@set{lower whisker}{" .. toTeXstring(computed.lowerWhisker) .. "}" ..
"\\pgfplotsplothandlersurveyend@boxplot@set{lower quartile}{" .. toTeXstring(computed.lowerQuartile) .. "}" ..
"\\pgfplotsplothandlersurveyend@boxplot@set{median}{" .. toTeXstring(computed.median) .. "}" ..
"\\pgfplotsplothandlersurveyend@boxplot@set{upper quartile}{" .. toTeXstring(computed.upperQuartile) .. "}" ..
"\\pgfplotsplothandlersurveyend@boxplot@set{upper whisker}{" .. toTeXstring(computed.upperWhisker) .. "}" ..
"\\pgfplotsplothandlersurveyend@boxplot@set{sample size}{" .. toTeXstring(# self.boxplotInput) .. "}"
self.boxplotInput = nil
Plothandler.surveystart(self)
local outliers = computed.outliers
for i =1,#outliers do
local outlier = outliers[i]
local pt = Coord.new()
-- this here resembles \pgfplotsplothandlersurveypoint@boxplot@prepared when it is invoked during boxplot:
local X,Y = self.boxplotsetxy(outlier, 0)
pt.x = { X, Y, nil }
Plothandler.surveypoint(self,pt)
end
Plothandler.surveyend(self)
return texResult
end
function BoxPlotPlothandler:semiSurveyedValue(data)
local result = pgftonumber(data)
if result then
table.insert( self.boxplotInput, result )
end
end
function BoxPlotPlothandler:surveypoint(pt)
if self.boxplotSurveyMode then
error("Unsupported Operation encountered: box plot survey in LUA are only in PARTIAL mode (i.e. only if almost all has been prepared in TeX. Use 'lua backend=false' to get around this.")
else
Plothandler.surveypoint(self,pt)
end
end
-------------------------------------------------------
end
|
-- vi: expandtab ts=2 sw=2
local fn = vim.fn
local api = vim.api
local cmd = vim.cmd
local function tryload(module)
local has_mod,mod = pcall(require,module)
if has_mod then
return mod
end
end
local M = {}
-- highlight groups
M.colors = {
active = '%#StatusLine#',
inactive = '%#StatuslineNC#',
mode = '%#Mode#',
git = '%#Git#',
file = '%#File#',
lsp = '%#Lsp#',
filetype = '%#Filetype#',
line_col = '%#LineCol#',
perc = '%#Percentage#',
char = '%#Char#',
}
M.trunc_width = setmetatable({
mode = 90,
git_status = 90,
filename = 140,
line_col = 60,
}, {
__index = function()
return 80
end
})
M.is_truncated = function(_, width)
local current_width = api.nvim_win_get_width(0)
return current_width < width
end
M.modes = setmetatable({
['n'] = {'Normal', 'N'};
['no'] = {'N-Pending', 'N-P'} ;
['v'] = {'Visual', 'V' };
['V'] = {'V-Line', 'V-L' };
[''] = {'V-Block', 'V-B'}; -- this is not ^V, but it's , they're different
['s'] = {'Select', 'S'};
['S'] = {'S-Line', 'S-L'};
[''] = {'S·Block', 'S-B'}; -- same with this one, it's not ^S but it's
['i'] = {'Insert', 'I'};
['ic'] = {'Insert', 'I'};
['R'] = {'Replace', 'R'};
['Rv'] = {'V-Replace', 'V-R'};
['c'] = {'Command', 'C'};
['cv'] = {'Vim-Ex ', 'V-E'};
['ce'] = {'Ex ', 'E'};
['r'] = {'Prompt ', 'P'};
['rm'] = {'More ', 'M'};
['r?'] = {'Confirm ', 'C'};
['!'] = {'Shell ', 'S'};
['t'] = {'Terminal ', 'T'};
}, {
__index = function()
return {'Unknown', 'U'} -- handle edge cases
end
})
M.get_current_mode = function(self)
local current_mode = api.nvim_get_mode().mode
if self:is_truncated(self.trunc_width.mode) then
return string.format(' %s ', self.modes[current_mode][2]):upper()
end
return string.format(' %s ', self.modes[current_mode][1]):upper()
end
M.get_git_status = function(self)
-- use fallback because it doesn't set this variable on the initial `BufEnter`
local signs = vim.b.gitsigns_status_dict or {head = '', added = 0, changed = 0, removed = 0}
local is_head_empty = signs.head ~= ''
if self:is_truncated(self.trunc_width.git_status)
or ( signs.added == nil and signs.changed == nil and signs.removed == nil ) then
return is_head_empty and string.format(' %s ', signs.head or '') or ''
end
return is_head_empty and string.format(
' +%s ~%s -%s | %s ',
signs.added, signs.changed, signs.removed, signs.head
) or ''
end
M.get_filename = function(self)
return ' %<%f '
end
M.get_filetype = function()
local icons = tryload('nvim-web-devicons')
local file_name, file_ext = fn.expand('%:t'), fn.expand('%:e')
local icon = icons and icons.get_icon(file_name, file_ext, { default = true })
local filetype = vim.bo.filetype
if filetype == '' or filetype == nil then
return ''
elseif icon == '' or icon == nil then
return string.format(' %s ', filetype):lower()
end
return string.format(' %s %s ', icon, filetype):lower()
end
M.get_character = function(self)
if self:is_truncated(self.trunc_width.line_col) then
return ''
end
return ' 0x%04B '
end
M.get_line_col = function(self)
if self:is_truncated(self.trunc_width.line_col) then
return ' %l:%c '
end
return ' Ln %l, Col %c '
end
M.get_lsp_diagnostic = function(self)
local result = {}
local levels = {
errors = 'Error',
warnings = 'Warning',
info = 'Information',
hints = 'Hint'
}
for k, level in pairs(levels) do
result[k] = vim.lsp.diagnostic.get_count(0, level)
end
if self:is_truncated(120) then
return ''
else
return string.format(
' :%s :%s :%s :%s ',
result['errors'] or 0, result['warnings'] or 0,
result['info'] or 0, result['hints'] or 0
)
end
end
M.set_active = function(self)
local colors = self.colors
cmd('hi Mode ctermfg=Black ctermbg=Yellow')
cmd('hi Git ctermfg=Black ctermbg=DarkGray')
cmd('hi File ctermfg=DarkGray')
cmd('hi Lsp ctermbg=LightMagenta ctermfg=Black')
cmd('hi FileType ctermbg=LightBlue ctermfg=Black')
cmd('hi LineCol ctermbg=DarkBlue ctermfg=Black')
cmd('hi Percentage ctermbg=Red ctermfg=White')
cmd('hi Char ctermbg=Yellow ctermfg=Black')
return table.concat({
colors.active,
colors.mode .. self:get_current_mode(),
colors.git .. self:get_git_status(),
colors.file .. self:get_filename(),
'%=',
colors.lsp .. self:get_lsp_diagnostic(),
colors.filetype .. self:get_filetype(),
colors.line_col .. self:get_line_col(),
colors.perc .. ' %p%% ',
colors.char .. self:get_character(),
})
end
M.set_inactive = function(self)
return self.colors.inactive .. '%= %F %='
end
M.set_explorer = function(self)
local title = self.colors.mode .. ' '
return table.concat({ self.colors.active, title })
end
Statusline = setmetatable(M, {
__call = function(statusline, mode)
if mode == 'active' then return statusline:set_active() end
if mode == 'inactive' then return statusline:set_inactive() end
if mode == 'explorer' then return statusline:set_explorer() end
end
})
api.nvim_exec([[
augroup Statusline
au!
au WinEnter,BufEnter * setlocal statusline=%!v:lua.Statusline('active')
au WinLeave,BufLeave * setlocal statusline=%!v:lua.Statusline('inactive')
au WinEnter,BufEnter,FileType NvimTree setlocal statusline=%!v:lua.Statusline('explorer')
augroup END
]], false)
|
local options = rbxmk.load{rbxmk.path{"$sd/options.lua"}, ...}
rbxmk.load{rbxmk.path{"$sd/defines.lua"}, options}
if options.help then
print(rbxmk.load{rbxmk.path{"$sd/help.lua"}})
return
end
local targetPath = options.target
if type(targetPath) ~= "string" then
error("options.target: string expected, got " .. type(targetPath))
end
----------------------------------------------------------------
----------------------------------------------------------------
-- Encode instance path table into a string.
local function encodePath(path)
return table.concat(path, ".")
end
-- Decode an instance path string into a table.
local function newPath(path)
local t = {}
if type(path) == "table" then
for i, v in ipairs(path) do
if type(v) ~= "string" then
return nil, string.format("index %d: string expected, got %s", i, type(v))
end
t[i] = v
end
elseif type(path) == "string" then
-- TODO: make more robust.
for element in string.gmatch(path, "[^%.]+") do
t[#t+1] = element
end
else
return nil, "table or string expected, got " .. type(path)
end
t.string = encodePath(t)
return t, nil
end
-- Compare instance path tables.
local function comparePaths(a, b)
if #a ~= #b then
return false
end
for i, v in ipairs(a) do
if b[i] ~= v then
return false
end
end
return true
end
-- Load a script from a file and run the preprocessor on it.
local function processScript(format, name, ...)
local script = rbxmk.input{format=format, rbxmk.path{...}}
if name then
rbxmk.map{
rbxmk.output{script, "Name"},
rbxmk.input{"generate://Value", string.format('string="%s"', name)},
}
end
local ok, script = pcall(rbxmk.filter, {"preprocess", script})
if not ok then
return nil, script
end
return script, nil
end
-- Generate a Folder instance of the given name.
local function createFolder(name)
return rbxmk.input{"generate://Instance", string.format('Folder{Name:string="%s"}', name)}
end
-- Validate and add map to mappings table.
local function addMapping(mappings, map)
if type(map) ~= "table" then
return "table expected, got " .. type(map)
end
local source = map.source
if type(source) ~= "string" then
return "field 'source': string expected, got " .. type(source)
end
local target, err = newPath(map.target)
if err then
return "field 'target': " .. err
end
local extension = map.extension
if extension ~= nil and type(extension) ~= "string" then
return "field 'extension': string expected, got " .. type(extension)
end
local excluded = map.excluded
if excluded ~= nil and type(excluded) ~= "boolean" then
return "field 'excluded': boolean expected, got " .. type(excluded)
end
local shared = map.shared
if shared ~= nil and type(shared) ~= "boolean" then
return "field 'shared': boolean expected, got " .. type(shared)
end
table.insert(mappings, {
source = rbxmk.path{source},
target = target,
extension = extension or ".modulescript.lua",
excluded = excluded or false,
shared = shared or false,
})
return nil
end
-- Retrieve modules from mapping.
local function resolveMapping(map, priority)
local sourcePath = rbxmk.path{map.source}
local ok, files = pcall(rbxmk.readdir, {sourcePath})
if not ok then
return files
end
local modules = {}
local function findModules(name, files)
for _, info in ipairs(files) do
if info.isdir then
table.insert(name, info.name)
local ok, subfiles = pcall(rbxmk.readdir, {rbxmk.path{sourcePath, unpack(name)}})
if ok then
findModules(name, subfiles)
end
table.remove(name)
elseif rbxmk.filename{info.name, "fext"} == map.extension then
table.insert(name, info.name)
local modulePath = rbxmk.path{unpack(name)}
table.remove(name)
table.insert(name, rbxmk.filename{info.name, "fstem"})
table.insert(modules, {
source = map.source,
path = modulePath,
name = newPath(name),
target = map.target,
priority = priority,
excluded = map.excluded,
shared = map.shared,
})
table.remove(name)
end
end
end
findModules({}, files)
map.modules = modules
end
-- Add module to list only if it is uniquely named.
local function insertModule(modules, module)
if module.untracked then
table.insert(modules, module)
return nil
end
for _, prev in ipairs(modules) do
if comparePaths(prev.name, module.name) then
return prev
end
end
table.insert(modules, module)
return nil
end
-- Write module to an output.
local function writeModule(input, output, module)
if module.excluded then
return nil
end
-- Ensure path exists.
local slice = {}
for _, name in ipairs(module.target) do
table.insert(slice, name)
local ok = pcall(rbxmk.input, {input, encodePath(slice)})
if not ok then
table.remove(slice)
if #slice == 0 then
-- Add to root.
rbxmk.map{output, createFolder(name)}
else
-- Add to descendant.
rbxmk.map{
rbxmk.output{input, encodePath(slice)},
createFolder(name),
}
end
table.insert(slice, name)
end
end
-- Write module.
local script, err = processScript(
"modulescript.lua",
module.name[#module.name],
module.source, module.path
)
if err ~= nil then
error(module.name.string .. ": " .. err)
end
rbxmk.map{
rbxmk.output{output, module.target.string},
script,
}
end
----------------------------------------------------------------
----------------------------------------------------------------
-- Add mappings.
local Mappings = {}
for i, map in ipairs(options.mappings) do
local err = addMapping(Mappings, map)
if err ~= nil then
error(string.format("options.mappings[%d]: %s", i, err))
end
end
-- Resolve mappings.
for i, map in ipairs(Mappings) do
local err = resolveMapping(map, i)
if err ~= nil then
error(string.format("mappings[%d]: %s", i, err))
end
end
-- Merge modules.
local Modules = {}
if options.mainserver then
local path = rbxmk.path{options.mainserver}
insertModule(Modules, {
source = rbxmk.filename{path, "dir"},
path = rbxmk.filename{path, "base"},
name = newPath("Main"),
target = newPath("ServerScriptService"),
priority = 0,
untracked = true,
})
end
if options.mainclient then
local path = rbxmk.path{options.mainclient}
insertModule(Modules, {
source = rbxmk.filename{path, "dir"},
path = rbxmk.filename{path, "base"},
name = newPath("Main"),
target = newPath("ReplicatedFirst"),
priority = 0,
untracked = true,
})
end
for i, map in ipairs(Mappings) do
for _, module in ipairs(map.modules) do
local prev = insertModule(Modules, module)
if prev then
print(string.format("mappings[%d]: ignored %s, already defined in mappings[%d]", i, module.name.string, prev.priority))
end
end
end
-- Exclude modules.
for _, module in ipairs(Modules) do
local include = options.modules[module.name.string]
if include ~= nil then
module.excluded = not include
end
end
-- Sort by priority, then name.
table.sort(Modules, function(a, b)
if a.priority == b.priority then
return a.name.string < b.name.string
end
return a.priority < b.priority
end)
-- Generate module manifests.
local ModuleTargets = {}
local SharedManifest = {}
local ServerManifest = {}
for _, module in ipairs(Modules) do
if not module.untracked then
if ModuleTargets[module.target.string] == nil then
table.insert(ModuleTargets, string.format("%q", module.target.string))
ModuleTargets[module.target.string] = #ModuleTargets
end
end
end
for _, module in ipairs(Modules) do
if not module.untracked then
local data = string.format("[%q]=%d", module.name.string, ModuleTargets[module.target.string])
if module.shared then
table.insert(SharedManifest, data)
else
table.insert(ServerManifest, data)
end
end
end
ModuleTargets = "{" .. table.concat(ModuleTargets, ",") .. "}"
SharedManifest = "{" .. table.concat(SharedManifest, ",") .. "}"
ServerManifest = "{" .. table.concat(ServerManifest, ",") .. "}"
----------------------------------------------------------------
----------------------------------------------------------------
-- Define variable for the preprocessor, causing `--[[#Core]]` to resolve to
-- code that loads the Core module.
rbxmk.configure{
define = {
Core = rbxmk.input{rbxmk.path{"$sd/loadcore.lua"}},
},
}
-- Define variables specified in options.
rbxmk.configure{define = options.define}
-- Load clean-slate place file.
local targetInput = rbxmk.load{rbxmk.path{"$sd/template.lua"}}
-- Create an output to write directly to the target in-memory.
local targetOutput = rbxmk.output{targetInput}
-- Add Core module.
do
local core = processScript("modulescript.lua", nil, "$sd/../scripts/Core.lua")
core = rbxmk.filter{"region", core, "ModuleTargets", ModuleTargets}
core = rbxmk.filter{"region", core, "ServerManifest", ServerManifest}
core = rbxmk.filter{"region", core, "SharedManifest", SharedManifest}
rbxmk.map{rbxmk.output{targetOutput, "ReplicatedFirst"}, core}
end
-- Add bootstrappers.
rbxmk.map{
rbxmk.output{targetOutput, "ServerScriptService"},
processScript("script.lua", "Bootstrap", "$sd/../scripts/BootstrapServer.lua"),
}
rbxmk.map{
rbxmk.output{targetOutput, "ReplicatedFirst"},
processScript("localscript.lua", "Bootstrap", "$sd/../scripts/BootstrapClient.lua"),
}
-- Add modules.
for _, module in ipairs(Modules) do
local err = writeModule(targetInput, targetOutput, module)
if err ~= nil then
error(string.format("module %q: %s", module.name.string, err))
end
end
-- Write to file.
rbxmk.delete{rbxmk.output{targetPath}}
rbxmk.map{targetInput, rbxmk.output{targetPath}}
if options.debug then
print("Module (priority : excluded : shared : source => target )")
print("-----------------------------------------------------------------------------------------------------------------------------------------------")
for _, module in pairs(Modules) do
rbxmk.printf{"%-9s (%-8d : %-8s : %-6s : %-64s => %-32s)\n",
module.name.string,
module.priority,
module.excluded,
module.shared,
rbxmk.path{module.source, module.path},
module.target.string,
}
end
end
|
assert(Skada, "Skada not found!")
Skada:AddLoadableModule("Friendly Fire", function(Skada, L)
if Skada:IsDisabled("Friendly Fire") then return end
local mod = Skada:NewModule(L["Friendly Fire"])
local spellmod = mod:NewModule(L["Damage spell list"])
local targetmod = mod:NewModule(L["Damage target list"])
local pairs, ipairs, select, format = pairs, ipairs, select, string.format
local getSpellInfo, tContains = Skada.getSpellInfo or GetSpellInfo, tContains
local _
-- spells in the following table will be ignored.
local ignoredSpells = {}
local function log_damage(set, dmg)
if dmg.spellid and tContains(ignoredSpells, dmg.spellid) then return end
local player = Skada:get_player(set, dmg.playerid, dmg.playername, dmg.playerflags)
if player then
Skada:AddActiveTime(player, dmg.amount > 0)
player.friendfire = (player.friendfire or 0) + dmg.amount
set.friendfire = (set.friendfire or 0) + dmg.amount
-- spell
player.friendfire_spells = player.friendfire_spells or {}
player.friendfire_spells[dmg.spellid] = (player.friendfire_spells[dmg.spellid] or 0) + dmg.amount
-- saving this to total set may become a memory hog deluxe.
if set == Skada.current and dmg.dstName then
player.friendfire_targets = player.friendfire_targets or {}
player.friendfire_targets[dmg.dstName] = (player.friendfire_targets[dmg.dstName] or 0) + dmg.amount
end
end
end
local dmg = {}
local function SpellDamage(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
if srcGUID ~= dstGUID then
local amount, absorbed
if eventtype == "SWING_DAMAGE" then
dmg.spellid = 6603
amount, _, _, _, _, absorbed = ...
else
dmg.spellid, _, _, amount, _, _, _, _, absorbed = ...
end
dmg.playerid = srcGUID
dmg.playername = srcName
dmg.playerflags = srcFlags
dmg.dstName = dstName
dmg.amount = (amount or 0) + (absorbed or 0)
log_damage(Skada.current, dmg)
log_damage(Skada.total, dmg)
end
end
function targetmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's targets"], label)
end
function targetmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's targets"], player.name)
local total = player.friendfire or 0
if total > 0 and player.friendfire_targets then
local maxvalue, nr = 0, 1
for targetname, amount in pairs(player.friendfire_targets) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = targetname
d.label = targetname
d.value = amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Damage,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function spellmod:Enter(win, id, label)
win.playerid, win.playername = id, label
win.title = format(L["%s's damage"], label)
end
function spellmod:Update(win, set)
local player = Skada:find_player(set, win.playerid, win.playername)
if player then
win.title = format(L["%s's damage"], player.name)
local total = player.friendfire or 0
if total > 0 and player.friendfire_spells then
local maxvalue, nr = 0, 1
for spellid, amount in pairs(player.friendfire_spells) do
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.spellid = spellid
d.label, _, d.icon = getSpellInfo(spellid)
d.value = amount
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
mod.metadata.columns.Damage,
Skada:FormatPercent(d.value, total),
mod.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
win.metadata.maxvalue = maxvalue
end
end
end
function mod:Update(win, set)
win.title = L["Friendly Fire"]
local total = set.friendfire or 0
if total > 0 then
local maxvalue, nr = 0, 1
for _, player in ipairs(set.players) do
if (player.friendfire or 0) > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.text = Skada:FormatName(player.name, player.id)
d.class = player.class
d.role = player.role
d.spec = player.spec
d.value = player.friendfire
d.valuetext = Skada:FormatValueText(
Skada:FormatNumber(d.value),
self.metadata.columns.Damage,
Skada:FormatPercent(d.value, total),
self.metadata.columns.Percent
)
if d.value > maxvalue then
maxvalue = d.value
end
nr = nr + 1
end
end
win.metadata.maxvalue = maxvalue
end
end
function mod:OnEnable()
self.metadata = {
showspots = true,
click1 = spellmod,
click2 = targetmod,
nototalclick = {targetmod},
columns = {Damage = true, Percent = true},
icon = "Interface\\Icons\\inv_gizmo_supersappercharge"
}
Skada:RegisterForCL(SpellDamage, "DAMAGE_SHIELD", {dst_is_interesting_nopets = true, src_is_interesting_nopets = true})
Skada:RegisterForCL(SpellDamage, "DAMAGE_SPLIT", {dst_is_interesting_nopets = true, src_is_interesting_nopets = true})
Skada:RegisterForCL(SpellDamage, "RANGE_DAMAGE", {dst_is_interesting_nopets = true, src_is_interesting_nopets = true})
Skada:RegisterForCL(SpellDamage, "SPELL_BUILDING_DAMAGE", {dst_is_interesting_nopets = true, src_is_interesting_nopets = true})
Skada:RegisterForCL(SpellDamage, "SPELL_DAMAGE", {dst_is_interesting_nopets = true, src_is_interesting_nopets = true})
Skada:RegisterForCL(SpellDamage, "SPELL_EXTRA_ATTACKS", {dst_is_interesting_nopets = true, src_is_interesting_nopets = true})
Skada:RegisterForCL(SpellDamage, "SPELL_PERIODIC_DAMAGE", {dst_is_interesting_nopets = true, src_is_interesting_nopets = true})
Skada:RegisterForCL(SpellDamage, "SWING_DAMAGE", {dst_is_interesting_nopets = true, src_is_interesting_nopets = true})
Skada:AddMode(self, L["Damage Done"])
end
function mod:OnDisable()
Skada:RemoveMode(self)
end
function mod:GetSetSummary(set)
local value = set.friendfire or 0
return Skada:FormatNumber(value), value
end
end) |
local M = {}
function M.get(cp)
return {
TelescopeNormal = { bg = cp.black3 },
TelescopePromptNormal = { bg = cp.black4 },
TelescopePreviewNormal = { bg = cp.black1 },
TelescopeBorder = { bg = cp.black3, fg = cp.black3 },
TelescopePromptBorder = { bg = cp.black4, fg = cp.black4 },
TelescopePreviewBorder = { bg = cp.black1, fg = cp.black1 },
TelescopePromptTitle = { bg = cp.black4, fg = cp.red, style = 'italic' },
TelescopePreviewTitle = { bg = cp.black1, fg = cp.green, style = 'italic' },
}
end
return M
|
RegisterProtectedOsirisListener("CharacterKilledBy", Data.OsirisEvents.CharacterKilledBy, "after", function(defender, owner, attacker)
if GameHelpers.Character.IsPlayer(owner) then
CustomStatSystem:ModifyStat(owner, ID.Kills, 1, ModuleUUID)
end
end)
RegisterProtectedOsirisListener("CharacterDied", Data.OsirisEvents.CharacterDied, "after", function(character)
if GameHelpers.Character.IsPlayer(character) then
CustomStatSystem:ModifyStat(character, ID.Deaths, 1, ModuleUUID)
end
end)
RegisterProtectedOsirisListener("NRD_OnHeal", Data.OsirisEvents.NRD_OnHeal, "after", function(target, source, amount, handle)
if amount > 0 and GameHelpers.Character.IsPlayer(source) then
CustomStatSystem:ModifyStat(source, ID.HealingDone, amount, ModuleUUID)
end
end)
local hitSource = {}
---@param target EsvCharacter|EsvItem
---@param source EsvCharacter|nil
---@param data HitData
---@param hitStatus EsvStatusHit
RegisterListener("StatusHitEnter", function(target, source, data, hitStatus)
if source then
hitSource[data.HitContext.HitId] = source.MyGuid
end
end)
---@param target EsvCharacter
---@param attacker StatCharacter
---@param hit HitRequest
---@param causeType string
---@param impactDirection number[]
---@param context HitContext
local function OnBeforeCharacterApplyDamage(target, attacker, hit, causeType, impactDirection, context)
--fprint(LOGLEVEL.TRACE, "[OnBeforeCharacterApplyDamage] context.HitId(%s) hitSource[%s] = %s", context.HitId, context.HitId, hitSource[context.HitId])
--print("OnBeforeCharacterApplyDamage", target.DisplayName, hit.TotalDamageDone, attacker, (attacker and attacker.Character and attacker.Character.IsPlayer) or "No attacker", hit.DamageDealt, causeType)
local source = hitSource[context.HitId]
if source then
source = Ext.GetGameObject(source)
end
if hit.TotalDamageDone > 0 then
if not source then
if attacker and attacker.Character then
source = attacker.Character
end
end
if GameHelpers.Character.IsPlayer(source) then
CustomStatSystem:ModifyStat(source, ID.TotalDamage, hit.TotalDamageDone)
local highestHitStat = CustomStatSystem:GetStatByID(ID.LargestHit, ModuleUUID)
if highestHitStat then
local amount = highestHitStat:GetValue(source)
if amount < hit.TotalDamageDone then
CustomStatSystem:SetStat(source, ID.LargestHit, hit.TotalDamageDone, ModuleUUID)
end
end
end
end
if not source and attacker then
source = attacker.Character
end
end
RegisterProtectedExtenderListener("BeforeCharacterApplyDamage", OnBeforeCharacterApplyDamage)
RegisterStatusListener(Vars.StatusEvent.Applied, "DRAIN", function(target, status, source, statusType)
if GameHelpers.Character.IsPlayer(source) then
CustomStatSystem:ModifyStat(source, ID.SoulsEaten, 1)
end
end) |
local coroutine_pool = setmetatable({}, {
__mode = "kv"
})
local function co_create(f)
local co = table.remove(coroutine_pool)
if co == nil then
co = coroutine.create(function(...)
f(...)
while true do
f = nil
coroutine_pool[#coroutine_pool + 1] = co
f = coroutine.yield "SUSPEND"
f(coroutine.yield())
end
end)
else
coroutine.resume(co, f)
end
return co
end
local function fun1()
f = io.open("/dev/null", "w")
f:write("jjjjjjjjjjjjjj")
end
local t1 = os.time()
local m1 = collectgarbage('count')
for i = 1, 100000 do
-- coroutine.resume(coroutine.create(fun1)) -- 不用pool
coroutine.resume(co_create(fun1)) -- 用协程池
end
local m2 = collectgarbage('count')
local t2 = os.time()
print('diff time is ', t2 - t1)
print('diff mem is ', m2 - m1)
|
-- test_framebuffer.lua
package.path = package.path..";../?.lua"
local DRMCard = require("DRMCard")
-- Try to create a connection to a card first
local card, err = DRMCard();
if not card then
print("Error creating card: ", err)
return false;
end
|
local class = require 'libs.middleclass'
local Bullet = class('Bullet')
function Bullet:initialize(speed, width, height,bullets)
self.width = width
self.height = height
self.speed = speed
self.bullets = bullets
end
function Bullet:create(x,y)
self.x = x
self.y = y
table.insert(self.bullets, {x = self.x, y = self.y})
end
function Bullet:update(dt)
for i, v in ipairs(self.bullets) do
v.y = v.y - self.speed * dt
end
end
function Bullet:draw()
love.graphics.setColor(255, 255, 255)
for i, v in ipairs(self.bullets) do
love.graphics.rectangle("fill", v.x, v.y, self.width, self.height)
end
end
function Bullet:destroy()
for i, v in ipairs(self.bullets) do
if v.y >= love.graphics.getHeight() then
table.remove(self.bullets, i)
end
end
end
return Bullet |
--
-- gcc.lua
-- Provides GCC-specific configuration strings.
-- Copyright (c) 2002-2008 Jason Perkins and the Premake project
--
premake.gcc = { }
--
-- Set default tools
--
premake.gcc.cc = "gcc"
premake.gcc.cxx = "g++"
premake.gcc.ar = "ar"
--
-- Translation of Premake flags into GCC flags
--
local cflags =
{
EnableSSE = "-msse",
EnableSSE2 = "-msse2",
ExtraWarnings = "-Wall",
FatalWarnings = "-Werror",
FloatFast = "-ffast-math",
FloatStrict = "-ffloat-store",
NoFramePointer = "-fomit-frame-pointer",
Optimize = "-O2",
OptimizeSize = "-Os",
OptimizeSpeed = "-O3",
Symbols = "-g",
}
local cxxflags =
{
NoExceptions = "-fno-exceptions",
NoRTTI = "-fno-rtti",
}
--
-- Map platforms to flags
--
premake.gcc.platforms =
{
Native = {
cppflags = "-MMD -MP",
},
x32 = {
cppflags = "-MMD -MP",
flags = "-m32",
ldflags = "-L/usr/lib32",
},
x64 = {
cppflags = "-MMD -MP",
flags = "-m64",
ldflags = "-L/usr/lib64",
},
Universal = {
cppflags = "",
flags = "-arch i386 -arch x86_64 -arch ppc -arch ppc64",
},
Universal32 = {
cppflags = "",
flags = "-arch i386 -arch ppc",
},
Universal64 = {
cppflags = "",
flags = "-arch x86_64 -arch ppc64",
},
PS3 = {
cc = "ppu-lv2-g++",
cxx = "ppu-lv2-g++",
ar = "ppu-lv2-ar",
cppflags = "-MMD -MP",
}
}
local platforms = premake.gcc.platforms
--
-- Returns a list of compiler flags, based on the supplied configuration.
--
function premake.gcc.getcppflags(cfg)
local result = { }
table.insert(result, platforms[cfg.platform].cppflags)
return result
end
function premake.gcc.getcflags(cfg)
local result = table.translate(cfg.flags, cflags)
table.insert(result, platforms[cfg.platform].flags)
if cfg.system ~= "windows" and cfg.kind == "SharedLib" then
table.insert(result, "-fPIC")
end
return result
end
function premake.gcc.getcxxflags(cfg)
local result = table.translate(cfg.flags, cxxflags)
return result
end
--
-- Returns a list of linker flags, based on the supplied configuration.
--
function premake.gcc.getldflags(cfg)
local result = { }
-- OS X has a bug, see http://lists.apple.com/archives/Darwin-dev/2006/Sep/msg00084.html
if not cfg.flags.Symbols then
if cfg.system == "macosx" then
table.insert(result, "-Wl,-x")
else
table.insert(result, "-s")
end
end
if cfg.kind == "SharedLib" then
if cfg.system == "macosx" then
result = table.join(result, { "-dynamiclib", "-flat_namespace" })
else
table.insert(result, "-shared")
end
if cfg.system == "windows" and not cfg.flags.NoImportLib then
table.insert(result, '-Wl,--out-implib="' .. cfg.linktarget.fullpath .. '"')
end
end
if cfg.kind == "WindowedApp" and cfg.system == "windows" then
table.insert(result, "-mwindows")
end
local platform = platforms[cfg.platform]
table.insert(result, platform.flags)
table.insert(result, platform.ldflags)
return result
end
--
-- Return a list of library search paths. Technically part of LDFLAGS but need to
-- be separated because of the way Visual Studio calls GCC for the PS3. See bug
-- #1729227 for background on why library paths must be split.
--
function premake.gcc.getlibdirflags(cfg)
local result = { }
for _, value in ipairs(premake.getlinks(cfg, "all", "directory")) do
table.insert(result, '-L' .. _MAKE.esc(value))
end
return result
end
--
-- Returns a list of linker flags for library search directories and library
-- names. See bug #1729227 for background on why the path must be split.
--
function premake.gcc.getlinkflags(cfg)
local result = { }
for _, value in ipairs(premake.getlinks(cfg, "all", "basename")) do
if path.getextension(value) == ".framework" then
table.insert(result, '-framework ' .. _MAKE.esc(path.getbasename(value)))
else
table.insert(result, '-l' .. _MAKE.esc(value))
end
end
return result
end
--
-- Decorate defines for the GCC command line.
--
function premake.gcc.getdefines(defines)
local result = { }
for _,def in ipairs(defines) do
table.insert(result, '-D' .. def)
end
return result
end
--
-- Decorate include file search paths for the GCC command line.
--
function premake.gcc.getincludedirs(includedirs)
local result = { }
for _,dir in ipairs(includedirs) do
table.insert(result, "-I" .. _MAKE.esc(dir))
end
return result
end
|
require 'base'
require 'os'
MST_ONLY = Clock:new('MST', nil, CLOCK_FONT, 'Arizona')
MST_ONLY.condition(function() os.date("*t", os.time()).isdst end)
CLOCKS = {
Clock:new('EST5EDT', nil, BIG_CLOCK_FONT, 'DC'),
Clock:new('JST', nil, CLOCK_FONT, 'Tokyo'),
Clock:new('GMT', nil, CLOCK_FONT, 'UTC'),
Clock:new('CST6CDT', nil, CLOCK_FONT, 'CST6CDT'),
Clock:new('MST7MDT', nil, CLOCK_FONT, 'MST7MDT'),
MST_ONLY,
Clock:new('PST8PDT', nil, CLOCK_FONT, 'PST8PDT'),
}
wordlclock = {
call = function(self)
worldclock:all()
end, --call
colors = { '' },
all = function(self)
--itterate over list
for clock in clocks do
print('}')
end, --all
clocks = CLOCKS,
}
Clock = {
tz = 'UTC',
place = 'Universal Coordinated Time',
font_size = 9,
display_id = tz,
condition = function(self) return true end,
new = function(self, tz, place, font_size, display_id)
self.tz = tz or self.tz
self.utc_offset = utc_offset or self.utc_offset()
self.place = place or self.place
self.font_size = font_size or self.font_size
self.display_id = display_id or self.display_id
end, --new
label = function(self)
return display_id
end, --label
time = function(self, format)
format = format or '%H:%M'
local offset_c_time = posix.mktime(posix.gmtime())+utc_offset_sec()
return posix.strftime(format, offset_c_time)
end, --time
utc_offset = function(self)
local f = io.popen('LANG=C TZ='..tz..' date +"%z"')
local l = f:read("*a")
f:close()
return trim(l)
end, --utc_offset
utc_offset_int = function(self)
local offset = get_offset(tz)
local r_offset = offset.reverse()
local sign = roffset:sub(5) or '+'
local hour = tonumber(roffset:sub(3,4).reverse())
local min = tonumber(roffset:sub(1,2).reverse())
return tonumber(sign..((hour*60)+min)*60)
end, --utc_offset_int
}
function trim(s)
return s:find'^%s*$' and '' or s:match'^%s*(.*%S)'
end
|
local p = peripheral.find("redstoneProbe")
test.assert(p, "no capacitor")
|
local ucursor = require 'luci.model.uci'.cursor()
local json = require 'luci.jsonc'
local server_section = arg[1]
local local_port = arg[3]
local host = arg[4]
local server = ucursor:get_all('vssr', server_section)
local ss = {
server = host,
server_port = server.server_port,
local_address = '0.0.0.0',
local_port = local_port,
password = server.password,
timeout = (server.timeout ~= nil) and server.timeout or 60,
method = server.encrypt_method_ss,
reuse_port = true,
fast_open = (server.fast_open == '1') and true or false,
plugin = (server.plugin ~= nil) and server.plugin or nil,
plugin_opts = (server.plugin ~= nil) and server.plugin_opts or nil
}
print(json.stringify(ss, 1))
|
local Ball3DRender = class("Ball3DRender")
function Ball3DRender.new(nTag, rootBall)
local rbDes = { }
rbDes.disableSleep = true
rbDes.mass = 1.0
rbDes.shape = cc.Physics3DShape:createSphere(0)
Ball3DRender = cc.PhysicsSprite3D:create("gameBilliards/3d_ball/ball.c3b", rbDes)
if Ball3DRender then
local rigidBody = cc.Physics3DRigidBody:create(rbDes)
local component = cc.Physics3DComponent:create(rigidBody)
Ball3DRender:setTexture("gameBilliards/3d_ball/" .. nTag .. ".png")
Ball3DRender:setTag(g_EightBallData.g_Border_Tag.texture3D)
Ball3DRender:setScale((rootBall:getContentSize().width / 2) / g_EightBallData.radius_3D)
Ball3DRender:setCameraMask(cc.CameraFlag.USER2)
Ball3DRender:setGlobalZOrder(0 - nTag)
-- 这里如果想要真实台球摆放位置,用random设置角度
-- Ball3DRender:setRotation3D(cc.vec3(0.0,0.0,0.0))
Ball3DRender:setRotation3D(cc.vec3(math.random(0, 180), math.random(0, 180), math.random(0, 180)))
rigidBody:setAngularVelocity(cc.vec3(0.0, 0.0, 0.0))
end
return Ball3DRender
end
return Ball3DRender
--local rbDes = { }
--rbDes.disableSleep = true
--rbDes.mass = 1.0
--rbDes.shape = cc.Physics3DShape:createSphere(0)
--local Ball3DRender = class("Ball3DRender",
--function()
-- return cc.PhysicsSprite3D:create("gameBilliards/3d_ball/ball.c3b", rbDes)
--end )
----调整3D滚动效果
----@母体速度
----@母体角速度
--function Ball3DRender:adjust3DRolling(velocity,angularVelocity)
-- if self then
-- local rigidBody = self:getPhysicsObj()
-- if rigidBody then
-- rigidBody:setAngularVelocity(cc.vec3(- velocity.y / g_EightBallData.ballRollingRate, velocity.x / g_EightBallData.ballRollingRate, angularVelocity / g_EightBallData.ballRollingRate))
-- end
-- end
--end
---- 渲染3D
----@tag
----@母体球
--function Ball3DRender:ctor(nTag, rootBall)
-- local rigidBody = cc.Physics3DRigidBody:create(rbDes)
-- local component = cc.Physics3DComponent:create(rigidBody)
-- self:setTexture("gameBilliards/3d_ball/" .. nTag .. ".png")
-- self:setTag(g_EightBallData.g_Border_Tag.texture3D)
-- self:setScale((rootBall:getContentSize().width / 2) / g_EightBallData.radius_3D)
-- self:setCameraMask(cc.CameraFlag.USER2)
-- self:setGlobalZOrder(0-nTag)
-- --这里如果想要真实台球摆放位置,用random设置角度
-- --self:setRotation3D(cc.vec3(0.0,0.0,0.0))
-- self:setRotation3D(cc.vec3(math.random(0, 180), math.random(0, 180), math.random(0, 180)))
-- rigidBody:setAngularVelocity(cc.vec3(0.0, 0.0, 0.0))
--end
--return Ball3DRender |
--sandbox.lua
require("lualog")
local lstdfs = require("lstdfs")
local pairs = pairs
local loadfile = loadfile
local iopen = io.open
local mabs = math.abs
local tpack = table.pack
local tunpack = table.unpack
local tinsert = table.insert
local sformat = string.format
local dgetinfo = debug.getinfo
local file_time = lstdfs.last_write_time
local logger = quanta.logger
local load_files = {}
local search_path = {}
local function ssplit(str, token)
local t = {}
while #str > 0 do
local pos = str:find(token)
if pos then
tinsert(t, str:sub(1, pos - 1))
str = str:sub(pos + 1, #str)
else
t[#t + 1] = str
break
end
end
return t
end
--加载lua文件搜索路径
for _, path in ipairs(ssplit(package.path, ";")) do
search_path[#search_path + 1] = path:sub(1, path:find("?") - 1)
end
local function search_load(node)
local load_path = node.fullpath
if load_path then
node.time = file_time(load_path)
return loadfile(load_path)
end
local filename = node.filename
for _, path_root in pairs(search_path) do
local fullpath = path_root .. filename
local file = iopen(fullpath)
if file then
file:close()
node.fullpath = fullpath
node.time = file_time(fullpath)
return loadfile(fullpath)
end
end
return nil, "file not exist!"
end
local function try_load(node)
local trunk_func, err = search_load(node)
if not trunk_func then
logger:error(sformat("[sandbox][try_load] load file: %s ... [failed]\nerror : %s", node.filename, err))
return
end
local res = tpack(pcall(trunk_func))
if not res[1] then
logger:error(sformat("[sandbox][try_load] exec file: %s ... [failed]\nerror : %s", node.filename, res[2]))
return
end
logger:info(sformat("[sandbox][try_load] load file: %s ... [ok]", node.filename))
return tunpack(res, 2)
end
function import(filename)
local node = load_files[filename]
if not node then
node = { filename = filename }
load_files[filename] = node
end
if not node.time then
local res = try_load(node)
if res then
node.res = res
end
end
return node.res
end
function quanta.reload()
for path, node in pairs(load_files) do
local filetime = file_time(node.fullpath)
if mabs(node.time - filetime) > 1 then
try_load(node)
end
end
end
function quanta.get(name)
local global_obj = quanta[name]
if not global_obj then
local info = dgetinfo(2, "S")
logger:error(sformat("[quanta][get] %s not initial! source(%s:%s)", name, info.short_src, info.linedefined))
return
end
return global_obj
end
|
workspace "Sentry-Native"
function sentry_native_common()
language "C++"
cppdialect "C++14"
includedirs {
SRC_ROOT.."/include",
}
pic "on"
filter "system:macosx or linux"
toolset("clang")
filter "system:windows"
buildoptions {
"/wd4201", -- nonstandard extension used : nameless struct/union
}
filter "system:android"
defines {
"SENTRY_WITH_NULL_UNWINDER",
"SENTRY_WITH_INPROC_BACKEND",
}
links {
"log",
}
filter {}
end
-- Temporary disable specific projects for Android by adding this function call
function disable_for_android()
filter "system:android"
kind "SharedLib"
removefiles {
SRC_ROOT.."/**",
}
filter {}
end
function sentry_native_library()
libdirs {
"bin/Release",
}
files {
SRC_ROOT.."/src/**.c",
SRC_ROOT.."/src/**.h",
SRC_ROOT.."/src/**.cpp",
SRC_ROOT.."/src/**.hpp",
}
filter "system:macosx"
links {
"curl",
}
defines {
"SENTRY_WITH_LIBCURL_TRANSPORT",
}
filter "system:linux"
links {
"pthread",
"uuid",
"curl",
"dl",
}
defines {
"SENTRY_WITH_LIBCURL_TRANSPORT",
}
filter "system:windows"
links {
"winhttp.lib",
"dbghelp.lib",
"rpcrt4.lib", -- for UUID operations
}
defines {
"SENTRY_WITH_WINHTTP_TRANSPORT",
}
filter {}
end
project "sentry"
kind "SharedLib"
sentry_native_common()
sentry_native_library()
project "sentry_crashpad"
kind "SharedLib"
sentry_native_common()
sentry_native_library()
dependson {
"crashpad_handler"
}
defines {
"SENTRY_WITH_CRASHPAD_BACKEND"
}
includedirs {
CRASHPAD_PKG,
CRASHPAD_PKG.."/third_party/mini_chromium/mini_chromium",
}
-- Crashpad
links {
"crashpad_client",
"crashpad_util",
"crashpad_minichromium_base",
}
filter "system:macosx"
-- System
links {
"Foundation.framework",
"Security.framework",
"CoreText.framework",
"CoreGraphics.framework",
"IOKit.framework",
"bsm",
}
filter {}
disable_for_android()
project "sentry_breakpad"
kind "SharedLib"
sentry_native_common()
sentry_native_library()
defines {
"SENTRY_WITH_BREAKPAD_BACKEND"
}
buildoptions {
"-fvisibility=hidden",
}
includedirs {
BREAKPAD_PKG.."/src",
}
-- Breakpad
links {
"breakpad_client",
}
filter "system:macosx"
-- System
links {
"Foundation.framework",
"pthread",
}
defines {
}
filter {}
project "example"
kind "ConsoleApp"
sentry_native_common()
links {
"sentry",
}
files {
SRC_ROOT.."/examples/example.c",
}
-- make sure we have a build-id
filter "system:linux"
linkoptions { "-Wl,--build-id=uuid" }
filter {}
disable_for_android()
project "example_crashpad"
kind "ConsoleApp"
sentry_native_common()
links {
"sentry_crashpad"
}
dependson {
"crashpad_handler"
}
files {
SRC_ROOT.."/examples/example_crashpad.c",
}
disable_for_android()
project "example_breakpad"
kind "ConsoleApp"
sentry_native_common()
links {
"sentry_breakpad",
}
files {
SRC_ROOT.."/examples/example_breakpad.c",
}
disable_for_android()
project "test_sentry"
kind "ConsoleApp"
sentry_native_common()
-- We compile the exe, but with the library settings
sentry_native_library()
includedirs {
SRC_ROOT.."/src",
}
defines {
"SENTRY_WITH_TESTS"
}
files {
SRC_ROOT.."/tests/**.cpp",
}
-- make sure we have a build-id
filter "system:linux"
-- -E is needed on linux to make dladdr work on the main executable
linkoptions { "-Wl,--build-id=uuid,-E" }
filter {}
|
return {'arabier','arabisch','arabische','arabischtalig','aramees','arameeer','ara','arabesk','arabier','arabisatie','arabiseren','arabisering','arabist','arabistiek','arachideolie','arachnofobie','arak','aramide','aramidevezel','arabicakoffie','arachidonzuur','arab','arabica','arabie','arafurazee','aragon','aralmeer','ararat','ara','arabella','arafat','aram','aran','aranka','aras','arab','arabieren','arameeers','aramese','arabesken','arabisten','arabischtalige','aras','arabieren','arabiseerde','aras','arabellas','arafats','arams','arans','arankas','aras'} |
-- See LICENSE for terms
local mod_EnableMod
local function ModOptions(id)
-- id is from ApplyModOptions
if id and id ~= CurrentModId then
return
end
mod_EnableMod = CurrentModOptions:GetProperty("EnableMod")
end
-- load default/saved settings
OnMsg.ModsReloaded = ModOptions
-- fired when Mod Options>Apply button is clicked
OnMsg.ApplyModOptions = ModOptions
local function BlockRivalMileStones(func, ...)
if not mod_EnableMod then
return func(...)
end
end
local orig_AIContestMilestone = AIContestMilestone
function AIContestMilestone(...)
return BlockRivalMileStones(orig_AIContestMilestone, ...)
end
local orig_AIContestAnomaly = AIContestAnomaly
function AIContestAnomaly(...)
return BlockRivalMileStones(orig_AIContestAnomaly, ...)
end
local orig_UpdateCompetitionItems = UpdateCompetitionItems
function UpdateCompetitionItems(...)
return BlockRivalMileStones(orig_UpdateCompetitionItems, ...)
end
|
local wibox = require("wibox")
local awful = require("awful")
local watch = require("awful.widget.watch")
local beautiful = require("beautiful")
rhythmbox_widget = wibox.widget {
font = 'Play 9',
widget = wibox.widget.textbox
}
rhythmbox_icon = wibox.widget
watch(
"rhythmbox-client --no-start --print-playing", 1,
function(widget, stdout, stderr, exitreason, exitcode)
if string.len(stdout) > 33 then
stdout = string.sub(stdout, 0, 30) .. "..."
end
rhythmbox_widget:set_text(stdout)
end
)
widget = wibox.widget {
{
{
image = "/usr/share/icons/Adwaita/16x16/devices/audio-speakers-symbolic.symbolic.png",
resize = false,
widget = wibox.widget.imagebox
},
rhythmbox_widget,
layout = wibox.layout.fixed.horizontal
},
widget = wibox.container.background
}
return widget |
local Native = require('lib.native.native')
---@class ItemRealField
local ItemRealField = {
ScalingValue = Native.ConvertItemRealField(0x69736361), --ITEM_RF_SCALING_VALUE
}
return ItemRealField
|
require 'nnlr'
function createModel(nGPU)
-- from https://code.google.com/p/cuda-convnet2/source/browse/layers/layers-imagenet-1gpu.cfg
-- this is AlexNet that was presented in the One Weird Trick paper. http://arxiv.org/abs/1404.5997
local features = nn.Sequential()
local SpatialConvolution = nn.SpatialConvolutionMKLDNN
local ReLU = nn.ReLUMKLDNN
local SpatialMaxPooling = nn.SpatialMaxPoolingMKLDNN
local SBatchNorm = nn.SpatialBatchNormalizationMKLDNN
local LRN = nn.LRNMKLDNN
local conv1 = SpatialConvolution(3,96,11,11,4,4)
conv1:learningRate('weight', 1)
conv1:weightDecay('weight', 1)
conv1:learningRate('bias', 2)
conv1:weightDecay('bias', 0)
conv1.weight:normal(0, 0.01)
conv1.bias:fill(0)
local conv2 = SpatialConvolution(96,256,5,5,1,1,2,2,2)
conv2:learningRate('weight', 1)
conv2:weightDecay('weight', 1)
conv2:learningRate('bias', 2)
conv2:weightDecay('bias', 0)
conv2.weight:normal(0, 0.01)
conv2.bias:fill(0.1)
local conv3 = SpatialConvolution(256,384,3,3,1,1,1,1)
conv3:learningRate('weight', 1)
conv3:weightDecay('weight', 1)
conv3:learningRate('bias', 2)
conv3:weightDecay('bias', 0)
conv3.weight:normal(0, 0.01)
conv3.bias:fill(0)
local conv4 = SpatialConvolution(384,384,3,3,1,1,1,1,2)
conv4:learningRate('weight', 1)
conv4:weightDecay('weight', 1)
conv4:learningRate('bias', 2)
conv4:weightDecay('bias', 0)
conv4.weight:normal(0, 0.01)
conv4.bias:fill(0.1)
local conv5 = SpatialConvolution(384,256,3,3,1,1,1,1,2)
conv5:learningRate('weight', 1)
conv5:weightDecay('weight', 1)
conv5:learningRate('bias', 2)
conv5:weightDecay('bias', 0)
conv5.weight:normal(0, 0.01)
conv5.bias:fill(0.1)
local fc6 = nn.Linear(256*6*6, 4096)
fc6:learningRate('weight', 1)
fc6:weightDecay('weight', 1)
fc6:learningRate('bias', 2)
fc6:weightDecay('bias', 0)
fc6.weight:normal(0, 0.005)
fc6.bias:fill(0.1)
local fc7 = nn.Linear(4096, 4096)
fc7:learningRate('weight', 1)
fc7:weightDecay('weight', 1)
fc7:learningRate('bias', 2)
fc7:weightDecay('bias', 0)
fc7.weight:normal(0, 0.005)
fc7.bias:fill(0.1)
local fc8 = nn.Linear(4096, nClasses)
fc8:learningRate('weight', 1)
fc8:weightDecay('weight', 1)
fc8:learningRate('bias', 2)
fc8:weightDecay('bias', 0)
fc8.weight:normal(0, 0.01)
fc8.bias:fill(0)
features:add(conv1) -- 224 -> 55
features:add(ReLU(true))
features:add(LRN(5,0.0001,0.75))
features:add(SpatialMaxPooling(3,3,2,2)) -- 55 -> 27
features:add(conv2) -- 27 -> 27
features:add(ReLU(true))
features:add(LRN(5,0.0001,0.75))
features:add(SpatialMaxPooling(3,3,2,2)) -- 27 -> 13
features:add(conv3) -- 13 -> 13
features:add(ReLU(true))
features:add(conv4) -- 13 -> 13
features:add(ReLU(true))
features:add(conv5) -- 13 -> 13
features:add(ReLU(true))
features:add(SpatialMaxPooling(3,3,2,2)) -- 13 -> 6
local classifier = nn.Sequential()
classifier:add(nn.View(256*6*6))
classifier:add(fc6)
classifier:add(nn.ReLU())
classifier:add(nn.Dropout(0.5))
classifier:add(fc7)
classifier:add(nn.ReLU())
classifier:add(nn.Dropout(0.5))
classifier:add(fc8)
classifier:add(nn.LogSoftMax())
features:get(1).gradInput = nil
--classifier:cuda()
local model = nn.Sequential():add(features):add(classifier)
model.imageSize = 256
model.imageCrop = 227
return model
end
|
local function parse_args()
local cmd = torch.CmdLine()
cmd:option("-TrainingData", "", "path for your training data to distill")
cmd:option("-TopResponseFile", "", "path for your extracted top frequent responses")
cmd:option("-saveFolder", "", "directory for saving output data")
cmd:option("-batch_size", 1280, "")
cmd:option("-gpu_index", 1, "")
cmd:option("-distill_rate", 0.08, "the proportion of training data to distill in this round")
cmd:option("-dictPath", "data/movie_25000", "dictionary file")
cmd:option("-params_file", "", "hyperparameters for the pre-trained generative model")
cmd:option("-model_file", "", " path for loading a pre-trained generative model")
cmd:option("-save_summary", false, "whether to write a summary file")
local params = cmd:parse(arg)
print(params)
return params
end
return parse_args
|
-- ===========================================================================
-- Status Message Manager
-- Non-interactive messages that appear in the upper-center of the screen.
-- ===========================================================================
include( "InstanceManager" );
-- ===========================================================================
-- CONSTANTS
-- ===========================================================================
local DEFAULT_TIME_TO_DISPLAY :number = 10; -- Seconds to display the message
-- ===========================================================================
-- VARIABLES
-- ===========================================================================
local m_statusIM :table = InstanceManager:new( "StatusMessageInstance", "Root", Controls.StackOfMessages );
local m_gossipIM :table = InstanceManager:new( "GossipMessageInstance", "Root", Controls.StackOfMessages );
local PlayerConnectedChatStr :string = Locale.Lookup( "LOC_MP_PLAYER_CONNECTED_CHAT" );
local PlayerDisconnectedChatStr :string = Locale.Lookup( "LOC_MP_PLAYER_DISCONNECTED_CHAT" );
local PlayerKickedChatStr :string = Locale.Lookup( "LOC_MP_PLAYER_KICKED_CHAT" );
local m_kMessages :table = {};
-- ===========================================================================
-- FUNCTIONS
-- ===========================================================================
-- ===========================================================================
-- ===========================================================================
function OnStatusMessage( str:string, fDisplayTime:number, type:number )
if (type == ReportingStatusTypes.DEFAULT or
type == ReportingStatusTypes.GOSSIP) then -- A type we handle?
local kTypeEntry :table = m_kMessages[type];
if (kTypeEntry == nil) then
-- New type
m_kMessages[type] = {
InstanceManager = nil,
MessageInstances= {}
};
kTypeEntry = m_kMessages[type];
-- Link to the instance manager and the stack the UI displays in
if (type == ReportingStatusTypes.GOSSIP) then
kTypeEntry.InstanceManager = m_gossipIM;
else
kTypeEntry.InstanceManager = m_statusIM;
end
end
local pInstance:table = kTypeEntry.InstanceManager:GetInstance();
table.insert( kTypeEntry.MessageInstances, pInstance );
local timeToDisplay:number = (fDisplayTime > 0) and fDisplayTime or DEFAULT_TIME_TO_DISPLAY;
pInstance.StatusLabel:SetText( str );
pInstance.Anim:SetEndPauseTime( timeToDisplay );
pInstance.Anim:RegisterEndCallback( function() OnEndAnim(kTypeEntry,pInstance) end );
pInstance.Anim:SetToBeginning();
pInstance.Anim:Play();
pInstance.Button:RegisterCallback( Mouse.eLClick, function() OnMessageClicked(kTypeEntry,pInstance) end );
Controls.StackOfMessages:CalculateSize();
Controls.StackOfMessages:ReprocessAnchoring();
end
end
-- ===========================================================================
function OnEndAnim( kTypeEntry:table, pInstance:table )
RemoveMessage( kTypeEntry, pInstance );
end
-- ===========================================================================
function OnMessageClicked( kTypeEntry:table, pInstance:table )
RemoveMessage( kTypeEntry, pInstance );
end
-- ===========================================================================
function RemoveMessage( kTypeEntry:table, pInstance:table )
pInstance.Anim:ClearEndCallback();
Controls.StackOfMessages:CalculateSize();
Controls.StackOfMessages:ReprocessAnchoring();
kTypeEntry.InstanceManager:ReleaseInstance( pInstance );
end
----------------------------------------------------------------
function OnMultplayerPlayerConnected( playerID )
if( ContextPtr:IsHidden() == false and GameConfiguration.IsNetworkMultiplayer() ) then
local pPlayerConfig = PlayerConfigurations[playerID];
local statusMessage = Locale.Lookup(pPlayerConfig:GetPlayerName()) .. " " .. PlayerConnectedChatStr;
OnStatusMessage( statusMessage, DEFAULT_TIME_TO_DISPLAY, ReportingStatusTypes.DEFAULT );
end
end
----------------------------------------------------------------
function OnMultiplayerPrePlayerDisconnected( playerID )
if( ContextPtr:IsHidden() == false and GameConfiguration.IsNetworkMultiplayer() ) then
local pPlayerConfig = PlayerConfigurations[playerID];
local statusMessage = Locale.Lookup(pPlayerConfig:GetPlayerName());
if(Network.IsPlayerKicked(playerID)) then
statusMessage = statusMessage .. " " .. PlayerKickedChatStr;
else
statusMessage = statusMessage .. " " .. PlayerDisconnectedChatStr;
end
OnStatusMessage(statusMessage, DEFAULT_TIME_TO_DISPLAY, ReportingStatusTypes.DEFAULT);
end
end
-- ===========================================================================
-- Testing: When on the "G" and "D" keys generate messages.
-- ===========================================================================
function Test()
OnStatusMessage("Testing out A message", 10, ReportingStatusTypes.GOSSIP );
OnStatusMessage("Testing out BB message", 10, ReportingStatusTypes.GOSSIP );
ContextPtr:SetInputHandler(
function( pInputStruct )
local uiMsg = pInputStruct:GetMessageType();
if uiMsg == KeyEvents.KeyUp then
local key = pInputStruct:GetKey();
if key == Keys.D then OnStatusMessage("Testing out status message ajsdkl akds dk dkdkj dkdkd ajksaksdkjkjd dkadkj f djkdkjdkj dak sdkjdjkal dkd kd dk adkj dkkadj kdjd kdkjd jkd jd dkj djkd dkdkdjdkdkjdkd djkd dkd dkjd kdjdkj d", 10, ReportingStatusTypes.DEFAULT ); return true; end
if key == Keys.G then OnStatusMessage("Testing out gossip message", 10, ReportingStatusTypes.GOSSIP ); return true; end
end
return false;
end, true);
end
-- ===========================================================================
function Initialize()
Events.StatusMessage.Add( OnStatusMessage );
LuaEvents.Custom_StatusMessage.Add( OnStatusMessage );
Events.MultiplayerPlayerConnected.Add( OnMultplayerPlayerConnected );
Events.MultiplayerPrePlayerDisconnected.Add( OnMultiplayerPrePlayerDisconnected );
--Test();
end
Initialize(); |
zBTN = 3 -- GPIO0 button
zRelay = 6 -- GPIO12 PWM0 relay (active high)
zLED = 7 -- GPIO13 PWM1 GREEN LED (active low)
--pwm.setup(zLED, 1, 500)
--pwm.start(zLED)
gpio.mode(zBTN,gpio.INT)
pwm.stop(zLED)
gpio.write(zLED,1)
gpio.trig(zBTN, "both",function()
if gpio.read(zBTN)==0 then
pwm.stop(zLED)
gpio.write(zLED,0)
t1=tmr.now()
else
gpio.write(zLED,1)
t2=tmr.now()
t3=(t2-t1)/1000000
print(t3)
if t3<2 then
gpio.write(zLED,1)
print("start")
pwm.setup(zLED, 1, 500)
pwm.start(zLED)
else
print("config")
pwm.setup(zLED, 10, 500)
pwm.start(zLED)
end
end
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.