repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
estansifer/water-maze
config.lua
1
3488
require "patterns/patterns" --[[ Configuration (information below) ]] local watercolor = "blue" local pattern = Zoom(Maze2(), 32) -- local pattern = Distort(Distort(Distort(Zoom(Checkerboard(), 16), 64, 1), 32, 0.05), 256, 1) -- local pattern = Distort(Distort(Distort(Zoom(Checkerboard(), 32), 256, 3.0), 128, 0.4), 64, 0.3) -- You might want to change the 16 above to a larger number to make it more playable -- Some fun patterns!: -- local pattern = SquaresAndBridges(64, 32, 4) -- the most popular pattern, probably -- local pattern = IslandifySquares(Maze3(), 16, 8, 4) -- local pattern = Union(Zoom(Cross(), 16), ConcentricCircles(1.3)) -- local pattern = Intersection(Zoom(Maze3(), 32), Zoom(Grid(), 2)) -- local pattern = Distort(Zoom(Comb(), 32)) -- local pattern = Union(Spiral(1.6, 0.6), Intersection(Zoom(Maze3(0.5, false), 8), Zoom(Grid(), 2))) -- local pattern = Union(Union(Zoom(Maze3(0.25, false), 31), Zoom(Maze3(0.1, false), 97)), Zoom(Maze3(0.6), 11)) -- local pattern = Union(Barcode(10, 5, 20), Barcode(60, 5, 30)) -- local pattern = Union(Zoom(JaggedIslands(0.3), 32), Union(Barcode(0, 6, 50), Barcode(90, 6, 50))) config = { check_for_instant_death = true, terrain_pattern = TerrainPattern(pattern, watercolor) } --[[ In most configurations, you will want to turn resource generation WAY up, probably to maximum on all settings, to compensate for the decreased land area and inaccessibility. You may want to turn down enemy spawns to compensate for inaccessibility. watercolor: "blue" or "green" Patterns (optional arguments show default value) barcode Barcode(angle = 0, landthickness = 20, waterthickness = 50) distort Distort(pattern, wavelengths = distort_light) islandify KroneckerProduct(pattern1, pattern2, sizex, sizey = sizex) Islandify(pattern1, pattern1, sizex, sizey = sizex, bridgelenth = 48, bridgewidth = 2) SquaresAndBridges(islandradius = 32, bridgelength = 48, bridgewidth = 2) CirclesAndBridges(islandradius = 32, bridgelength = 48, bridgewidth = 2) IslandifySquares(pattern, islandradius = 32, bridgelength = 48, bridgewidth = 2) IslandifyCircles(pattern, islandradius = 32, bridgelength = 48, bridgewidth = 2) jaggedislands JaggedIslands(landratio = 0.5) mandelbrot Mandelbrot(sixe = 100) maze1 Maze1() maze2 Maze2() maze3 Maze3(threshold = 0.6, verify = true) simple AllLand() AllWater() Square(radius = 32) Circle(radius = 32) Halfplane() Quarterplane() Strip(width = 1) Cross(width = 1) Comb() Gridf() Checkerboard() Spiral(ratio = 1.4, land = 0.5) ConcentricCircles(ratio = 1.4, land = 0.5) transform Zoom(pattern. factor = 16) Invert(pattern) Union(pattern1, pattern2) Intersection(pattern1, pattern2) Translate(pattern, dx, dy) Rotate(pattern, angle) Affine(pattern, a, b, c, d, dx, dy) Tile(pattern, xszize, ysize) AngularRepeat(pattern, k) Jitter(pattern, radius = 10) Smooth(pattern, radius = 3) -- too slow, don't use ]]
mit
kitala1/darkstar
scripts/zones/Mhaura/npcs/Mauriri.lua
34
1077
---------------------------------- -- Area: Mhaura -- NPC: Mauriri -- Type: Item Deliverer -- @pos 10.883 -15.99 66.186 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, MAURIRI_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Windurst_Woods/npcs/Gottah_Maporushanoh.lua
37
1152
----------------------------------- -- Area: Windurst Woods -- NPC: Gottah Maporushanoh -- Working 100% ----------------------------------- require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) AmazinScorpio = player:getQuestStatus(WINDURST,THE_AMAZIN_SCORPIO); if (AmazinScorpio == QUEST_COMPLETED) then player:startEvent(0x01e6); elseif (AmazinScorpio == QUEST_ACCEPTED) then player:startEvent(0x01e3); else player:startEvent(0x1a4); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Tahrongi_Canyon/npcs/Signpost.lua
10
1325
----------------------------------- -- Area: Tahrongi Canyon -- NPC: Signpost ----------------------------------- package.loaded["scripts/zones/Tahrongi_Canyon/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Tahrongi_Canyon/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(npc:getID() == 17257026) or (npc:getID() == 17257026) then player:messageSpecial(SIGN_1); elseif(npc:getID() == 17257027) or (npc:getID() == 17257028) then player:messageSpecial(SIGN_3); elseif(npc:getID() == 17257031) or (npc:getID() == 17257032) then player:messageSpecial(SIGN_5); elseif(npc:getID() == 17257033) or (npc:getID() == 17257034) then player:messageSpecial(SIGN_7); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --print("CSID: %u",csid); --print("RESULT: %u",option); end;
gpl-3.0
apletnev/koreader
frontend/document/koptinterface.lua
3
41008
local TileCacheItem = require("document/tilecacheitem") local KOPTContext = require("ffi/koptcontext") local Document = require("document/document") local DataStorage = require("datastorage") local CacheItem = require("cacheitem") local Screen = require("device").screen local Geom = require("ui/geometry") local serial = require("serialize") local Cache = require("cache") local DEBUG = require("dbg") local logger = require("logger") local util = require("ffi/util") local KoptInterface = { ocrengine = "ocrengine", tessocr_data = DataStorage:getDataDir() .. "/data", ocr_lang = "eng", ocr_type = 3, -- default 0, for more accuracy use 3 last_context_size = nil, default_context_size = 1024*1024, screen_dpi = Screen:getDPI(), } local ContextCacheItem = CacheItem:new{} function ContextCacheItem:onFree() if self.kctx.free then KoptInterface:waitForContext(self.kctx) logger.dbg("free koptcontext", self.kctx) self.kctx:free() end end function ContextCacheItem:dump(filename) if self.kctx:isPreCache() == 0 then logger.dbg("dumping koptcontext to", filename) return serial.dump(self.size, KOPTContext.totable(self.kctx), filename) end end function ContextCacheItem:load(filename) logger.dbg("loading koptcontext from", filename) local size, kc_table = serial.load(filename) self.size = size self.kctx = KOPTContext.fromtable(kc_table) end local OCREngine = CacheItem:new{} function OCREngine:onFree() if self.ocrengine.freeOCR then logger.dbg("free OCREngine", self.ocrengine) self.ocrengine:freeOCR() end end function KoptInterface:waitForContext(kc) -- if koptcontext is being processed in background thread -- the isPreCache will return 1. while kc and kc:isPreCache() == 1 do logger.dbg("waiting for background rendering") util.usleep(100000) end return kc end --[[ get reflow context --]] function KoptInterface:createContext(doc, pageno, bbox) -- Now koptcontext keeps track of its dst bitmap reflowed by libk2pdfopt. -- So there is no need to check background context when creating new context. local kc = KOPTContext.new() local screen_size = Screen:getSize() local lang = doc.configurable.doc_language if lang == "chi_sim" or lang == "chi_tra" or lang == "jpn" or lang == "kor" then kc:setCJKChar() end kc:setLanguage(lang) kc:setTrim(doc.configurable.trim_page) kc:setWrap(doc.configurable.text_wrap) kc:setIndent(doc.configurable.detect_indent) kc:setColumns(doc.configurable.max_columns) kc:setDeviceDim(screen_size.w, screen_size.h) kc:setDeviceDPI(self.screen_dpi) kc:setStraighten(doc.configurable.auto_straighten) kc:setJustification(doc.configurable.justification) kc:setWritingDirection(doc.configurable.writing_direction) kc:setZoom(doc.configurable.font_size) kc:setMargin(doc.configurable.page_margin) kc:setQuality(doc.configurable.quality) kc:setContrast(doc.configurable.contrast) kc:setDefectSize(doc.configurable.defect_size) kc:setLineSpacing(doc.configurable.line_spacing) kc:setWordSpacing(doc.configurable.word_spacing) if bbox then if bbox.x0 >= bbox.x1 or bbox.y0 >= bbox.y1 then local page_size = Document.getNativePageDimensions(doc, pageno) bbox.x0, bbox.y0 = 0, 0 bbox.x1, bbox.y1 = page_size.w, page_size.h end kc:setBBox(bbox.x0, bbox.y0, bbox.x1, bbox.y1) end if DEBUG.is_on then kc:setDebug() end return kc end function KoptInterface:getContextHash(doc, pageno, bbox) local screen_size = Screen:getSize() local screen_size_hash = screen_size.w.."|"..screen_size.h local bbox_hash = bbox.x0.."|"..bbox.y0.."|"..bbox.x1.."|"..bbox.y1 return doc.file.."|"..doc.mod_time.."|"..pageno.."|" ..doc.configurable:hash("|").."|"..bbox_hash.."|"..screen_size_hash end function KoptInterface:getPageBBox(doc, pageno) if doc.configurable.text_wrap ~= 1 and doc.configurable.trim_page == 1 then -- auto bbox finding return self:getAutoBBox(doc, pageno) elseif doc.configurable.text_wrap ~= 1 and doc.configurable.trim_page == 2 then -- semi-auto bbox finding return self:getSemiAutoBBox(doc, pageno) else -- get saved manual bbox return Document.getPageBBox(doc, pageno) end end --[[ auto detect bbox --]] function KoptInterface:getAutoBBox(doc, pageno) local native_size = Document.getNativePageDimensions(doc, pageno) local bbox = { x0 = 0, y0 = 0, x1 = native_size.w, y1 = native_size.h, } local context_hash = self:getContextHash(doc, pageno, bbox) local hash = "autobbox|"..context_hash local cached = Cache:check(hash) if not cached then local page = doc._document:openPage(pageno) local kc = self:createContext(doc, pageno, bbox) page:getPagePix(kc) local x0, y0, x1, y1 = kc:getAutoBBox() local w, h = native_size.w, native_size.h if (x1 - x0)/w > 0.1 or (y1 - y0)/h > 0.1 then bbox.x0, bbox.y0, bbox.x1, bbox.y1 = x0, y0, x1, y1 else bbox = Document.getPageBBox(doc, pageno) end Cache:insert(hash, CacheItem:new{ autobbox = bbox }) page:close() kc:free() return bbox else return cached.autobbox end end --[[ detect bbox within user restricted bbox --]] function KoptInterface:getSemiAutoBBox(doc, pageno) -- use manual bbox local bbox = Document.getPageBBox(doc, pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local hash = "semiautobbox|"..context_hash local cached = Cache:check(hash) if not cached then local page = doc._document:openPage(pageno) local kc = self:createContext(doc, pageno, bbox) local auto_bbox = {} page:getPagePix(kc) auto_bbox.x0, auto_bbox.y0, auto_bbox.x1, auto_bbox.y1 = kc:getAutoBBox() auto_bbox.x0 = auto_bbox.x0 + bbox.x0 auto_bbox.y0 = auto_bbox.y0 + bbox.y0 auto_bbox.x1 = auto_bbox.x1 + bbox.x0 auto_bbox.y1 = auto_bbox.y1 + bbox.y0 logger.dbg("Semi-auto detected bbox", auto_bbox) local native_size = Document.getNativePageDimensions(doc, pageno) if (auto_bbox.x1 - auto_bbox.x0)/native_size.w < 0.1 and (auto_bbox.y1 - auto_bbox.y0)/native_size.h < 0.1 then logger.dbg("Semi-auto detected bbox too small, using manual bbox") auto_bbox = bbox end page:close() Cache:insert(hash, CacheItem:new{ semiautobbox = auto_bbox }) kc:free() return auto_bbox else return cached.semiautobbox end end --[[ get cached koptcontext for centain page. if context doesn't exist in cache make new context and reflow the src page immediatly, or wait background thread for reflowed context. --]] function KoptInterface:getCachedContext(doc, pageno) local bbox = doc:getPageBBox(pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local kctx_hash = "kctx|"..context_hash local cached = Cache:check(kctx_hash, ContextCacheItem) if not cached then -- If kctx is not cached, create one and get reflowed bmp in foreground. local kc = self:createContext(doc, pageno, bbox) local page = doc._document:openPage(pageno) logger.dbg("reflowing page", pageno, "in foreground") -- reflow page --local secs, usecs = util.gettime() page:reflow(kc, 0) page:close() --local nsecs, nusecs = util.gettime() --local dur = nsecs - secs + (nusecs - usecs) / 1000000 --self:logReflowDuration(pageno, dur) local fullwidth, fullheight = kc:getPageDim() logger.dbg("reflowed page", pageno, "fullwidth:", fullwidth, "fullheight:", fullheight) self.last_context_size = fullwidth * fullheight + 128 -- estimation Cache:insert(kctx_hash, ContextCacheItem:new{ persistent = true, size = self.last_context_size, kctx = kc }) return kc else -- wait for background thread local kc = self:waitForContext(cached.kctx) local fullwidth, fullheight = kc:getPageDim() self.last_context_size = fullwidth * fullheight + 128 -- estimation return kc end end --[[ get page dimensions --]] function KoptInterface:getPageDimensions(doc, pageno, zoom, rotation) if doc.configurable.text_wrap == 1 then return self:getRFPageDimensions(doc, pageno, zoom, rotation) else return Document.getPageDimensions(doc, pageno, zoom, rotation) end end --[[ get reflowed page dimensions --]] function KoptInterface:getRFPageDimensions(doc, pageno, zoom, rotation) local kc = self:getCachedContext(doc, pageno) local fullwidth, fullheight = kc:getPageDim() return Geom:new{ w = fullwidth, h = fullheight } end --[[ get first page image --]] function KoptInterface:getCoverPageImage(doc) local native_size = Document.getNativePageDimensions(doc, 1) local screen_size = Screen:getSize() local zoom = math.min(screen_size.w / native_size.w, screen_size.h / native_size.h) local tile = Document.renderPage(doc, 1, nil, zoom, 0, 1, 0) if tile then return tile.bb:copy() end end function KoptInterface:renderPage(doc, pageno, rect, zoom, rotation, gamma, render_mode) if doc.configurable.text_wrap == 1 then return self:renderReflowedPage(doc, pageno, rect, zoom, rotation, render_mode) elseif doc.configurable.page_opt == 1 then return self:renderOptimizedPage(doc, pageno, rect, zoom, rotation, render_mode) else return Document.renderPage(doc, pageno, rect, zoom, rotation, gamma, render_mode) end end --[[ inherited from common document interface render reflowed page into tile cache. --]] function KoptInterface:renderReflowedPage(doc, pageno, rect, zoom, rotation, render_mode) doc.render_mode = render_mode local bbox = doc:getPageBBox(pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local renderpg_hash = "renderpg|"..context_hash local cached = Cache:check(renderpg_hash) if not cached then -- do the real reflowing if kctx is not been cached yet local kc = self:getCachedContext(doc, pageno) local fullwidth, fullheight = kc:getPageDim() if not Cache:willAccept(fullwidth * fullheight / 2) then -- whole page won't fit into cache error("aborting, since we don't have enough cache for this page") end -- prepare cache item with contained blitbuffer local tile = TileCacheItem:new{ size = fullwidth * fullheight + 64, -- estimation excerpt = Geom:new{ w = fullwidth, h = fullheight }, pageno = pageno, } tile.bb = kc:dstToBlitBuffer() Cache:insert(renderpg_hash, tile) return tile else return cached end end --[[ inherited from common document interface render optimized page into tile cache. --]] function KoptInterface:renderOptimizedPage(doc, pageno, rect, zoom, rotation, render_mode) doc.render_mode = render_mode local bbox = doc:getPageBBox(pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local renderpg_hash = "renderoptpg|"..context_hash..zoom local cached = Cache:check(renderpg_hash, TileCacheItem) if not cached then local page_size = Document.getNativePageDimensions(doc, pageno) local full_page_bbox = { x0 = 0, y0 = 0, x1 = page_size.w, y1 = page_size.h, } local kc = self:createContext(doc, pageno, full_page_bbox) local page = doc._document:openPage(pageno) kc:setZoom(zoom) page:getPagePix(kc) page:close() logger.dbg("optimizing page", pageno) kc:optimizePage() local fullwidth, fullheight = kc:getPageDim() -- prepare cache item with contained blitbuffer local tile = TileCacheItem:new{ persistent = true, size = fullwidth * fullheight + 64, -- estimation excerpt = Geom:new{ x = 0, y = 0, w = fullwidth, h = fullheight }, pageno = pageno, } tile.bb = kc:dstToBlitBuffer() kc:free() Cache:insert(renderpg_hash, tile) return tile else return cached end end function KoptInterface:hintPage(doc, pageno, zoom, rotation, gamma, render_mode) if doc.configurable.text_wrap == 1 then self:hintReflowedPage(doc, pageno, zoom, rotation, gamma, render_mode) elseif doc.configurable.page_opt == 1 then self:renderOptimizedPage(doc, pageno, nil, zoom, rotation, gamma, render_mode) else Document.hintPage(doc, pageno, zoom, rotation, gamma, render_mode) end end --[[ inherited from common document interface render reflowed page into cache in background thread. this method returns immediatly leaving the precache flag on in context. subsequent usage of this context should wait for the precache flag off by calling self:waitForContext(kctx) --]] function KoptInterface:hintReflowedPage(doc, pageno, zoom, rotation, gamma, render_mode) local bbox = doc:getPageBBox(pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local kctx_hash = "kctx|"..context_hash local cached = Cache:check(kctx_hash) if not cached then local kc = self:createContext(doc, pageno, bbox) local page = doc._document:openPage(pageno) logger.dbg("hinting page", pageno, "in background") -- reflow will return immediately and running in background thread kc:setPreCache() page:reflow(kc, 0) page:close() Cache:insert(kctx_hash, ContextCacheItem:new{ size = self.last_context_size or self.default_context_size, kctx = kc, }) end end function KoptInterface:drawPage(doc, target, x, y, rect, pageno, zoom, rotation, gamma, render_mode) if doc.configurable.text_wrap == 1 then self:drawContextPage(doc, target, x, y, rect, pageno, zoom, rotation, render_mode) elseif doc.configurable.page_opt == 1 then self:drawContextPage(doc, target, x, y, rect, pageno, zoom, rotation, render_mode) else Document.drawPage(doc, target, x, y, rect, pageno, zoom, rotation, gamma, render_mode) end end --[[ inherited from common document interface draw cached tile pixels into target blitbuffer. --]] function KoptInterface:drawContextPage(doc, target, x, y, rect, pageno, zoom, rotation, render_mode) local tile = self:renderPage(doc, pageno, rect, zoom, rotation, render_mode) target:blitFrom(tile.bb, x, y, rect.x - tile.excerpt.x, rect.y - tile.excerpt.y, rect.w, rect.h) end --[[ extract text boxes in a PDF/Djvu page returned boxes are in native page coordinates zoomed at 1.0 --]] function KoptInterface:getTextBoxes(doc, pageno) local text = doc:getPageTextBoxes(pageno) if text and #text > 1 and doc.configurable.forced_ocr == 0 then return text -- if we have no text in original page then we will reuse native word boxes -- in reflow mode and find text boxes from scratch in non-reflow mode else if doc.configurable.text_wrap == 1 then return self:getNativeTextBoxes(doc, pageno) else return self:getNativeTextBoxesFromScratch(doc, pageno) end end end --[[ get text boxes in reflowed page via rectmaps in koptcontext --]] function KoptInterface:getReflowedTextBoxes(doc, pageno) local bbox = doc:getPageBBox(pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local hash = "rfpgboxes|"..context_hash local cached = Cache:check(hash) if not cached then local kctx_hash = "kctx|"..context_hash cached = Cache:check(kctx_hash) if cached then local kc = self:waitForContext(cached.kctx) --kc:setDebug() local fullwidth, fullheight = kc:getPageDim() local boxes = kc:getReflowedWordBoxes("dst", 0, 0, fullwidth, fullheight) Cache:insert(hash, CacheItem:new{ rfpgboxes = boxes }) return boxes end else return cached.rfpgboxes end end --[[ get text boxes in native page via rectmaps in koptcontext --]] function KoptInterface:getNativeTextBoxes(doc, pageno) local bbox = doc:getPageBBox(pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local hash = "nativepgboxes|"..context_hash local cached = Cache:check(hash) if not cached then local kctx_hash = "kctx|"..context_hash cached = Cache:check(kctx_hash) if cached then local kc = self:waitForContext(cached.kctx) --kc:setDebug() local fullwidth, fullheight = kc:getPageDim() local boxes = kc:getNativeWordBoxes("dst", 0, 0, fullwidth, fullheight) Cache:insert(hash, CacheItem:new{ nativepgboxes = boxes }) return boxes end else return cached.nativepgboxes end end --[[ get text boxes in reflowed page via optical method, i.e. OCR pre-processing in Tesseract and Leptonica. --]] function KoptInterface:getReflowedTextBoxesFromScratch(doc, pageno) local bbox = doc:getPageBBox(pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local hash = "scratchrfpgboxes|"..context_hash local cached = Cache:check(hash) if not cached then local kctx_hash = "kctx|"..context_hash cached = Cache:check(kctx_hash) if cached then local reflowed_kc = self:waitForContext(cached.kctx) local fullwidth, fullheight = reflowed_kc:getPageDim() local kc = self:createContext(doc, pageno) kc:copyDestBMP(reflowed_kc) local boxes = kc:getNativeWordBoxes("dst", 0, 0, fullwidth, fullheight) Cache:insert(hash, CacheItem:new{ scratchrfpgboxes = boxes }) kc:free() return boxes end else return cached.scratchrfpgboxes end end --[[ get text boxes in native page via optical method, i.e. OCR pre-processing in Tesseract and Leptonica. --]] function KoptInterface:getNativeTextBoxesFromScratch(doc, pageno) local hash = "scratchnativepgboxes|"..doc.file.."|"..pageno local cached = Cache:check(hash) if not cached then local page_size = Document.getNativePageDimensions(doc, pageno) local bbox = { x0 = 0, y0 = 0, x1 = page_size.w, y1 = page_size.h, } local kc = self:createContext(doc, pageno, bbox) kc:setZoom(1.0) local page = doc._document:openPage(pageno) page:getPagePix(kc) local boxes = kc:getNativeWordBoxes("src", 0, 0, page_size.w, page_size.h) Cache:insert(hash, CacheItem:new{ scratchnativepgboxes = boxes }) page:close() kc:free() return boxes else return cached.scratchnativepgboxes end end --[[ get page regions in native page via optical method, --]] function KoptInterface:getPageBlock(doc, pageno, x, y) local kctx local bbox = doc:getPageBBox(pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local hash = "pageblocks|"..context_hash local cached = Cache:check(hash) if not cached then local page_size = Document.getNativePageDimensions(doc, pageno) local full_page_bbox = { x0 = 0, y0 = 0, x1 = page_size.w, y1 = page_size.h, } local kc = self:createContext(doc, pageno, full_page_bbox) local screen_size = Screen:getSize() -- leptonica needs a source image of at least 300dpi kc:setZoom(screen_size.w / page_size.w * 300 / self.screen_dpi) local page = doc._document:openPage(pageno) page:getPagePix(kc) kc:findPageBlocks() Cache:insert(hash, CacheItem:new{ kctx = kc }) page:close() kctx = kc else kctx = cached.kctx end return kctx:getPageBlock(x, y) end --[[ get word from OCR providing selected word box --]] function KoptInterface:getOCRWord(doc, pageno, wbox) if not Cache:check(self.ocrengine) then Cache:insert(self.ocrengine, OCREngine:new{ ocrengine = KOPTContext.new() }) end if doc.configurable.text_wrap == 1 then return self:getReflewOCRWord(doc, pageno, wbox.sbox) else return self:getNativeOCRWord(doc, pageno, wbox.sbox) end end --[[ get word from OCR in reflew page --]] function KoptInterface:getReflewOCRWord(doc, pageno, rect) self.ocr_lang = doc.configurable.doc_language local bbox = doc:getPageBBox(pageno) local context_hash = self:getContextHash(doc, pageno, bbox) local hash = "rfocrword|"..context_hash..rect.x..rect.y..rect.w..rect.h local cached = Cache:check(hash) if not cached then local kctx_hash = "kctx|"..context_hash cached = Cache:check(kctx_hash) if cached then local kc = self:waitForContext(cached.kctx) local _, word = pcall( kc.getTOCRWord, kc, "dst", rect.x, rect.y, rect.w, rect.h, self.tessocr_data, self.ocr_lang, self.ocr_type, 0, 1) Cache:insert(hash, CacheItem:new{ rfocrword = word }) return word end else return cached.rfocrword end end --[[ get word from OCR in native page --]] function KoptInterface:getNativeOCRWord(doc, pageno, rect) self.ocr_lang = doc.configurable.doc_language local hash = "ocrword|"..doc.file.."|"..pageno..rect.x..rect.y..rect.w..rect.h logger.dbg("hash", hash) local cached = Cache:check(hash) if not cached then local bbox = { x0 = rect.x - math.floor(rect.h * 0.3), y0 = rect.y - math.floor(rect.h * 0.3), x1 = rect.x + rect.w + math.floor(rect.h * 0.3), y1 = rect.y + rect.h + math.floor(rect.h * 0.3), } local kc = self:createContext(doc, pageno, bbox) kc:setZoom(30/rect.h) local page = doc._document:openPage(pageno) page:getPagePix(kc) --kc:exportSrcPNGFile({rect}, nil, "ocr-word.png") local word_w, word_h = kc:getPageDim() local _, word = pcall( kc.getTOCRWord, kc, "src", 0, 0, word_w, word_h, self.tessocr_data, self.ocr_lang, self.ocr_type, 0, 1) Cache:insert(hash, CacheItem:new{ ocrword = word }) logger.dbg("word", word) page:close() kc:free() return word else return cached.ocrword end end --[[ get text from OCR providing selected text boxes --]] function KoptInterface:getOCRText(doc, pageno, tboxes) if not Cache:check(self.ocrengine) then Cache:insert(self.ocrengine, OCREngine:new{ ocrengine = KOPTContext.new() }) end logger.info("Not implemented yet") end function KoptInterface:getClipPageContext(doc, pos0, pos1, pboxes, drawer) assert(pos0.page == pos1.page) assert(pos0.zoom == pos1.zoom) local rect if pboxes and #pboxes > 0 then local box = pboxes[1] rect = Geom:new{ x = box.x, y = box.y, w = box.w, h = box.h, } for _, _box in ipairs(pboxes) do rect = rect:combine(Geom:new(_box)) end else local zoom = pos0.zoom or 1 rect = { x = math.min(pos0.x, pos1.x)/zoom, y = math.min(pos0.y, pos1.y)/zoom, w = math.abs(pos0.x - pos1.x)/zoom, h = math.abs(pos0.y - pos1.y)/zoom } end local bbox = { x0 = rect.x, y0 = rect.y, x1 = rect.x + rect.w, y1 = rect.y + rect.h } local kc = self:createContext(doc, pos0.page, bbox) local page = doc._document:openPage(pos0.page) page:getPagePix(kc) page:close() return kc, rect end function KoptInterface:clipPagePNGFile(doc, pos0, pos1, pboxes, drawer, filename) local kc = self:getClipPageContext(doc, pos0, pos1, pboxes, drawer) kc:exportSrcPNGFile(pboxes, drawer, filename) kc:free() end function KoptInterface:clipPagePNGString(doc, pos0, pos1, pboxes, drawer) local kc = self:getClipPageContext(doc, pos0, pos1, pboxes, drawer) -- there is no fmemopen in Android so leptonica.pixWriteMemPng will -- fail silently, workaround is creating a PNG file and read back the string local png = nil if util.isAndroid() then local tmp = "cache/tmpclippng.png" kc:exportSrcPNGFile(pboxes, drawer, tmp) local pngfile = io.open(tmp, "rb") if pngfile then png = pngfile:read("*all") pngfile:close() end else png = kc:exportSrcPNGString(pboxes, drawer) end kc:free() return png end --[[ get index of nearest word box around pos --]] local function inside_box(box, pos) local x, y = pos.x, pos.y if box.x0 <= x and box.y0 <= y and box.x1 >= x and box.y1 >= y then return true end return false end local function box_distance(box, pos) if inside_box(box, pos) then return 0 else local x0, y0 = pos.x, pos.y local x1, y1 = (box.x0 + box.x1) / 2, (box.y0 + box.y1) / 2 return (x0 - x1)*(x0 - x1) + (y0 - y1)*(y0 - y1) end end local function getWordBoxIndices(boxes, pos) local m, n = 1, 1 for i = 1, #boxes do for j = 1, #boxes[i] do if box_distance(boxes[i][j], pos) < box_distance(boxes[m][n], pos) then m, n = i, j end end end return m, n end --[[ get word and word box around pos --]] function KoptInterface:getWordFromBoxes(boxes, pos) if not pos or #boxes == 0 then return {} end local i, j = getWordBoxIndices(boxes, pos) local lb = boxes[i] local wb = boxes[i][j] if lb and wb then local box = Geom:new{ x = wb.x0, y = lb.y0, w = wb.x1 - wb.x0, h = lb.y1 - lb.y0, } return { word = wb.word, box = box, } end end --[[ get text and text boxes between pos0 and pos1 --]] function KoptInterface:getTextFromBoxes(boxes, pos0, pos1) if not pos0 or not pos1 or #boxes == 0 then return {} end local line_text = "" local line_boxes = {} local i_start, j_start = getWordBoxIndices(boxes, pos0) local i_stop, j_stop = getWordBoxIndices(boxes, pos1) if i_start == i_stop and j_start > j_stop or i_start > i_stop then i_start, i_stop = i_stop, i_start j_start, j_stop = j_stop, j_start end for i = i_start, i_stop do if i_start == i_stop and #boxes[i] == 0 then break end -- insert line words local j0 = i > i_start and 1 or j_start local j1 = i < i_stop and #boxes[i] or j_stop for j = j0, j1 do local word = boxes[i][j].word if word then -- if last character of this word is an ascii char then append a space local space = (word:match("[%z\194-\244][\128-\191]*$") or j == j1) and "" or " " line_text = line_text..word..space end end -- insert line box local lb = boxes[i] if i > i_start and i < i_stop then local line_box = Geom:new{ x = lb.x0, y = lb.y0, w = lb.x1 - lb.x0, h = lb.y1 - lb.y0, } table.insert(line_boxes, line_box) elseif i == i_start and i < i_stop then local wb = boxes[i][j_start] local line_box = Geom:new{ x = wb.x0, y = lb.y0, w = lb.x1 - wb.x0, h = lb.y1 - lb.y0, } table.insert(line_boxes, line_box) elseif i > i_start and i == i_stop then local wb = boxes[i][j_stop] local line_box = Geom:new{ x = lb.x0, y = lb.y0, w = wb.x1 - lb.x0, h = lb.y1 - lb.y0, } table.insert(line_boxes, line_box) elseif i == i_start and i == i_stop then local wb_start = boxes[i][j_start] local wb_stop = boxes[i][j_stop] local line_box = Geom:new{ x = wb_start.x0, y = lb.y0, w = wb_stop.x1 - wb_start.x0, h = lb.y1 - lb.y0, } table.insert(line_boxes, line_box) end end return { text = line_text, boxes = line_boxes, } end --[[ get word and word box from doc position ]]-- function KoptInterface:getWordFromPosition(doc, pos) local text_boxes = self:getTextBoxes(doc, pos.page) if text_boxes then if doc.configurable.text_wrap == 1 then return self:getWordFromReflowPosition(doc, text_boxes, pos) else return self:getWordFromNativePosition(doc, text_boxes, pos) end end end local function getBoxRelativePosition(s_box, l_box) local pos_rel = {} local s_box_center = s_box:center() pos_rel.x = (s_box_center.x - l_box.x)/l_box.w pos_rel.y = (s_box_center.y - l_box.y)/l_box.h return pos_rel end --[[ get word and word box from position in reflowed page ]]-- function KoptInterface:getWordFromReflowPosition(doc, boxes, pos) local pageno = pos.page local scratch_reflowed_page_boxes = self:getReflowedTextBoxesFromScratch(doc, pageno) local scratch_reflowed_word_box = self:getWordFromBoxes(scratch_reflowed_page_boxes, pos) local reflowed_page_boxes = self:getReflowedTextBoxes(doc, pageno) local reflowed_word_box = self:getWordFromBoxes(reflowed_page_boxes, pos) local reflowed_pos_abs = scratch_reflowed_word_box.box:center() local reflowed_pos_rel = getBoxRelativePosition(scratch_reflowed_word_box.box, reflowed_word_box.box) local native_pos = self:reflowToNativePosTransform(doc, pageno, reflowed_pos_abs, reflowed_pos_rel) local native_word_box = self:getWordFromBoxes(boxes, native_pos) local word_box = { word = native_word_box.word, pbox = native_word_box.box, -- box on page sbox = scratch_reflowed_word_box.box, -- box on screen pos = native_pos, } return word_box end --[[ get word and word box from position in native page ]]-- function KoptInterface:getWordFromNativePosition(doc, boxes, pos) local native_word_box = self:getWordFromBoxes(boxes, pos) local word_box = { word = native_word_box.word, pbox = native_word_box.box, -- box on page sbox = native_word_box.box, -- box on screen pos = pos, } return word_box end --[[ get link from position in screen page ]]-- function KoptInterface:getLinkFromPosition(doc, pageno, pos) local function _inside_box(_pos, box) if _pos then local x, y = _pos.x, _pos.y if box.x <= x and box.y <= y and box.x + box.w >= x and box.y + box.h >= y then return true end end end local page_links = doc:getPageLinks(pageno) if page_links then if doc.configurable.text_wrap == 1 then pos = self:reflowToNativePosTransform(doc, pageno, pos, {x=0.5, y=0.5}) end for i = 1, #page_links do local link = page_links[i] -- enlarge tappable link box local lbox = Geom:new{ x = link.x0 - Screen:scaleBySize(5), y = link.y0 - Screen:scaleBySize(5), w = link.x1 - link.x0 + Screen:scaleBySize(10), h = link.y1 - link.y0 + Screen:scaleBySize(10) } if _inside_box(pos, lbox) and link.page then return link, lbox end end end end --[[ transform position in native page to reflowed page ]]-- function KoptInterface:nativeToReflowPosTransform(doc, pageno, pos) local kc = self:getCachedContext(doc, pageno) local rpos = {} rpos.x, rpos.y = kc:nativeToReflowPosTransform(pos.x, pos.y) return rpos end --[[ transform position in reflowed page to native page ]]-- function KoptInterface:reflowToNativePosTransform(doc, pageno, abs_pos, rel_pos) local kc = self:getCachedContext(doc, pageno) local npos = {} npos.x, npos.y = kc:reflowToNativePosTransform(abs_pos.x, abs_pos.y, rel_pos.x, rel_pos.y) return npos end --[[ get text and text boxes from screen positions --]] function KoptInterface:getTextFromPositions(doc, pos0, pos1) local text_boxes = self:getTextBoxes(doc, pos0.page) if text_boxes then if doc.configurable.text_wrap == 1 then return self:getTextFromReflowPositions(doc, text_boxes, pos0, pos1) else return self:getTextFromNativePositions(doc, text_boxes, pos0, pos1) end end end --[[ get text and text boxes from screen positions for reflowed page ]]-- function KoptInterface:getTextFromReflowPositions(doc, native_boxes, pos0, pos1) local pageno = pos0.page local scratch_reflowed_page_boxes = self:getReflowedTextBoxesFromScratch(doc, pageno) local reflowed_page_boxes = self:getReflowedTextBoxes(doc, pageno) local scratch_reflowed_word_box0 = self:getWordFromBoxes(scratch_reflowed_page_boxes, pos0) local reflowed_word_box0 = self:getWordFromBoxes(reflowed_page_boxes, pos0) local scratch_reflowed_word_box1 = self:getWordFromBoxes(scratch_reflowed_page_boxes, pos1) local reflowed_word_box1 = self:getWordFromBoxes(reflowed_page_boxes, pos1) local reflowed_pos_abs0 = scratch_reflowed_word_box0.box:center() local reflowed_pos_rel0 = getBoxRelativePosition(scratch_reflowed_word_box0.box, reflowed_word_box0.box) local reflowed_pos_abs1 = scratch_reflowed_word_box1.box:center() local reflowed_pos_rel1 = getBoxRelativePosition(scratch_reflowed_word_box1.box, reflowed_word_box1.box) local native_pos0 = self:reflowToNativePosTransform(doc, pageno, reflowed_pos_abs0, reflowed_pos_rel0) local native_pos1 = self:reflowToNativePosTransform(doc, pageno, reflowed_pos_abs1, reflowed_pos_rel1) local reflowed_text_boxes = self:getTextFromBoxes(reflowed_page_boxes, pos0, pos1) local native_text_boxes = self:getTextFromBoxes(native_boxes, native_pos0, native_pos1) local text_boxes = { text = native_text_boxes.text, pboxes = native_text_boxes.boxes, -- boxes on page sboxes = reflowed_text_boxes.boxes, -- boxes on screen pos0 = native_pos0, pos1 = native_pos1 } return text_boxes end --[[ get text and text boxes from screen positions for native page ]]-- function KoptInterface:getTextFromNativePositions(doc, native_boxes, pos0, pos1) local native_text_boxes = self:getTextFromBoxes(native_boxes, pos0, pos1) local text_boxes = { text = native_text_boxes.text, pboxes = native_text_boxes.boxes, -- boxes on page sboxes = native_text_boxes.boxes, -- boxes on screen pos0 = pos0, pos1 = pos1, } return text_boxes end --[[ get text boxes from page positions --]] function KoptInterface:getPageBoxesFromPositions(doc, pageno, ppos0, ppos1) if not ppos0 or not ppos1 then return end if doc.configurable.text_wrap == 1 then local spos0 = self:nativeToReflowPosTransform(doc, pageno, ppos0) local spos1 = self:nativeToReflowPosTransform(doc, pageno, ppos1) local page_boxes = self:getReflowedTextBoxes(doc, pageno) local text_boxes = self:getTextFromBoxes(page_boxes, spos0, spos1) return text_boxes.boxes else local page_boxes = self:getTextBoxes(doc, pageno) local text_boxes = self:getTextFromBoxes(page_boxes, ppos0, ppos1) return text_boxes.boxes end end --[[ get page rect from native rect --]] function KoptInterface:nativeToPageRectTransform(doc, pageno, rect) if doc.configurable.text_wrap == 1 then local pos0 = { x = rect.x + 5, y = rect.y + 5 } local pos1 = { x = rect.x + rect.w - 5, y = rect.y + rect.h - 5 } local boxes = self:getPageBoxesFromPositions(doc, pageno, pos0, pos1) local res_rect = nil if #boxes > 0 then res_rect = boxes[1] for _, box in pairs(boxes) do res_rect = res_rect:combine(box) end end return res_rect else return rect end end local function all_matches(boxes, pattern, caseInsensitive) -- pattern list of single words local plist = {} -- split utf-8 characters for words in pattern:gmatch("[\32-\127\192-\255]+[\128-\191]*") do -- split space seperated words for word in words:gmatch("[^%s]+") do table.insert(plist, caseInsensitive and word:lower() or word) end end -- return mached word indices from index i, j local function match(i, j) local pindex = 1 local matched_indices = {} if #plist == 0 then return end while true do if #boxes[i] < j then j = j - #boxes[i] i = i + 1 end if i > #boxes then break end local box = boxes[i][j] local word = caseInsensitive and box.word:lower() or box.word if word:match(plist[pindex]) then table.insert(matched_indices, {i, j}) if pindex == #plist then return matched_indices else j = j + 1 pindex = pindex + 1 end else break end end end return coroutine.wrap(function() for i, line in ipairs(boxes) do for j, box in ipairs(line) do local matches = match(i, j) if matches then coroutine.yield(matches) end end end end) end function KoptInterface:findAllMatches(doc, pattern, caseInsensitive, page) local text_boxes = doc:getPageTextBoxes(page) if not text_boxes then return end local matches = {} for indices in all_matches(text_boxes or {}, pattern, caseInsensitive) do for _, index in ipairs(indices) do local i, j = unpack(index) local word = text_boxes[i][j] local word_box = { x = word.x0, y = word.y0, w = word.x1 - word.x0, h = word.y1 - word.y0, } -- rects will be transformed to reflowed page rects if needed table.insert(matches, self:nativeToPageRectTransform(doc, page, word_box)) end end return matches end function KoptInterface:findText(doc, pattern, origin, reverse, caseInsensitive, pageno) logger.dbg("Koptinterface: find text", pattern, origin, reverse, caseInsensitive, pageno) local last_pageno = doc:getPageCount() local start_page, end_page if reverse == 1 then -- backward if origin == 0 then -- from end of current page to first page start_page, end_page = pageno, 1 elseif origin == -1 then -- from the last page to end of current page start_page, end_page = last_pageno, pageno + 1 elseif origin == 1 then start_page, end_page = pageno - 1, 1 end else -- forward if origin == 0 then -- from current page to the last page start_page, end_page = pageno, last_pageno elseif origin == -1 then -- from the first page to current page start_page, end_page = 1, pageno - 1 elseif origin == 1 then -- from next page to the last page start_page, end_page = pageno + 1, last_pageno end end for i = start_page, end_page, (reverse == 1) and -1 or 1 do local matches = self:findAllMatches(doc, pattern, caseInsensitive, i) if #matches > 0 then matches.page = i return matches end end end --[[ helper functions --]] function KoptInterface:logReflowDuration(pageno, dur) local file = io.open("reflow_dur_log.txt", "a+") if file then if file:seek("end") == 0 then -- write the header only once file:write("PAGE\tDUR\n") end file:write(string.format("%s\t%s\n", pageno, dur)) file:close() end end return KoptInterface
agpl-3.0
paulosalvatore/maruim_server
data/actions/scripts/tools/pick.lua
1
1447
local groundIds = {354, 355} function onUse(player, item, fromPosition, target, toPosition, isHotkey) if toPosition.x == CONTAINER_POSITION then return false end local tile = Tile(toPosition) if not tile then return false end local ground = tile:getGround() if not ground then return false end if isInArray(groundIds, ground.itemid) then ground:transform(392) ground:decay() toPosition:sendMagicEffect(CONST_ME_POFF) toPosition.z = toPosition.z + 1 tile:relocateTo(toPosition) elseif target.itemid == 8934 then local chance = math.random(1, 100) local adicionarItem if chance <= 15 then adicionarItem = 2145 elseif chance <= 30 then adicionarItem = 10169 end if adicionarItem ~= nil then player:addItem(adicionarItem, 1) end target:transform(target.itemid+1) target:decay() toPosition:sendMagicEffect(CONST_ME_BLOCKHIT) elseif target.actionid == 3000 and target.itemid == 6283 then target:remove() toPosition:sendMagicEffect(CONST_ME_POFF) addEvent(function(posicao) Game.createItem(6283, 1, posicao):setActionId(3000) end, 300000, toPosition) elseif target.actionid == 19959 and target.itemid == 19959 then target:remove() toPosition:sendMagicEffect(CONST_ME_POFF) addEvent(function(posicao) posicao:sendMagicEffect(CONST_ME_POFF) Game.createItem(19959, 1, posicao):setActionId(19959) end, 10*1000, toPosition) else return false end return true end
gpl-2.0
kitala1/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Rholont.lua
14
2290
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Rholont -- @zone 80 -- @pos -168 -2 56 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 1) then player:startEvent(0x017); -- Gifts of Griffon Start elseif (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 9) then player:startEvent(0x018); -- Gifts of Griffon Quest Complete elseif(player:getQuestStatus(CRYSTAL_WAR,CLAWS_OF_THE_GRIFFON) == QUEST_AVAILABLE and player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_COMPLETED and player:getMainLvl() >= 15) then player:startEvent(0x02F) -- Claws of Griffon Start else player:startEvent(0x020); -- Default Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x02F) then player:addQuest(CRYSTAL_WAR,CLAWS_OF_THE_GRIFFON); elseif (csid == 0x017) then if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,2528); else player:setVar("GiftsOfGriffonProg",2); player:addItem(2528,7); -- Plume d'or player:messageSpecial(ITEM_OBTAINED,2528); end elseif (csid == 0x018) then player:addItem(812,1) player:messageSpecial(ITEM_OBTAINED,812); player:setVar("GiftsOfGriffonProg",0); player:completeQuest(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON); end end;
gpl-3.0
LaurieJohnson/iguana-web-apps
scratch/E76737E42964D985AA06049A663C1D2B/main.lua
2
3312
-- -- The server and the app object are global. -- server = require 'server.simplewebserver' app = require 'channelmanager.backend' function main(Data) --server.serveRequest(Data) importChannel() net.http.respond{body='oak'} end -- Draft code for import channel. Clean up and move to -- proper method in channelmanager.backend.lua function importChannel() -- Grab the channel config assuming we were -- passed the name of the directory (guid) local Guid = "EB004E5EB4123CD02D0722A4B0D6895F" local Dir = app.config.channelExportPath local ChannelName = 'channel_exporter' local ChConf = xml.parse{ data=io.open(Dir.."/"..ChannelName..".xml") :read("*a")} local Tmp = Dir.."/".."scratch" local ChGuid = ChConf.channel.from_http.guid print(Tmp) if not os.fs.stat(Tmp) then os.fs.mkdir(Tmp) end local PrjDir = Dir.."/"..ChannelName.."_http" trace(PrjDir) --[[ os.execute("cp -R "..PrjDir.." "..Tmp) ]] -- Open the project.prj file and pull in needed files local PrjF = json.parse{ data=io.open( PrjDir.."/project.prj") :read("*a")} -- Copy over project files for k,v in os.fs.glob(PrjDir.."/*") do if not os.fs.stat(Tmp.."/"..ChGuid) then os.fs.mkdir(Tmp.."/"..ChGuid) end os.execute("cp "..k.." "..Tmp .."/"..ChGuid) end -- Move over dependencies for k,v in pairs(PrjF['OtherDependencies']) do if not os.fs.stat(Tmp.."/other") then os.fs.mkdir(Tmp.."/other") end print(k,v) os.execute("cp "..Dir.."/other/"..v.. " "..Tmp.."/other") end for k,v in pairs(PrjF['LuaDependencies']) do if not os.fs.stat(Tmp.."/shared") then os.fs.mkdir(Tmp.."/shared") end if os.fs.stat(Dir.."/shared/"..v..".lua") then print('hi') os.execute("cp "..Dir.."/shared/"..v..".lua "..Tmp.."/shared") elseif v:find(".") then local PackageDir = v:sub(1, v:find('%.')-1) -- It's a package, copy from top down. os.execute("cp -R "..Dir.."/shared/"..PackageDir.. " "..Tmp.."/shared") end end -- Zip and import first project os.execute("cd "..Dir.."/scratch && zip -r scratch.zip *") ---[[ require 'iguanaServer' local Web = iguana.webInfo() local ChAPI = iguanaServer.connect{ url='http://localhost:6545', username='admin', password='password'} local B64 = filter.base64.enc(io.open(Dir.."/scratch/scratch.zip"):read("*a")) ChAPI:importProject{project=B64, guid='F8AE93FE7D8BEE761E982D75A76145B3',live=true} --]] -- Zip and import filter -- Zip and import second project --[[ for k,v in os.fs.glob(app.config.channelExportPath .. "/EB004E5EB4123CD02D0722A4B0D6895F/*") do print(k,v) end ]] --[[ for f in os.fs.glob( app.config.channelExportPath .. "/EB004E5EB4123CD02D0722A4B0D6895F" .. "/E76737E42964D985AA06049A663C1D2B/*") do -- grab the file name if f:match("/project.prj") then local F = io.open(f) local C = F:read("*a") local J = json.parse{data=C} --for k,v in pairs(J) do -- print(k,v) --end --trace(J.LuaDependencies[1]) end end ]] end
mit
tetoali605/THETETOO_A7A
plugins/badword.lua
7
3635
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY tetoo ▀▄ ▄▀ ▀▄ ▄▀ BY nmore (@l_l_lo) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY l_l_ll ▀▄ ▄▀ ▀▄ ▄▀ broadcast : منـع الكلـما ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function addword(msg, name) local hash = 'chat:'..msg.to.id..':badword' redis:hset(hash, name, 'newword') return "🎀🎖تــم اضــافه كلـمه جـديـده الى قائمه المنــع ✔️🔔 تابـع قـناةة الســورس @no_no2 \n>"..name end local function get_variables_hash(msg) return 'chat:'..msg.to.id..':badword' end local function list_variablesbad(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '🎀🎖قــائمـةة الــمنـع 🔕✖️ الـكلـمات المحـظورةة عــن الكـروب تابع قـناةة الســورس @no_no2 :\n\n' for i=1, #names do text = text..'> '..names[i]..'\n' end return text else return end end function clear_commandbad(msg, var_name) --Save on redis local hash = get_variables_hash(msg) redis:del(hash, var_name) return '🎀🎖تــم تنــضـيف الـكـلمات المحـظوره 😿🍃 ســورس تيـتو تـابع القـناةة @no_no2' end local function list_variables2(msg, value) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do if string.match(value, names[i]) and not is_momod(msg) then if msg.to.type == 'channel' then delete_msg(msg.id,ok_cb,false) else kick_user(msg.from.id, msg.to.id) end return end --text = text..names[i]..'\n' end end end local function get_valuebad(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return else return value end end end function clear_commandsbad(msg, cmd_name) --Save on redis local hash = get_variables_hash(msg) redis:hdel(hash, cmd_name) return ''..cmd_name..' 🎀🎖الـكلـمةة 📩 تـم حـذفـها مـن قائمةة المنع 😿قـناة السـورس. @no_no2' end local function run(msg, matches) if matches[2] == 'منع' then if not is_momod(msg) then return 'only for moderators' end local name = string.sub(matches[3], 1, 50) local text = addword(msg, name) return text end if matches[2] == 'قائمه المنع' then return list_variablesbad(msg) elseif matches[2] == 'تنظيف قائمه المنع' then if not is_momod(msg) then return '_|_' end local asd = '1' return clear_commandbad(msg, asd) elseif matches[2] == 'الغاء منع' or matches[2] == 'rw' then if not is_momod(msg) then return '_|_' end return clear_commandsbad(msg, matches[3]) else local name = user_print_name(msg.from) return list_variables2(msg, matches[1]) end end return { patterns = { "^()(rw) (.*)$", "^()(منع) (.*)$", "^()(الغاء منع) (.*)$", "^()(قائمه المنع)$", "^()(تنظيف قائمه المنع)$", "^(.+)$", }, run = run }
gpl-2.0
kitala1/darkstar
scripts/zones/Jugner_Forest_[S]/npcs/Logging_Point.lua
29
1113
----------------------------------- -- Area: Jugner Forest [S] -- NPC: Logging Point ----------------------------------- package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil; ------------------------------------- require("scripts/globals/logging"); require("scripts/zones/Jugner_Forest_[S]/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startLogging(player,player:getZoneID(),npc,trade,0x0385); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Bastok_Markets/npcs/Carmelide.lua
36
1551
----------------------------------- -- Area: Bastok Markets -- NPC: Carmelide -- Standard Merchant NPC -- -- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CARMELIDE_SHOP_DIALOG); stock = { 0x0326, 1676,2, --Tourmaline 0x0327, 1676,2, --Sardonyx 0x0320, 1676,2, --Amethyst 0x032E, 1676,2, --Amber 0x031B, 1676,2, --Lapis Lazuli 0x0329, 1676,2, --Clear Topaz 0x031F, 1676,2, --Onyx 0x031C, 1676,2, --Light Opal 0x348E, 68,3 --Copper Ring } showNationShop(player, SANDORIA, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
pedishield/Persian_King
plugins/qrcode.lua
16
3828
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^[!/]qr "(%w+)" "(%w+)" (.+)$', "^[!/]qr (.+)$", '^[!/]qrcode "(%w+)" "(%w+)" (.+)$', "^[!/]qrcode (.+)$" }, run = run } -- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- -- -- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- ||\\ //|| //\\ || //|| //\\ // || || // -- || \\ // || // \\ || // || // \\ // || || // -- || \\ // || // \\ || // || // \\ || || || // -- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || // -- || \\ // || // \\ || // || // \\ || || || || \\ -- || \\ // || // \\ || // || // \\ \\ || || || \\ -- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\ -- -- -- ||-_-_-_- || || || //-_-_-_-_-_- -- || || || || || // -- ||_-_-_|| || || || // -- || || || || \\ -- || || \\ // \\ -- || || \\ // // -- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-// -- --By @ali_ghoghnoos --@telemanager_ch
gpl-2.0
ChronoPong/corona
ChronoPong/scenes/playScn.lua
1
18171
local composer = require( "composer" ) local physics = require("physics") local scoreLib=require("lib.scoreLib") local scene = composer.newScene() physics.start() -- ----------------------------------------------------------------------------------------------------------------- -- All code outside of the listener functions will only be executed ONCE unless "composer.removeScene()" is called. -- ----------------------------------------------------------------------------------------------------------------- -- local forward references should go here --variables local sceneGlobal, ball, upWall, leftWall, downWall, rightWall,currentScore,score,paddleCount,trail1ball,trail2ball,timeInMiniSeconds,secondTimer, transitionSecondIn,transitionSecondOut local bombs,powerUps,spiralLines={false,false,false},{false,false,false},{} --Functions --Paddle functions local makePaddleImage,makePaddleLine,makePaddle,multiplierText --Wall functions local makeWalls,setUpWallColor,upWallCollision,gameOverListener --Event functions local makeObstacle,score --Ball functions local makeBall,makeTrail,getBallSpeed --Spiral functions local makeSpiral,spiralListener,turnLineToGraphic -- ------------------------------------------------------------------------------- -- "scene:create()" function scene:create( event ) local sceneGroup = self.view sceneGlobal = sceneGroup ball=makeBall() upWall,downWall,leftWall,rightWall,upWall=makeWalls() makeSpiral() sceneGroup:insert(upWall) sceneGroup:insert(downWall) sceneGroup:insert(leftWall) sceneGroup:insert(rightWall) sceneGroup:insert(upWall) sceneGroup:insert(ball) physics.setGravity( 0, 0 ) physics.addBody( upWall, "static", {density=1000, friction=0, bounce=0.5 } ) physics.addBody( downWall, "static", {density=1000, friction=0, bounce=0 } ) physics.addBody( rightWall, "static", {density=1000, friction=0, bounce=0 } ) physics.addBody( leftWall, "static", {density=1000, friction=0, bounce=0 } ) physics.addBody( ball, { density = 0, friction = 0, bounce = 1, radius = 20 } ) ball.isFixedRotation = true ball.isBullet= true ball:setLinearVelocity(400,400) scoreBoard = display.newText({text ="SCORE = ".. 0,x = display.contentWidth/2, y =40,fontSize= 20}) sceneGroup:insert(scoreBoard) end function scene:show( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then physics.start() timeInMiniSeconds = 0 currentScore = 0 paddleCount = 0 ball:setLinearVelocity(400,400) ball.x,ball.y = 200,200 upWall:setStrokeColor(0,0,1) for i=1,#spiralLines do spiralLines[i].alpha=0.3 end Runtime:addEventListener("enterFrame",score) Runtime:addEventListener("enterFrame", spiralListener) downWall:addEventListener("collision",gameOverListener) upWall:addEventListener("collision",upWallCollision) Runtime:addEventListener("touch",makePaddle) elseif ( phase == "did" ) then --[[for i=1,#seconds do seconds[i].img.alpha=0 end secondTimer=timer.performWithDelay(1000,transitionSecondIn,0) ]] end end -- "scene:hide()" function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Called when the scene is on screen (but is about to go off screen). -- Insert code here to "pause" the scene. -- Example: stop timers, stop animation, stop audio, etc. elseif ( phase == "did" ) then -- Called immediately after scene goes off screen. Runtime:removeEventListener("enterFrame",score) downWall:removeEventListener("collision",gameOverListener) upWall:removeEventListener("collision",upWallCollision) Runtime:removeEventListener("touch",makePaddle) Runtime:removeEventListener("enterFrame", spiralListener) composer.setVariable("lastScore",currentScore) physics.pause() local highscore = scoreLib.load() if tonumber(currentScore)>(tonumber(highscore) or 0) then scoreLib.set(currentScore) scoreLib.save() end print("score was :"..currentScore) for i=1,#bombs do bombs[i]=false end --timer.cancel(secondTimer) --transition.cancel("secondsTransition") end end -- "scene:destroy()" function scene:destroy( event ) local sceneGroup = self.view -- Called prior to the removal of scene's view ("sceneGroup"). -- Insert code here to clean up the scene. -- Example: remove display objects, save state, etc. end ------------------------------------------PADDLE CODE------------------------------------------------ --Making a paddle consists of producing its image and a line which will be the actual physical body acting. function makePaddleImage(event) local paddleImage = display.newImageRect("resources/icons/paddle.png", ((event.xStart-event.x)^2+(event.yStart-event.y)^2)^0.5, 20 ) paddleImage.alpha=0.2 paddleImage.rotation=(360/(2*math.pi))*(math.atan((event.y-event.yStart)/(event.x-event.xStart))) paddleImage.x = (event.xStart+event.x)*0.5 paddleImage.y = (event.yStart+event.y)*0.5 return paddleImage end function makePaddleLine(event) local paddleLine = display.newLine( event.xStart, event.yStart, event.x, event.y) paddleLine.alpha = 0 paddleLine.strokeWidth = 10 return paddleLine end function makePaddle( event ) if ( event.phase == "ended" and paddleCount<2) then paddleCount = paddleCount +1 local maxLength=display.contentWidth*0.4 if(((event.xStart-event.x)^2+(event.yStart-event.y)^2)^0.5>maxLength) then local angle=math.abs(math.atan( (event.yStart-event.y)/(event.xStart-event.x) )) if event.x>event.xStart then event.x=event.xStart+maxLength*math.cos(angle) else event.x=event.xStart-maxLength*math.cos(angle) end if event.y>event.yStart then event.y=event.yStart+maxLength*math.sin(angle) else event.y=event.yStart-maxLength*math.sin(angle) end end --Make the paddle line a physical object local paddleLine,paddleImage = makePaddleLine(event),makePaddleImage(event) sceneGlobal:insert(paddleLine) sceneGlobal:insert(paddleImage) physics.addBody( paddleLine, "static", {density=1, friction=0, bounce=1 } ) paddleLine.isBullet = true --Fade out the paddle line transition.fadeOut( paddleLine, {time =800 , onComplete = function () physics.removeBody( paddleLine ) paddleLine:removeSelf( ) paddleLine=nil end}) --Fade in the paddle image and when complete, fade it out transition.fadeIn( paddleImage, {time = 400, onComplete = function () transition.fadeOut( paddleImage, {time =400 , onComplete = function () paddleImage:removeSelf( ) paddleImage=nil end}) end}) function paddleCollision(event) multiplier = 0 local vx,vy = ball:getLinearVelocity() local direction = math.atan2(vy,vx) if (event.phase == "began") then speed = math.sqrt(vx*vx+vy*vy) print("bg paddle alpha :"..paddleImage.alpha.."speed: "..speed) elseif (event.phase=="ended") then multiplier= (paddleImage.alpha + 0.5)^2 if(multiplier* speed)<400 then speed=400 elseif(multiplier*speed>2000) then speed=2000 else speed=speed*multiplier end multiplierText() ball:setLinearVelocity(math.cos(direction)*speed, math.sin(direction)*speed) print("end paddle alpha :"..paddleImage.alpha.." multiplier : "..multiplier.. " speed: "..speed) end end setUpWallColor() paddleLine:addEventListener( "collision", paddleCollision ) end end function multiplierText() local multiplierText = display.newText( { text = "x"..math.round(multiplier*100)/100, x = display.contentWidth/2 , y= display.contentHeight/2 } ) multiplierText:setFillColor( 1,0,0 ) transition.scaleBy( multiplierText, {xScale = 10,yScale = 10, time = 500, onStart = function ( ) transition.fadeOut( multiplierText, {time = 500, onComplete = function () multiplierText:removeSelf( ) end} ) end} ) return multiplierText end ------------------------------------------PADDLE CODE------------------------------------------------ ------------------------------------------CLOCK CODE------------------------------------------------ --[[clock.seconds={} function clock.makeSeconds() local angle=-90 while angle<270 do clock.seconds[((angle+90)/6)+1]={ text=(angle+90)/6, x=display.contentCenterX+250*math.cos(angle*2*math.pi/360), y=display.contentCenterY+250*math.sin(angle*2*math.pi/360), font=native.systemFont, fontSize=20 } angle=angle+6 --seconds[i].img=display.newText(seconds[i]) end return clock.seconds end function clock.makeMinutes() local minutes={} for i=1,2 do minutes[i]={ text=0, x=300, y=500, font=native.systemFont, fontSize=150 } end return minutes end function transitionSecondIn() timeInSeconds=timeInSeconds+1 seconds[timeInSeconds%60+1].transition=transition.to(seconds[timeInSeconds%60+1].img,{ time=200, alpha=1, tag="secondsTransition", onComplete=transitionSecondOut} ) end function transitionSecondOut() seconds[(timeInSeconds-1)%60+1].fadeOut=transition.to(seconds[(timeInSeconds-1)%60+1].img,{ time=30000, alpha=0, tag="secondsTransition"} ) end --Create the circle of seconds and add them to the sceneGroup seconds=clock.makeSeconds() for i=1,#seconds do seconds[i].img=display.newText(seconds[i]) sceneGroup:insert(seconds[i].img) end minutes=clock.makeMinutes() for i=1,#minutes do minutes[i].img=display.newText(minutes[i]) sceneGroup:insert(minutes[i].img) end --]] ------------------------------------------CLOCK CODE------------------------------------------------ ------------------------------------------SPIRAL CODE ---------------------------------------------- function makeSpiral() local angle=4.5*math.pi/180 local theta,x,y,dx,dy --make background graphic local lineLength=300 local spiralWidth=50 for i=0,179 do local line theta=i*angle+math.pi x=spiralWidth*theta*math.cos(theta)+display.contentWidth*0.5 y=display.contentHeight-spiralWidth*theta*math.sin(theta)-display.contentHeight*0.5 dyCalc=(spiralWidth*theta*math.sin(theta)-spiralWidth*math.cos(theta))/(spiralWidth*math.sin(theta)+spiralWidth*theta*math.cos(theta)) dxCalc=1 dyActual=dyCalc/(dyCalc^2+dxCalc^2)^0.5 * lineLength dxActual=dxCalc/(dyCalc^2+dxCalc^2)^0.5 * lineLength local x1,y1,x2,y2=x-dxActual,y-dyActual,x+dxActual,y+dyActual --line=display.newLine(x1,y1,x2,y2) line=turnLineToGraphic(x1,y1,x2,y2,0.2) sceneGlobal:insert(line) --line.alpha=0 --line:setStrokeColor(0,0,1) --sceneGlobal:insert(line) print(i,x,y,dyCalc,dxCalc,dyActual,dxActual) end --make spiral ---[[ lineLength=30 spiralWidth=18 for i=1,180 do theta=i*angle+math.pi x=spiralWidth*theta*math.cos(theta)+display.contentWidth*0.5 y=display.contentHeight-spiralWidth*theta*math.sin(theta)-display.contentHeight*0.5 dyCalc=(spiralWidth*theta*math.sin(theta)-spiralWidth*math.cos(theta))/(spiralWidth*math.sin(theta)+spiralWidth*theta*math.cos(theta)) dxCalc=1 dyActual=dyCalc/(dyCalc^2+dxCalc^2)^0.5 * lineLength dxActual=dxCalc/(dyCalc^2+dxCalc^2)^0.5 * lineLength local x1,y1,x2,y2=x-dxActual,y+dyActual,x+dxActual,y-dyActual --line=display.newLine(x1,y1,x2,y2) spiralLines[i]=turnLineToGraphic(x1,y1,x2,y2,0.3) --line.alpha=0 --sceneGlobal:insert(line) sceneGlobal:insert(spiralLines[i]) --print(i,x,y,dyCalc,dxCalc,dyActual,dxActual) end --]] end function spiralListener() timeInMiniSeconds=timeInMiniSeconds+1 spiralLines[(timeInMiniSeconds%60)+1].alpha=0.7 if timeInMiniSeconds%60==0 then spiralLines[60].alpha=0.3 else spiralLines[(timeInMiniSeconds%60)].alpha=0.3 end if timeInMiniSeconds%60==0 then transition.to(spiralLines[timeInMiniSeconds/60+59],{time=400,alpha=0.3}) transition.to(spiralLines[timeInMiniSeconds/60+60],{time=600,alpha=0.7}) end end function turnLineToGraphic(x1,y1,x2,y2,a) local lineGraphic = display.newImageRect("resources/icons/paddle.png", ((x1-x2)^2+(y1-y2)^2)^0.5, 20 ) lineGraphic.alpha=a lineGraphic.rotation=(360/(2*math.pi))*(math.atan((y2-y1)/(x2-x1))) lineGraphic.x = (x1+x2)*0.5 lineGraphic.y = (y1+y2)*0.5 --lineGraphic:setFillColor(0,1,0) return lineGraphic end ------------------------------------------SPIRAL CODE ---------------------------------------------- ------------------------------------------WALL CODE------------------------------------------------ function makeWalls() upWall = display.newLine(0, 100, display.contentWidth, 100 ) upWall.StrokeWidth = 3 downWall = display.newLine(0, display.contentHeight, display.contentWidth, display.contentHeight ) leftWall = display.newLine(0, 0, 0, display.contentHeight ) rightWall = display.newLine(display.contentWidth, 0, display.contentWidth, display.contentHeight ) upWallBlock = display.newRoundedRect( display.contentWidth/2, 50, display.contentWidth-5, 95, 10 ) upWallBlock:setFillColor( 0,0,0 ) upWallBlock.alpha = 0.6 return upWall,downWall,leftWall,rightWall,upWallBlock end function setUpWallColor() if (paddleCount == 0) then upWall:setStrokeColor(0,0,1 ) elseif(paddleCount == 1) then upWall:setStrokeColor(0,1,0 ) else upWall:setStrokeColor(1,0,0 ) end end function upWallCollision( event ) if (event.phase =="began") then paddleCount = 0 setUpWallColor() end end function gameOverListener( event ) if(event.phase == "ended") then -- ball:setLinearVelocity(0,-1000) --physics.pause( ) print("gameOverListener") --Runtime:removeEventListener("enterFrame",score ) --downWall:removeEventListener("collision",gameOverListener) composer.gotoScene("scenes.menuScn") end end ------------------------------------------WALL CODE------------------------------------------------ ------------------------------------------EVENT CODE------------------------------------------------ function makeObstacle(x,y) --local obstacle=display.newRect(sceneGroup,x,y,80,80) local obstacle = display.newImage( "resources/icons/mine.png" ,x,y) obstacle:scale( 0.5,0.5) obstacle.alpha=0.2 transition.fadeIn( obstacle, {time = 1000, onComplete = function () transition.fadeOut( obstacle, {time =1000 , onComplete = function () physics.removeBody( obstacle ) obstacle:removeSelf( ) end}) end}) --transition.scaleTo( obstacle, {time = 2000, xScale = 3, yScale= 3}) physics.addBody(obstacle,"static", {density=1000, friction=0, bounce=1,radius = 50 }) sceneGlobal:insert(obstacle) end function score(event) local vx,vy = ball:getLinearVelocity() local speed = math.sqrt(vx*vx+vy*vy) ball.x, ball.y = ball.x, ball.y ball:setFillColor((speed-100)/2000,600/speed,0) currentScore = currentScore +math.round(speed/400) scoreBoard.text = "SCORE = ".. currentScore --makeTrail((speed-100)/2000,600/speed,0) if(currentScore>500 and not bombs[1])then makeObstacle(300,300) bombs[1]=true end --trail1ball.x,trail1ball.y = ball.x,ball.y --trail1touchJoint:setTarget( ball.x, ball.y ) --trail2ball.touchJoint:setTarget( ball.x, ball.y ) end ------------------------------------------EVENT CODE------------------------------------------------ ------------------------------------------BALL CODE------------------------------------------------ function makeBall() local ball=display.newImage( "resources/icons/face.png") ball:scale(0.25,0.25) return ball end function makeTrail (r,g,b) local trail = display.newCircle( ball.x, ball.y, 18 ) trail:setFillColor(r,g,b ) transition.scaleTo( trail, {time = 200, xScale = 0.2, yScale= 0.2, onStart = function () transition.fadeOut(trail, {time = 180, onComplete = function ( ) trail:removeSelf( ) end}) end} ) end function getBallSpeed() if(ball) then --get the direction and set the speed local vx,vy = ball:getLinearVelocity() local direction = math.atan2(vy,vx) print(math.cos(direction)*speed, math.sin(direction)*speed) end end ------------------------------------------BALL CODE------------------------------------------------ ---------------------------------------Listener setup----------------------------------------------- scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) -- ------------------------------------------------------------------------------- return scene
gpl-2.0
kitala1/darkstar
scripts/globals/items/forest_carp.lua
17
1334
----------------------------------------- -- ID: 4289 -- Item: forest_carp -- Food Effect: 30Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if(target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4289); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/tortilla_bueno.lua
35
1193
----------------------------------------- -- ID: 5181 -- Item: tortilla_bueno -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 8 -- Vitality 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5181); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 8); target:addMod(MOD_VIT, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 8); target:delMod(MOD_VIT, 4); end;
gpl-3.0
kitala1/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5fb.lua
34
1110
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Leviathan's Gate -- @pos 249 -34 -60 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then player:messageSpecial(SOLID_STONE); end return 0; end; -- ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/slice_of_tavnazian_ram_meat.lua
17
1334
----------------------------------------- -- ID: 5208 -- Item: slice_of_tavnazian_ram_meat -- Food Effect: 5Min, Galka only ----------------------------------------- -- Strength 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if(target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5208); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Port_Jeuno/npcs/Moulloie.lua
38
1028
----------------------------------- -- Area: Port Jeuno -- NPC: Moulloie -- Type: Standard NPC -- @zone: 246 -- @pos -77.724 7.003 59.044 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x002e); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Port_Windurst/npcs/Pygmalion.lua
38
1033
----------------------------------- -- Area: Port Windurst -- NPC: Pygmalion -- Type: Standard NPC -- @zone: 240 -- @pos 228.710 -7 93.314 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2723); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Norg/npcs/Edal-Tahdal.lua
17
4274
----------------------------------- -- Area: Norg -- NPC: Edal-Tahdal -- Starts and Finishes Quest: Trial by Water -- @pos -13 1 -20 252 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TrialByWater = player:getQuestStatus(OUTLANDS,TRIAL_BY_WATER); local WhisperOfTides = player:hasKeyItem(WHISPER_OF_TIDES); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day if((TrialByWater == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 4) or (TrialByWater == QUEST_COMPLETED and realday ~= player:getVar("TrialByWater_date"))) then player:startEvent(0x006d,0,TUNING_FORK_OF_WATER); -- Start and restart quest "Trial by Water" elseif(TrialByWater == QUEST_ACCEPTED and player:hasKeyItem(TUNING_FORK_OF_WATER) == false and WhisperOfTides == false) then player:startEvent(0x00be,0,TUNING_FORK_OF_WATER); -- Defeat against Avatar : Need new Fork elseif(TrialByWater == QUEST_ACCEPTED and WhisperOfTides == false) then player:startEvent(0x006e,0,TUNING_FORK_OF_WATER,2); elseif(TrialByWater == QUEST_ACCEPTED and WhisperOfTides) then numitem = 0; if(player:hasItem(17439)) then numitem = numitem + 1; end -- Leviathan's Rod if(player:hasItem(13246)) then numitem = numitem + 2; end -- Water Belt if(player:hasItem(13565)) then numitem = numitem + 4; end -- Water Ring if(player:hasItem(1204)) then numitem = numitem + 8; end -- Eye of Nept if(player:hasSpell(300)) then numitem = numitem + 32; end -- Ability to summon Leviathan player:startEvent(0x0070,0,TUNING_FORK_OF_WATER,2,0,numitem); else player:startEvent(0x0071); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x006d and option == 1) then if(player:getQuestStatus(OUTLANDS,TRIAL_BY_WATER) == QUEST_COMPLETED) then player:delQuest(OUTLANDS,TRIAL_BY_WATER); end player:addQuest(OUTLANDS,TRIAL_BY_WATER); player:setVar("TrialByWater_date", 0); player:addKeyItem(TUNING_FORK_OF_WATER); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_WATER); elseif(csid == 0x00be) then player:addKeyItem(TUNING_FORK_OF_WATER); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_WATER); elseif(csid == 0x0070) then local item = 0; if(option == 1) then item = 17439; -- Leviathan's Rod elseif(option == 2) then item = 13246; -- Water Belt elseif(option == 3) then item = 13565; -- Water Ring elseif(option == 4) then item = 1204; -- Eye of Nept end if(player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); else if(option == 5) then player:addGil(GIL_RATE*10000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil elseif(option == 6) then player:addSpell(300); -- Avatar player:messageSpecial(AVATAR_UNLOCKED,0,0,2); else player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); -- Item end player:addTitle(HEIR_OF_THE_GREAT_WATER); player:delKeyItem(WHISPER_OF_TIDES); --Whisper of Tides, as a trade for the above rewards player:setVar("TrialByWater_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(NORG,NORG_FAME*30); player:completeQuest(OUTLANDS,TRIAL_BY_WATER); end end end;
gpl-3.0
sylvanaar/IDLua
resources/stdlibrary/string.lua
2
8199
-- Copyright 2013 Jon S Akhtar (Sylvanaar) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. --- string operations like searching and matching. -- @module string module "string" --- -- Returns the internal numerical codes of the characters `s[i]`, `s[i+1]`, -- ..., `s[j]`. The default value for `i` is 1; the default value for `j` -- is `i`. -- Note that numerical codes are not necessarily portable across platforms. function byte(s, i, j) end --- -- Receives zero or more integers. Returns a string with length equal to -- the number of arguments, in which each character has the internal numerical -- code equal to its corresponding argument. -- Note that numerical codes are not necessarily portable across platforms. function char(...) end --- -- Returns a string containing a binary representation of the given -- function, so that a later `loadstring` on this string returns a copy of -- the function. `function` must be a Lua function without upvalues. function dump(func) end --- -- Looks for the first match of `pattern` in the string `s`. If it finds a -- match, then `find` returns the indices of `s` where this occurrence starts -- and ends; otherwise, it returns nil. A third, optional numerical argument -- `init` specifies where to start the search; its default value is 1 and -- can be negative. A value of true as a fourth, optional argument `plain` -- turns off the pattern matching facilities, so the function does a plain -- "find substring" operation, with no characters in `pattern` being considered -- "magic". Note that if `plain` is given, then `init` must be given as well. -- If the pattern has captures, then in a successful match the captured values -- are also returned, after the two indices. function find(s, pattern, init, plain) end --- -- Returns a formatted version of its variable number of arguments following -- the description given in its first argument (which must be a string). The -- format string follows the same rules as the `printf` family of standard C -- functions. The only differences are that the options/modifiers `*`, `l`, -- `L`, `n`, `p`, and `h` are not supported and that there is an extra option, -- `q`. The `q` option formats a string in a form suitable to be safely read -- back by the Lua interpreter: the string is written between double quotes, -- and all double quotes, newlines, embedded zeros, and backslashes in the -- string are correctly escaped when written. For instance, the call -- -- string.format('%q', 'a string with "quotes" and \n new line') -- -- will produce the string: -- -- "a string with \"quotes\" and \ -- new line" -- -- The options `c`, `d`, `E`, `e`, `f`, `g`, `G`, `i`, `o`, `u`, `X`, and -- `x` all expect a number as argument, whereas `q` and `s` expect a string. -- This function does not accept string values containing embedded zeros, -- except as arguments to the `q` option. function format(formatstring, ...) end --- -- Returns an iterator function that, each time it is called, returns the -- next captures from `pattern` over string `s`. If `pattern` specifies no -- captures, then the whole match is produced in each call. -- As an example, the following loop -- -- s = "hello world from Lua" -- for w in string.gmatch(s, "%a+") do -- print(w) -- end -- -- will iterate over all the words from string `s`, printing one per line. The -- next example collects all pairs `key=value` from the given string into -- a table: -- -- t = {} -- s = "from=world, to=Lua" -- for k, v in string.gmatch(s, "(%w+)=(%w+)") do -- t[k] = v -- end -- -- For this function, a '`^`' at the start of a pattern does not work as an -- anchor, as this would prevent the iteration. function gmatch(s, pattern) end --- -- Returns a copy of `s` in which all (or the first `n`, if given) -- occurrences of the `pattern` have been replaced by a replacement string -- specified by `repl`, which can be a string, a table, or a function. `gsub` -- also returns, as its second value, the total number of matches that occurred. -- -- If `repl` is a string, then its value is used for replacement. The character -- `%` works as an escape character: any sequence in `repl` of the form `%n`, -- with *n* between 1 and 9, stands for the value of the *n*-th captured -- substring (see below). The sequence `%0` stands for the whole match. The -- sequence `%%` stands for a single `%`. -- -- If `repl` is a table, then the table is queried for every match, using -- the first capture as the key; if the pattern specifies no captures, then -- the whole match is used as the key. -- -- If `repl` is a function, then this function is called every time a match -- occurs, with all captured substrings passed as arguments, in order; if -- the pattern specifies no captures, then the whole match is passed as a -- sole argument. -- -- If the value returned by the table query or by the function call is a -- string or a number, then it is used as the replacement string; otherwise, -- if it is false or nil, then there is no replacement (that is, the original -- match is kept in the string). -- -- Here are some examples: -- x = string.gsub("hello world", "(%w+)", "%1 %1") -- -- > x="hello hello world world" -- x = string.gsub("hello world", "%w+", "%0 %0", 1) -- -- > x="hello hello world" -- x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") -- -- > x="world hello Lua from" -- x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) -- -- > x="home = /home/roberto, user = roberto" -- x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) -- return loadstring(s)() -- end) -- -- > x="4+5 = 9" -- local t = {name="lua", version="5.1"} -- x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) -- -- > x="lua-5.1.tar.gz" function gsub(s, pattern, repl, n) end --- -- Receives a string and returns its length. The empty string `""` has -- length 0. Embedded zeros are counted, so `"a\000bc\000"` has length 5. function len(s) end --- -- Receives a string and returns a copy of this string with all uppercase -- letters changed to lowercase. All other characters are left unchanged. The -- definition of what an uppercase letter is depends on the current locale. function lower(s) end --- -- Looks for the first *match* of `pattern` in the string `s`. If it -- finds one, then `match` returns the captures from the pattern; otherwise -- it returns nil. If `pattern` specifies no captures, then the whole match -- is returned. A third, optional numerical argument `init` specifies where -- to start the search; its default value is 1 and can be negative. function match(s, pattern, init) end --- -- Returns a string that is the concatenation of `n` copies of the string -- `s`. function rep(s, n) return "" end --- -- Returns a string that is the string `s` reversed. function reverse(s) return "" end --- -- Returns the substring of `s` that starts at `i` and continues until -- `j`; `i` and `j` can be negative. If `j` is absent, then it is assumed to -- be equal to -1 (which is the same as the string length). In particular, -- the call `string.sub(s,1,j)` returns a prefix of `s` with length `j`, and -- `string.sub(s, -i)` returns a suffix of `s` with length `i`. function sub(s, i, j) end --- -- Receives a string and returns a copy of this string with all lowercase -- letters changed to uppercase. All other characters are left unchanged. The -- definition of what a lowercase letter is depends on the current locale. function upper(s) return "" end return string
apache-2.0
fqrouter/luci
libs/lucid-rpc/luasrc/lucid/rpc/ruci.lua
52
2144
--[[ LuCIRPCd (c) 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci" local tostring, getmetatable, pairs = tostring, getmetatable, pairs local error, type = error, type local nixio = require "nixio" local srv = require "luci.lucid.rpc.server" --- Remote UCI functions. module "luci.lucid.rpc.ruci" -- Prepare the remote UCI functions. function _factory() local m = srv.Module("Remote UCI API") for k, v in pairs(_M) do if type(v) == "function" and v ~= _factory then m:add(k, srv.Method.extended(v)) end end return m end -- Get the associate RUCI instance. local function getinst(session, name) return session.ruci and session.ruci[name] end -- Set a new RUCI instance. local function setinst(session, obj) session.ruci = session.ruci or {} local name = tostring(obj):match("0x([a-z0-9]+)") session.ruci[name] = obj return name end local Cursor = getmetatable(uci.cursor()) for name, func in pairs(Cursor) do _M[name] = function(session, inst, ...) inst = getinst(session, inst) return inst[name](inst, ...) end end --- Generate a new RUCI cursor. -- @param session Session object -- @param ... Parameters passed to the UCI constructor -- @return RUCI instance function cursor(session, ...) return setinst(session, uci.cursor(...)) end --- Generate a new RUCI state cursor. -- @param session Session object -- @param ... Parameters passed to the UCI constructor -- @return RUCI instance function cursor_state(session, ...) return setinst(session, uci.cursor_state(...)) end --- Custom foreach function. -- @param session Session object -- @param inst RUCI instance -- @param config UCI config -- @param sectiontype UCI sectiontype -- @return section data function foreach(session, inst, config, sectiontype) local inst = getinst(session, inst) local secs = {} inst:foreach(config, sectiontype, function(s) secs[#secs+1] = s end) return secs end
apache-2.0
kitala1/darkstar
scripts/globals/items/lungfish.lua
18
1255
----------------------------------------- -- ID: 4315 -- Item: Lungfish -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -2 -- Mind 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; elseif (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end if(target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4315); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -2); target:addMod(MOD_MND, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -2); target:delMod(MOD_MND, 4); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Port_San_dOria/npcs/Rugiette.lua
19
2279
----------------------------------- -- Area: Port San d'Oria -- NPC: Rugiette -- Involved in Quests: Riding on the Clouds, Lure of the Wildcat (San d'Oria) -- @pos 71 -9 -73 232 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if(trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart Flyer player:messageSpecial(FLYER_REFUSED); end end if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_1") == 8) then if(trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_1",0); player:tradeComplete(); player:addKeyItem(SCOWLING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SCOWLING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if(player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,14) == false) then player:startEvent(0x02ea); elseif(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_AVAILABLE and player:getVar("FFR") == 0)then player:startEvent(0x0259); else player:startEvent(0x1fe); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if(csid == 0x02ea) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",14,true); elseif(csid == 0x0259)then player:setVar("FFR",1); end end;
gpl-3.0
omideblisss/omid
plugins/anti_fosh.lua
49
1591
local function run(msg, matches) if is_owner(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['antifosh'] then lock_fosh = data[tostring(msg.to.id)]['settings']['antifosh'] end end end local chat = get_receiver(msg) local user = "user#id"..msg.from.id if lock_fosh == "yes" then send_large_msg(chat, 'بدلیل فحاشی از گروه سیکتیر شدید') chat_del_user(chat, user, ok_cb, true) end end return { patterns = { "کس(.*)", "کون(.*)", "کیر(.*)", "ممه(.*)", "سکس(.*)", "سیکتیر(.*)", "قهبه(.*)", "بسیک(.*)", "بیناموس(.*)", "اوبی(.*)", "کونی(.*)", "بیشرف(.*)", "کس ننه(.*)", "ساک(.*)", "کیری(.*)", "خار کوسه(.*)", "ننه(.*)", "خواهرتو(.*)", "سکسی(.*)", "کسکش(.*)", "سیک تیر(.*)", "گاییدم(.*)", "میگام(.*)", "میگامت(.*)", "بسیک(.*)", "خواهرت(.*)", "خارتو(.*)", "کونت(.*)", "کوست(.*)", "شورت(.*)", "سگ(.*)", "کیری(.*)", "دزد(.*)", "ننت(.*)", "ابمو(.*)", "جق(.*)" }, run = run } --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است--
gpl-2.0
kitala1/darkstar
scripts/globals/items/magma_steak.lua
36
1537
----------------------------------------- -- ID: 6071 -- Item: Magma Steak -- Food Effect: 180 Min, All Races ----------------------------------------- -- Strength +8 -- Attack +23% Cap 180 -- Ranged Attack +23% Cap 180 -- Vermin Killer +5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,6071); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 8); target:addMod(MOD_FOOD_ATTP, 23); target:addMod(MOD_FOOD_ATT_CAP, 180); target:addMod(MOD_FOOD_RATTP, 23); target:addMod(MOD_FOOD_RATT_CAP, 180); target:addMod(MOD_VERMIN_KILLER, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 8); target:delMod(MOD_FOOD_ATTP, 23); target:delMod(MOD_FOOD_ATT_CAP, 180); target:delMod(MOD_FOOD_RATTP, 23); target:delMod(MOD_FOOD_RATT_CAP, 180); target:delMod(MOD_VERMIN_KILLER, 5); end;
gpl-3.0
kiarash14/be
plugins/remind.lua
279
1873
local filename='data/remind.lua' local cronned = load_from_file(filename) local function save_cron(msg, text,date) local origin = get_receiver(msg) if not cronned[date] then cronned[date] = {} end local arr = { origin, text } ; table.insert(cronned[date], arr) serialize_to_file(cronned, filename) return 'Saved!' end local function delete_cron(date) for k,v in pairs(cronned) do if k == date then cronned[k]=nil end end serialize_to_file(cronned, filename) end local function cron() for date, values in pairs(cronned) do if date < os.time() then --time's up send_msg(values[1][1], "Time's up:"..values[1][2], ok_cb, false) delete_cron(date) --TODO: Maybe check for something else? Like user end end end local function actually_run(msg, delay,text) if (not delay or not text) then return "Usage: !remind [delay: 2h3m1s] text" end save_cron(msg, text,delay) return "I'll remind you on " .. os.date("%x at %H:%M:%S",delay) .. " about '" .. text .. "'" end local function run(msg, matches) local sum = 0 for i = 1, #matches-1 do local b,_ = string.gsub(matches[i],"[a-zA-Z]","") if string.find(matches[i], "s") then sum=sum+b end if string.find(matches[i], "m") then sum=sum+b*60 end if string.find(matches[i], "h") then sum=sum+b*3600 end end local date=sum+os.time() local text = matches[#matches] local text = actually_run(msg, date, text) return text end return { description = "remind plugin", usage = { "!remind [delay: 2hms] text", "!remind [delay: 2h3m] text", "!remind [delay: 2h3m1s] text" }, patterns = { "^!remind ([0-9]+[hmsdHMSD]) (.+)$", "^!remind ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$", "^!remind ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$" }, run = run, cron = cron }
gpl-2.0
kitala1/darkstar
scripts/globals/weaponskills/spirit_taker.lua
30
1443
----------------------------------- -- Spirit Taker -- Staff weapon skill -- Skill Level: 215 -- Converts damage dealt to own MP. Damage varies with TP. -- Will stack with Sneak Attack. -- Not aligned with any "elemental gorgets" or "elemental belts" due to it's absence of Skillchain properties. -- It is a physical weapon skill, and is affected by the user's params.accuracy and the enemy's evasion. It may miss completely. -- Element: None -- Modifiers: INT:50% ; MND:50% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.5; params.mnd_wsc = 0.5; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER player:addMP(damage); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
kitala1/darkstar
scripts/zones/Throne_Room/mobs/Shadow_of_Rage.lua
29
1102
----------------------------------- -- Area: Throne Room -- NPC: Shadows -- Mission 9-2 BCNM Fight ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) end; function onMobDespawn(mob) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) printf("updateCSID: %u",csid); printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) printf("finishCSID: %u",csid); printf("RESULT: %u",option); end;
gpl-3.0
xsolinsx/AISashaAPI
plugins/check_tag.lua
1
25719
notified = { } -- recursive to simplify code local function check_tag(msg, user_id, user) if msg.entities then for k, v in pairs(msg.entities) do -- check if there's a text_mention if msg.entities[k].type == 'text_mention' and msg.entities[k].user then if tonumber(msg.entities[k].user.id) == tonumber(user_id) then return true end end end end if user then if type(user) == 'table' then -- only sudoers -- check if first name is in message if msg.text then if string.match(msg.text, "^" .. user.first_name) or string.match(msg.text, "%W+" .. user.first_name .. "%W+") or string.match(msg.text, user.first_name .. "$") then return true end end if user.username then -- check if username is in message if msg.text then if string.match(msg.text:lower(), "^" .. user.username:lower()) or string.match(msg.text:lower(), "%W+" .. user.username:lower() .. "%W+") or string.match(msg.text:lower(), user.username:lower() .. "$") then return true end end end return false else if msg.text then if string.match(msg.text:lower(), "^" .. tostring(user):lower()) or string.match(msg.text:lower(), "%W+" .. tostring(user):lower() .. "%W+") or string.match(msg.text:lower(), tostring(user):lower() .. "$") then return true end end end end end local function run(msg, matches) if msg.cb then if matches[2] == 'ALREADYREAD' then answerCallbackQuery(msg.cb_id, langs[msg.lang].markedAsRead, false) if not deleteMessage(msg.chat.id, msg.message_id, true) then editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].markedAsRead) end elseif matches[2] == 'REGISTER' then if not redis_hget_something('tagalert:usernames', msg.from.id) then answerCallbackQuery(msg.cb_id, langs[msg.lang].tagalertRegistered, true) if msg.from.username then redis_hset_something('tagalert:usernames', msg.from.id, msg.from.username:lower()) else redis_hset_something('tagalert:usernames', msg.from.id, true) end mystat(matches[1] .. matches[2] .. msg.from.id) else answerCallbackQuery(msg.cb_id, langs[msg.lang].pmnoticesAlreadyRegistered, true) end editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].startMessage .. '\n' .. langs[msg.lang].nowSetNickname) -- editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].startMessage .. '\n' .. langs[msg.lang].nowSetNickname, { inline_keyboard = { { { text = langs[msg.lang].tutorialWord, url = 'http://telegra.ph/TUTORIAL-AISASHABOT-09-15' } } } }) else if matches[2] == 'DELETEUP' then if tonumber(matches[3]) == tonumber(msg.from.id) then if deleteMessage(msg.chat.id, msg.message_id) then answerCallbackQuery(msg.cb_id, langs[msg.lang].upMessageDeleted, false) else answerCallbackQuery(msg.cb_id, langs[msg.lang].cantDeleteMessage, false) editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].stop) end end mystat(matches[1] .. matches[2] .. matches[3] .. matches[4]) elseif matches[2] == 'GOTO' then local link_in_keyboard = false if msg.from.username then local res = sendKeyboard(matches[4], 'UP @' .. msg.from.username .. '\n#tag' .. msg.from.id, keyboard_tag(matches[4], matches[3], true, msg.from.id), false, matches[3], false, true) if data[tostring(matches[4])] then if is_mod2(msg.from.id, matches[4]) or(not data[tostring(matches[4])].settings.lock_grouplink) then if data[tostring(matches[4])].link then link_in_keyboard = true if res then editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].repliedToMessage, { inline_keyboard = { { { text = langs[msg.lang].alreadyRead, callback_data = 'check_tagALREADYREAD' } }, { { text = langs[msg.lang].gotoGroup, url = data[tostring(matches[4])].link } } } }, false, false, true) else editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].cantFindMessage, { inline_keyboard = { { { text = langs[msg.lang].alreadyRead, callback_data = 'check_tagALREADYREAD' } }, { { text = langs[msg.lang].gotoGroup, url = data[tostring(matches[4])].link } } } }, false, false, true) end end end end if not link_in_keyboard then if res then answerCallbackQuery(msg.cb_id, langs[msg.lang].repliedToMessage, true) else answerCallbackQuery(msg.cb_id, langs[msg.lang].cantFindMessage, true) end if not deleteMessage(msg.chat.id, msg.message_id, true) then if sent then editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].repliedToMessage) else editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].cantFindMessage) end end end else local sent = false local res = sendKeyboard(matches[4], 'UP [' .. msg.from.first_name:mEscape_hard() .. '](tg://user?id=' .. msg.from.id .. ')\n#tag' .. msg.from.id, keyboard_tag(matches[4], matches[3], true, msg.from.id), 'markdown', matches[3], false, true) if res then sent = true else res = sendKeyboard(matches[4], 'UP <a href="tg://user?id=' .. msg.from.id .. '">' .. html_escape(msg.from.first_name) .. '</a>\n#tag' .. msg.from.id, keyboard_tag(matches[4], matches[3], true, msg.from.id), 'html', matches[3], false, true) if res then sent = true else res = sendKeyboard(matches[4], 'UP [' .. msg.from.first_name .. '](tg://user?id=' .. msg.from.id .. ')\n#tag' .. msg.from.id, keyboard_tag(matches[4], matches[3], true, msg.from.id), false, matches[3], false, true) if res then sent = true end end end if data[tostring(matches[4])] then if is_mod2(msg.from.id, matches[4]) or(not data[tostring(matches[4])].settings.lock_grouplink) then if data[tostring(matches[4])].link then link_in_keyboard = true if sent then editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].repliedToMessage, { inline_keyboard = { { { text = langs[msg.lang].alreadyRead, callback_data = 'check_tagALREADYREAD' } }, { { text = langs[msg.lang].gotoGroup, url = data[tostring(matches[4])].link } } } }, false, false, true) else editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].cantFindMessage, { inline_keyboard = { { { text = langs[msg.lang].alreadyRead, callback_data = 'check_tagALREADYREAD' } }, { { text = langs[msg.lang].gotoGroup, url = data[tostring(matches[4])].link } } } }, false, false, true) end end end end if sent then answerCallbackQuery(msg.cb_id, langs[msg.lang].repliedToMessage, true) else answerCallbackQuery(msg.cb_id, langs[msg.lang].cantFindMessage, true) end if not link_in_keyboard then if not deleteMessage(msg.chat.id, msg.message_id, true) then if sent then editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].repliedToMessage) else editMessageText(msg.chat.id, msg.message_id, langs[msg.lang].cantFindMessage) end end end end mystat(matches[1] .. matches[2] .. matches[3] .. matches[4]) end end return end if matches[1]:lower() == 'enablenotices' then if data[tostring(msg.chat.id)] and msg.from.is_owner then if not data[tostring(msg.chat.id)].settings.pmnotices then mystat('/enablenotices') data[tostring(msg.chat.id)].settings.pmnotices = true return langs[msg.lang].noticesEnabledGroup else return langs[msg.lang].noticesAlreadyEnabledGroup end else return langs[msg.lang].useYourGroups .. '\n' .. langs[msg.lang].require_owner end end if matches[1]:lower() == 'disablenotices' then if data[tostring(msg.chat.id)] and msg.from.is_owner then if data[tostring(msg.chat.id)].settings.pmnotices then mystat('/disablenotices') data[tostring(msg.chat.id)].settings.pmnotices = false return langs[msg.lang].noticesDisabledGroup else return langs[msg.lang].noticesGroupAlreadyDisabled end else return langs[msg.lang].useYourGroups .. '\n' .. langs[msg.lang].require_owner end end if matches[1]:lower() == 'registernotices' then if msg.chat.type == 'private' then if not redis_get_something('notice:' .. msg.from.id) then mystat('/registernotices') redis_set_something('notice:' .. msg.from.id, 1) return langs[msg.lang].pmnoticesRegistered else return langs[msg.lang].pmnoticesAlreadyRegistered end else return sendReply(msg, langs[msg.lang].require_private, 'html') end end if matches[1]:lower() == 'unregisternotices' then if msg.chat.type == 'private' then if redis_get_something('notice:' .. msg.from.id) then mystat('/unregisternotices') redis_del_something('notice:' .. msg.from.id) return langs[msg.lang].pmnoticesUnregistered else return langs[msg.lang].pmnoticesAlreadyUnregistered end else return sendReply(msg, langs[msg.lang].require_private, 'html') end end if matches[1]:lower() == 'enabletagalert' then if data[tostring(msg.chat.id)] and msg.from.is_owner then if not data[tostring(msg.chat.id)].settings.tagalert then mystat('/enabletagalert') data[tostring(msg.chat.id)].settings.tagalert = true return langs[msg.lang].tagalertGroupEnabled else return langs[msg.lang].tagalertGroupAlreadyEnabled end else return langs[msg.lang].useYourGroups .. '\n' .. langs[msg.lang].require_owner end end if matches[1]:lower() == 'disabletagalert' then if data[tostring(msg.chat.id)] and msg.from.is_owner then if data[tostring(msg.chat.id)].settings.tagalert then mystat('/disabletagalert') data[tostring(msg.chat.id)].settings.tagalert = false return langs[msg.lang].tagalertGroupDisabled else return langs[msg.lang].tagalertGroupAlreadyDisabled end else return langs[msg.lang].useYourGroups .. '\n' .. langs[msg.lang].require_owner end end if matches[1]:lower() == 'registertagalert' then if msg.chat.type == 'private' then if not redis_hget_something('tagalert:usernames', msg.from.id) then mystat('/registertagalert') if msg.from.username then redis_hset_something('tagalert:usernames', msg.from.id, msg.from.username:lower()) else redis_hset_something('tagalert:usernames', msg.from.id, true) end return langs[msg.lang].tagalertRegistered else return langs[msg.lang].tagalertAlreadyRegistered end else return sendReply(msg, langs[msg.lang].require_private, 'html') end end if matches[1]:lower() == 'unregistertagalert' then if redis_hget_something('tagalert:usernames', msg.from.id) then mystat('/unregistertagalert') redis_hdelsrem_something('tagalert:usernames', msg.from.id) redis_hdelsrem_something('tagalert:nicknames', msg.from.id) return langs[msg.lang].tagalertUnregistered else return langs[msg.lang].tagalertAlreadyUnregistered end end if matches[1]:lower() == 'setnickname' and matches[2] then if redis_hget_something('tagalert:usernames', msg.from.id) then if string.len(matches[2]) >= 3 and matches[2]:match('%w+') then mystat('/setnickname') redis_hset_something('tagalert:nicknames', msg.from.id, matches[2]:lower()) return langs[msg.lang].tagalertNicknameSet else return langs[msg.lang].tagalertNicknameTooShort end else return langs[msg.lang].tagalertRegistrationNeeded end end if matches[1]:lower() == 'unsetnickname' then if redis_hget_something('tagalert:usernames', msg.from.id) then mystat('/unsetnickname') redis_hdelsrem_something('tagalert:nicknames', msg.from.id) return langs[msg.lang].tagalertNicknameUnset else return langs[msg.lang].tagalertRegistrationNeeded end end --[[if matches[1]:lower() == 'tagall' then if msg.from.is_owner then return langs[msg.lang].useAISasha local text = '' if matches[2] then mystat('/tagall <text>') text = matches[2] .. "\n" elseif msg.reply then mystat('/tagall <reply_text>') text = msg.reply_to_message.text .. "\n" end local participants = getChatParticipants(msg.chat.id) for k, v in pairs(participants) do if v.user then v = v.user if v.username then text = text .. "@" .. v.username .. " " else local print_name =(v.first_name or '') ..(v.last_name or '') if print_name ~= '' then text = text .. print_name .. " " end end end end return text else return langs[msg.lang].require_owner end end]] end local function send_tag_alert(msg, user_id) local lang = get_lang(user_id) if msg.reply then if not msg.reply_to_message.service then forwardMessage(user_id, msg.chat.id, msg.reply_to_message.message_id) end end local text = langs[lang].receiver .. msg.chat.print_name:gsub("_", " ") .. ' [' .. msg.chat.id .. ']\n' .. langs[lang].sender if msg.from.username then text = text .. '@' .. msg.from.username .. ' [' .. msg.from.id .. ']\n' else text = text .. msg.from.print_name:gsub("_", " ") .. ' [' .. msg.from.id .. ']\n' end text = text .. langs[lang].msgText if msg.media then local tot_len = string.len(text .. '\n#tag' .. user_id) local caption_len = string.len(msg.text) local allowed_len = 200 - tot_len if caption_len > allowed_len then text = text .. msg.text:sub(1, allowed_len - 3) .. '...' else text = text .. msg.text end text = text .. '\n#tag' .. user_id if msg.media_type == 'photo' then local bigger_pic_id = '' local size = 0 for k, v in pairsByKeys(msg.photo) do if v.file_size then if v.file_size > size then size = v.file_size bigger_pic_id = v.file_id end end end sendPhotoId(user_id, bigger_pic_id, text) elseif msg.media_type == 'video' then sendVideoId(user_id, msg.video.file_id, text) elseif msg.media_type == 'audio' then sendAudioId(user_id, msg.audio.file_id, text) elseif msg.media_type == 'voice_note' then sendVoiceId(user_id, msg.voice.file_id, text) elseif msg.media_type == 'gif' then sendAnimationId(user_id, msg.animation.file_id, text) elseif msg.media_type == 'document' then sendDocumentId(user_id, msg.document.file_id, text) end else text = text .. msg.text .. '\n#tag' .. user_id sendMessage(user_id, text) end sendKeyboard(user_id, langs[lang].whatDoYouWantToDo, keyboard_tag(msg.chat.id, msg.message_id, false, user_id)) end local function pre_process(msg) if msg then notified = { } -- update usernames if redis_hget_something('tagalert:usernames', msg.from.id) then if msg.from.username then if redis_hget_something('tagalert:usernames', msg.from.id) ~= msg.from.username:lower() then redis_hset_something('tagalert:usernames', msg.from.id, msg.from.username:lower()) end else redis_hset_something('tagalert:usernames', msg.from.id, true) end end if data[tostring(msg.chat.id)] then -- exclude private chats with bot for k, v in pairs(config.sudo_users) do if not notified[tostring(k)] then -- exclude already notified if tonumber(msg.from.id) ~= tonumber(k) and tonumber(msg.from.id) ~= tonumber(bot.userVersion.id) and tonumber(k) ~= tonumber(bot.userVersion.id) then -- exclude autotags and tags from tg-cli version and tags of tg-cli version if check_tag(msg, k, v) then print('sudo', k) -- set user as notified to not send multiple notifications notified[tostring(k)] = true if sendChatAction(k, 'typing') then send_tag_alert(msg, k) end end end end end if data[tostring(msg.chat.id)].settings.tagalert then -- if group is enabled to tagalert notifications then local usernames = redis_get_something('tagalert:usernames') for k, v in pairs(usernames) do if not notified[tostring(k)] then -- exclude already notified if tonumber(msg.from.id) ~= tonumber(k) and tonumber(msg.from.id) ~= tonumber(bot.userVersion.id) and tonumber(k) ~= tonumber(bot.userVersion.id) then -- exclude autotags and tags from tg-cli version and tags of tg-cli version local usr = redis_hget_something('tagalert:usernames', k) if usr == 'true' then usr = nil end if check_tag(msg, k, usr) then print('username', k) if not msg.command then -- set user as notified to not send multiple notifications notified[tostring(k)] = true if sendChatAction(k, 'typing') then send_tag_alert(msg, k) end else print("TAG FOUND BUT COMMAND") end end end end end local nicknames = redis_get_something('tagalert:nicknames') for k, v in pairs(nicknames) do if not notified[tostring(k)] then -- exclude already notified if tonumber(msg.from.id) ~= tonumber(k) and tonumber(msg.from.id) ~= tonumber(bot.userVersion.id) and tonumber(k) ~= tonumber(bot.userVersion.id) then -- exclude autotags and tags from tg-cli version and tags of tg-cli version local nck = redis_hget_something('tagalert:usernames', k) if nck == 'true' then nck = nil end if check_tag(msg, k, nck) then print('nickname', k) if not msg.command then -- set user as notified to not send multiple notifications notified[tostring(k)] = true if sendChatAction(k, 'typing') then local obj = getChatMember(msg.chat.id, k) if type(obj) == 'table' then if obj.ok and obj.result then obj = obj.result if obj.status == 'creator' or obj.status == 'administrator' or obj.status == 'member' or obj.status == 'restricted' then send_tag_alert(msg, k) end end end end else print("TAG FOUND BUT COMMAND") end end end end end end end return msg end end return { description = "CHECK_TAG", patterns = { "^(###cbcheck_tag)(ALREADYREAD)$", "^(###cbcheck_tag)(REGISTER)$", "^(###cbcheck_tag)(DELETEUP)(%d+)(%-%d+)$", "^(###cbcheck_tag)(GOTO)(%d+)(%-%d+)$", "^[#!/]([Ee][Nn][Aa][Bb][Ll][Ee][Tt][Aa][Gg][Aa][Ll][Ee][Rr][Tt])$", "^[#!/]([Dd][Ii][Ss][Aa][Bb][Ll][Ee][Tt][Aa][Gg][Aa][Ll][Ee][Rr][Tt])$", "^[#!/]([Rr][Ee][Gg][Ii][Ss][Tt][Ee][Rr][Tt][Aa][Gg][Aa][Ll][Ee][Rr][Tt])$", "^[#!/]([Uu][Nn][Rr][Ee][Gg][Ii][Ss][Tt][Ee][Rr][Tt][Aa][Gg][Aa][Ll][Ee][Rr][Tt])$", "^[#!/]([Ee][Nn][Aa][Bb][Ll][Ee][Nn][Oo][Tt][Ii][Cc][Ee][Ss])$", "^[#!/]([Dd][Ii][Ss][Aa][Bb][Ll][Ee][Nn][Oo][Tt][Ii][Cc][Ee][Ss])$", "^[#!/]([Rr][Ee][Gg][Ii][Ss][Tt][Ee][Rr][Nn][Oo][Tt][Ii][Cc][Ee][Ss])$", "^[#!/]([Uu][Nn][Rr][Ee][Gg][Ii][Ss][Tt][Ee][Rr][Nn][Oo][Tt][Ii][Cc][Ee][Ss])$", "^[#!/]([Ss][Ee][Tt][Nn][Ii][Cc][Kk][Nn][Aa][Mm][Ee]) (.*)$", "^[#!/]([Uu][Nn][Ss][Ee][Tt][Nn][Ii][Cc][Kk][Nn][Aa][Mm][Ee])$", "^[#!/]([Tt][Aa][Gg][Aa][Ll][Ll])$", "^[#!/]([Tt][Aa][Gg][Aa][Ll][Ll]) +(.+)$", }, run = run, pre_process = pre_process, min_rank = 1, syntax = { "USER", "/registertagalert", "/unregistertagalert", "/registernotices", "/unregisternotices", "/setnickname {nickname}", "/unsetnickname", "OWNER", "/enabletagalert", "/disabletagalert", "/enablenotices", "/disablenotices", -- "/tagall {text}|{reply_text}", }, }
gpl-2.0
Mechaniston/FibaroHC_mechHomeBcfg
TB_ventAuto (253, maxInst = 1).lua
1
1093
--[[ %% autostart %% properties %% globals --]] -- CONSTS local debugMode = false; -- Device's ID local ventID = 12; -- init vars local ventValue = "0"; local curTime = 0; -- PROCESS if ( debugMode ) then fibaro:debug("Vent sequence ON!"); end while true do ventValue = fibaro:getValue(ventID, "value"); if ( (ventValue == "0") and (fibaro:getGlobalValue("B_vent") == "0") ) then if ( debugMode ) then fibaro:debug("Vent turn ON"); end fibaro:call(ventID, "setValue", "50"); curTime = os.time(); while ( ((os.time() - curTime) < (10 * 60)) and (fibaro:getGlobalValue("B_vent") == "0") ) do fibaro:sleep(5000); end if ( fibaro:getGlobalValue("B_vent") == "0" ) then if ( debugMode ) then fibaro:debug("Vent turn OFF"); end fibaro:call(ventID, "setValue", "0"); else if ( debugMode ) then fibaro:debug("B_vent mode detected!"); end end end fibaro:sleep(50 * 60 * 1000); end if ( debugMode ) then fibaro:debug("Vent sequence OFF!"); end
mit
kidaa/MoonGen
test/example-scripts/test-qos.lua
6
2258
local mg = require "moongen" require "number-assert" describe("quality-of-service-test example", function() it("should run", function() local proc = mg.start("./examples/quality-of-service-test.lua", 8, 9, 100, 1000) finally(function() proc:destroy() end) proc:waitForPorts(2) --[[ output should look like this: [Output] [RxQueue: id=9, qid=0] Port 42: Received 18 packets, current rate 0.00 Mpps, 0.00 MBit/s, 0.00 MBit/s wire rate [Output] [TxQueue: id=8, qid=0] Sent 976500 packets, current rate 0.98 Mpps, 999.91 MBit/s, 1156.15 MBit/s wire rate [Output] [RxQueue: id=9, qid=0] Port 43: Received 97610 packets, current rate 0.10 Mpps, 99.95 MBit/s, 115.57 MBit/s wire rate [Output] [RxQueue: id=9, qid=0] Port 42: Received 976617 packets, current rate 0.98 Mpps, 1000.04 MBit/s, 1156.29 MBit/s wire rate [Output] [TxQueue: id=8, qid=1] Sent 97902 packets, current rate 0.10 Mpps, 100.22 MBit/s, 115.87 MBit/s wire rate [Output] [TxQueue: id=8, qid=0] Sent 1953063 packets, current rate 0.98 Mpps, 999.95 MBit/s, 1156.20 MBit/s wire rate [Output] [RxQueue: id=9, qid=0] Port 43: Received 195263 packets, current rate 0.10 Mpps, 100.00 MBit/s, 115.62 MBit/s wire rate [Output] [RxQueue: id=9, qid=0] Port 42: Received 1953130 packets, current rate 0.98 Mpps, 999.95 MBit/s, 1156.19 MBit/s wire rate [Output] [TxQueue: id=8, qid=1] Sent 195552 packets, current rate 0.10 Mpps, 99.98 MBit/s, 115.60 MBit/s wire rate ]]-- -- ignore first measurement proc:waitFor("Sent %d+ packets, current rate (%S+) Mpps") proc:waitFor("Sent %d+ packets, current rate (%S+) Mpps") local rate1 = proc:waitFor("qid=0.* Sent %d+ packets, current rate (%S+) Mpps") local rate2 = proc:waitFor("qid=1.* Sent %d+ packets, current rate (%S+) Mpps") rate1, rate2 = tonumber(rate1), tonumber(rate2) assert.rel_range(rate1, 1, 5) assert.rel_range(rate2, 0.1, 5) -- should also be receiving at that rate rate1 = proc:waitFor("Port 42: Received %d+ packets, current rate (%S+) Mpps") rate2 = proc:waitFor("Port 43: Received %d+ packets, current rate (%S+) Mpps") rate1, rate2 = tonumber(rate1), tonumber(rate2) assert.rel_range(rate1, 1, 5) assert.rel_range(rate2, 0.1, 5) proc:kill() end) end)
mit
Teaonly/easyLearning.js
qulogo/data.lua
1
1511
require('torch') require('image') local randomBatch = function(opt, config, pageIndex) local fileName = opt.d .. "/" .. pageIndex .. ".jpg" local fullImage = image.loadJPG(fileName) local batch = torch.Tensor(opt.batch_size, 3, config.inputHeight, config.inputWidth) local i = 1 for i = 1, opt.batch_size do while true do local x = torch.random(config.imageWidth - config.inputWidth) local y = torch.random(config.imageHeight - config.inputHeight) local xx = math.min(x, config.logoX) local yy = math.min(y, config.logoY) local xx_ = math.max(x+config.inputWidth, config.logoX + config.logoWidth) local yy_ = math.max(x+config.inputHeight, config.logoY + config.logoHeight) if ( (xx_ - xx) > (config.logoWidth + config.inputWidth) or (yy_ - yy) > (config.logoHeight + config.inputHeight) ) then batch[{i,{},{},{}}]:copy( fullImage[{{},{yy, yy + config.inputHeight - 1},{xx, xx + config.inputWidth -1}}] ) break; end end end batch = batch * 2 - 1; local maskPos = {{},{}, {config.maskTop, config.maskTop + config.maskHeight - 1}, {config.maskLeft, config.maskLeft + config.maskWidth - 1} } local centerBatch = batch[maskPos]:clone() batch[maskPos]:zero() return batch, centerBatch end d = {} d.randomBatch = randomBatch return d
mit
kitala1/darkstar
scripts/zones/Chateau_dOraguille/npcs/Nachou.lua
38
1046
----------------------------------- -- Area: Chateau d'Oraguille -- NPC: Nachou -- Type: Standard NPC -- @zone: 233 -- @pos -39.965 -3.999 34.292 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x020b); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Cavernous_Maw.lua
58
1890
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Cavernous Maw -- @pos -334 -24 52 -- Teleports Players to Abyssea - Attohwa ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/abyssea"); require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_ABYSSEA == 1 and player:getMainLvl() >= 30) then local HasStone = getTravStonesTotal(player); if (HasStone >= 1 and player:getQuestStatus(ABYSSEA, DAWN_OF_DEATH) == QUEST_ACCEPTED and player:getQuestStatus(ABYSSEA, A_FLUTTERY_FIEND) == QUEST_AVAILABLE) then player:startEvent(62); else player:startEvent(61,0,1); -- No param = no entry. end else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 62) then player:addQuest(ABYSSEA, A_FLUTTERY_FIEND); elseif (csid == 63) then -- Killed Itzpapalotl elseif (csid == 61 and option == 1) then player:setPos(-140, 20, -181, 131, 215); end end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/bluetail.lua
18
1256
----------------------------------------- -- ID: 4399 -- Item: Bluetail -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 3 -- Mind -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if(target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4399); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -5); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Selbina/npcs/Bretta.lua
34
1105
----------------------------------- -- Area: Selbina -- NPC: Bretta -- @zone -- @pos ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getZPos() > -28.750) then player:startEvent(0x046d, 1152 - ((os.time() - 1009810584)%1152)); else player:startEvent(0x00de); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
apletnev/koreader
plugins/coverbrowser.koplugin/main.lua
2
27105
local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local logger = require("logger") local _ = require("gettext") local BookInfoManager = require("bookinfomanager") --[[ This plugin provides additional display modes to file browsers (File Manager and History). It does that by dynamically replacing some methods code to their classes or instances. --]] -- We need to save the original methods early here as locals. -- For some reason, saving them as attributes in init() does not allow -- us to get back to classic mode local FileChooser = require("ui/widget/filechooser") local _FileChooser__recalculateDimen_orig = FileChooser._recalculateDimen local _FileChooser_updateItems_orig = FileChooser.updateItems local _FileChooser_onCloseWidget_orig = FileChooser.onCloseWidget local _FileChooser_onSwipe_orig = FileChooser.onSwipe local FileManagerHistory = require("apps/filemanager/filemanagerhistory") local _FileManagerHistory_updateItemTable_orig = FileManagerHistory.updateItemTable -- Available display modes local DISPLAY_MODES = { -- nil or "" -- classic : filename only mosaic_image = true, -- 3x3 grid covers with images mosaic_text = true, -- 3x3 grid covers text only list_image_meta = true, -- image with metadata (title/authors) list_only_meta = true, -- metadata with no image list_image_filename = true, -- image with filename (no metadata) } -- Store some states as locals, to be permanent across instantiations local init_done = false local filemanager_display_mode = false -- not initialized yet local history_display_mode = false -- not initialized yet local CoverBrowser = InputContainer:new{} function CoverBrowser:init() self.full_featured = true -- (Could be set to false for some platforms to provide a fallback -- option with only a menu for managing a few core settings) self.ui.menu:registerToMainMenu(self) if not self.full_featured then -- nothing else than menu registration return end if init_done then -- things already patched according to current modes return end self:setupFileManagerDisplayMode(BookInfoManager:getSetting("filemanager_display_mode")) self:setupHistoryDisplayMode(BookInfoManager:getSetting("history_display_mode")) init_done = true end function CoverBrowser:addToMainMenu(menu_items) -- We add it only to FileManager menu if self.ui.view then -- Reader return end -- Items available even if not full_featured -- (settings used by core, that fit in this menu) local generic_items = { { text_func = function() local current_state = _("Show new files in bold") if G_reader_settings:readSetting("show_file_in_bold") == "opened" then current_state = _("Show opened files in bold") elseif G_reader_settings:readSetting("show_file_in_bold") == false then current_state = _("Show files in bold") -- with checkmark unchecked end if self.full_featured then -- Inform that this settings applies only to classic file chooser current_state = _("(Classic mode) ") .. current_state end return current_state end, checked_func = function() return G_reader_settings:readSetting("show_file_in_bold") ~= false end, sub_item_table = { { text = _("Don't show files in bold"), checked_func = function() return G_reader_settings:readSetting("show_file_in_bold") == false end, callback = function() G_reader_settings:saveSetting("show_file_in_bold", false) self:refreshFileManagerInstance() end, }, { text = _("Show opened files in bold"), checked_func = function() return G_reader_settings:readSetting("show_file_in_bold") == "opened" end, callback = function() G_reader_settings:saveSetting("show_file_in_bold", "opened") self:refreshFileManagerInstance() end, }, { text = _("Show new (not yet opened) files in bold"), checked_func = function() return G_reader_settings:readSetting("show_file_in_bold") ~= false and G_reader_settings:readSetting("show_file_in_bold") ~= "opened" end, callback = function() G_reader_settings:delSetting("show_file_in_bold") self:refreshFileManagerInstance() end, }, }, separator = true, }, { text = _("Shorten home directory to ~"), checked_func = function() return G_reader_settings:readSetting("home_dir_display_name") end, callback = function() if G_reader_settings:readSetting("home_dir_display_name") then G_reader_settings:delSetting("home_dir_display_name") local FileManager = require("apps/filemanager/filemanager") if FileManager.instance then FileManager.instance:reinit() end else G_reader_settings:saveSetting("home_dir_display_name", "~") local FileManager = require("apps/filemanager/filemanager") if FileManager.instance then FileManager.instance:reinit() end end end, }, { text = _("Auto-remove deleted or purged items from history"), checked_func = function() return G_reader_settings:readSetting("autoremove_deleted_items_from_history") end, callback = function() G_reader_settings:flipNilOrFalse("autoremove_deleted_items_from_history") end, }, } if not self.full_featured then -- Make the generic items directly as 1st level items, -- and use alternate name for main menu, not mentionning -- "display mode" that are not available menu_items.filemanager_display_mode = { text = _("File browser settings"), sub_item_table = generic_items } return end menu_items.filemanager_display_mode = { text = _("Display mode"), sub_item_table = { -- selecting these does not close menu, which may be nice -- so one can see how they look below the menu { text = _("Classic (filename only)"), checked_func = function() return not filemanager_display_mode end, callback = function() self:setupFileManagerDisplayMode("") end, }, { text = _("Mosaic with cover images"), checked_func = function() return filemanager_display_mode == "mosaic_image" end, callback = function() self:setupFileManagerDisplayMode("mosaic_image") end, }, { text = _("Mosaic with text covers"), checked_func = function() return filemanager_display_mode == "mosaic_text" end, callback = function() self:setupFileManagerDisplayMode("mosaic_text") end, }, { text = _("Detailed list with cover images and metadata"), checked_func = function() return filemanager_display_mode == "list_image_meta" end, callback = function() self:setupFileManagerDisplayMode("list_image_meta") end, }, { text = _("Detailed list with metadata, no images"), checked_func = function() return filemanager_display_mode == "list_only_meta" end, callback = function() self:setupFileManagerDisplayMode("list_only_meta") end, }, { text = _("Detailed list with cover images and filenames"), checked_func = function() return filemanager_display_mode == "list_image_filename" end, callback = function() self:setupFileManagerDisplayMode("list_image_filename") end, separator = true, }, -- Plug the same choices for History here as a submenu -- (Any other suitable place for that ?) { text = _("History display mode"), sub_item_table = { { text = _("Classic (filename only)"), checked_func = function() return not history_display_mode end, callback = function() self:setupHistoryDisplayMode("") end, }, { text = _("Mosaic with cover images"), checked_func = function() return history_display_mode == "mosaic_image" end, callback = function() self:setupHistoryDisplayMode("mosaic_image") end, }, { text = _("Mosaic with text covers"), checked_func = function() return history_display_mode == "mosaic_text" end, callback = function() self:setupHistoryDisplayMode("mosaic_text") end, }, { text = _("Detailed list with cover images and metadata"), checked_func = function() return history_display_mode == "list_image_meta" end, callback = function() self:setupHistoryDisplayMode("list_image_meta") end, }, { text = _("Detailed list with metadata, no images"), checked_func = function() return history_display_mode == "list_only_meta" end, callback = function() self:setupHistoryDisplayMode("list_only_meta") end, }, { text = _("Detailed list with cover images and filenames"), checked_func = function() return history_display_mode == "list_image_filename" end, callback = function() self:setupHistoryDisplayMode("list_image_filename") end, separator = true, }, }, separator = true, }, -- Misc settings { text = _("Other settings"), sub_item_table = { { text = _("Show hint for books with description"), checked_func = function() return not BookInfoManager:getSetting("no_hint_description") end, callback = function() if BookInfoManager:getSetting("no_hint_description") then BookInfoManager:saveSetting("no_hint_description", false) else BookInfoManager:saveSetting("no_hint_description", true) end self:refreshFileManagerInstance() end, }, { text = _("Show hint for opened books in history"), checked_func = function() return BookInfoManager:getSetting("history_hint_opened") end, callback = function() if BookInfoManager:getSetting("history_hint_opened") then BookInfoManager:saveSetting("history_hint_opened", false) else BookInfoManager:saveSetting("history_hint_opened", true) end self:refreshFileManagerInstance() end, }, { text = _("Append series metadata to authors"), checked_func = function() return BookInfoManager:getSetting("append_series_to_authors") end, callback = function() if BookInfoManager:getSetting("append_series_to_authors") then BookInfoManager:saveSetting("append_series_to_authors", false) else BookInfoManager:saveSetting("append_series_to_authors", true) end self:refreshFileManagerInstance() end, }, { text = _("Append series metadata to title"), checked_func = function() return BookInfoManager:getSetting("append_series_to_title") end, callback = function() if BookInfoManager:getSetting("append_series_to_title") then BookInfoManager:saveSetting("append_series_to_title", false) else BookInfoManager:saveSetting("append_series_to_title", true) end self:refreshFileManagerInstance() end, }, -- generic_items will be inserted here }, }, { text = _("Book info cache management"), sub_item_table = { { text_func = function() -- add current db size to menu text local sstr = BookInfoManager:getDbSize() return _("Current cache size: ") .. sstr end, -- no callback, only for information }, { text = _("Prune cache of removed books"), callback = function() local ConfirmBox = require("ui/widget/confirmbox") UIManager:close(self.file_dialog) UIManager:show(ConfirmBox:new{ -- Checking file existences is quite fast, but deleting entries is slow. text = _("Are you sure that you want to prune cache of removed books?\n(This may take a while.)"), ok_text = _("Prune cache"), ok_callback = function() local InfoMessage = require("ui/widget/infomessage") local msg = InfoMessage:new{ text = _("Pruning cache of removed books…") } UIManager:show(msg) UIManager:nextTick(function() local summary = BookInfoManager:removeNonExistantEntries() UIManager:close(msg) UIManager:show( InfoMessage:new{ text = summary } ) end) end }) end, }, { text = _("Compact cache database"), callback = function() local ConfirmBox = require("ui/widget/confirmbox") UIManager:close(self.file_dialog) UIManager:show(ConfirmBox:new{ text = _("Are you sure that you want to compact cache database?\n(This may take a while.)"), ok_text = _("Compact database"), ok_callback = function() local InfoMessage = require("ui/widget/infomessage") local msg = InfoMessage:new{ text = _("Compacting cache database…") } UIManager:show(msg) UIManager:nextTick(function() local summary = BookInfoManager:compactDb() UIManager:close(msg) UIManager:show( InfoMessage:new{ text = summary } ) end) end }) end, }, { text = _("Delete cache database"), callback = function() local ConfirmBox = require("ui/widget/confirmbox") UIManager:close(self.file_dialog) UIManager:show(ConfirmBox:new{ text = _("Are you sure that you want to delete cover and metadata cache?\n(This will also reset your display mode settings.)"), ok_text = _("Purge"), ok_callback = function() BookInfoManager:deleteDb() end }) end, }, }, }, }, } -- Finally, insert the generic items at end of "Other settings" submenu local sub_item_table = menu_items.filemanager_display_mode.sub_item_table local generic_items_target = sub_item_table[#sub_item_table-1].sub_item_table -- second to last for _, item in pairs(generic_items) do table.insert(generic_items_target, item) end end function CoverBrowser:refreshFileManagerInstance(cleanup, post_init) local FileManager = require("apps/filemanager/filemanager") local fm = FileManager.instance if fm then local fc = fm.file_chooser if cleanup then -- clean instance properties we may have set if fc.onFileHold_orig then -- remove our onFileHold that extended file_dialog with new buttons fc.onFileHold = fc.onFileHold_orig fc.onFileHold_orig = nil fc.onFileHold_ours = nil end end if filemanager_display_mode then if post_init then -- FileBrowser was initialized in classic mode, but we changed -- display mode: items per page may have changed, and we want -- to re-position on the focused_file fc:_recalculateDimen() fc:changeToPath(fc.path, fc.prev_focused_path) else fc:updateItems() end else -- classic file_chooser needs this for a full redraw fc:refreshPath() end end end function CoverBrowser:setupFileManagerDisplayMode(display_mode) if not DISPLAY_MODES[display_mode] then display_mode = nil -- unknow mode, fallback to classic end if init_done and display_mode == filemanager_display_mode then -- no change return end if init_done then -- save new mode in db BookInfoManager:saveSetting("filemanager_display_mode", display_mode) end -- remember current mode in module variable filemanager_display_mode = display_mode logger.dbg("CoverBrowser: setting FileManager display mode to:", display_mode or "classic") if not init_done and not display_mode then return -- starting in classic mode, nothing to patch end if not display_mode then -- classic mode -- Put back original methods FileChooser.updateItems = _FileChooser_updateItems_orig FileChooser.onCloseWidget = _FileChooser_onCloseWidget_orig FileChooser.onSwipe = _FileChooser_onSwipe_orig FileChooser._recalculateDimen = _FileChooser__recalculateDimen_orig -- Also clean-up what we added, even if it does not bother original code FileChooser._updateItemsBuildUI = nil FileChooser._do_cover_images = nil FileChooser._do_filename_only = nil FileChooser._do_hint_opened = nil self:refreshFileManagerInstance(true) return end -- In both mosaic and list modes, replace original methods with those from -- our generic CoverMenu local CoverMenu = require("covermenu") FileChooser.updateItems = CoverMenu.updateItems FileChooser.onCloseWidget = CoverMenu.onCloseWidget FileChooser.onSwipe = CoverMenu.onSwipe if display_mode == "mosaic_image" or display_mode == "mosaic_text" then -- mosaic mode -- Replace some other original methods with those from our MosaicMenu local MosaicMenu = require("mosaicmenu") FileChooser._recalculateDimen = MosaicMenu._recalculateDimen FileChooser._updateItemsBuildUI = MosaicMenu._updateItemsBuildUI -- Set MosaicMenu behaviour: FileChooser._do_cover_images = display_mode ~= "mosaic_text" FileChooser._do_hint_opened = true -- dogear at bottom -- One could override default 3x3 grid here (put that as settings ?) -- FileChooser.nb_cols_portrait = 4 -- FileChooser.nb_rows_portrait = 4 -- FileChooser.nb_cols_landscape = 6 -- FileChooser.nb_rows_landscape = 3 elseif display_mode == "list_image_meta" or display_mode == "list_only_meta" or display_mode == "list_image_filename" then -- list modes -- Replace some other original methods with those from our ListMenu local ListMenu = require("listmenu") FileChooser._recalculateDimen = ListMenu._recalculateDimen FileChooser._updateItemsBuildUI = ListMenu._updateItemsBuildUI -- Set ListMenu behaviour: FileChooser._do_cover_images = display_mode ~= "list_only_meta" FileChooser._do_filename_only = display_mode == "list_image_filename" FileChooser._do_hint_opened = true -- dogear at bottom end if init_done then self:refreshFileManagerInstance() else -- If KOReader has started directly to FileManager, the FileManager -- instance is being init()'ed and there is no FileManager.instance yet, -- but there'll be one at next tick. UIManager:nextTick(function() self:refreshFileManagerInstance(false, true) end) end end local function _FileManagerHistory_updateItemTable(self) -- 'self' here is the single FileManagerHistory instance -- FileManagerHistory has just created a new instance of Menu as 'hist_menu' -- at each display of History. Soon after instantiation, this method -- is called. The first time it is called, we replace some methods. local display_mode = self.display_mode local hist_menu = self.hist_menu if not hist_menu._coverbrowser_overridden then hist_menu._coverbrowser_overridden = true -- In both mosaic and list modes, replace original methods with those from -- our generic CoverMenu local CoverMenu = require("covermenu") hist_menu.updateItems = CoverMenu.updateItems hist_menu.onCloseWidget = CoverMenu.onCloseWidget hist_menu.onSwipe = CoverMenu.onSwipe -- Also replace original onMenuHold (it will use original method, so remember it) hist_menu.onMenuHold_orig = hist_menu.onMenuHold hist_menu.onMenuHold = CoverMenu.onHistoryMenuHold if display_mode == "mosaic_image" or display_mode == "mosaic_text" then -- mosaic mode -- Replace some other original methods with those from our MosaicMenu local MosaicMenu = require("mosaicmenu") hist_menu._recalculateDimen = MosaicMenu._recalculateDimen hist_menu._updateItemsBuildUI = MosaicMenu._updateItemsBuildUI -- Set MosaicMenu behaviour: hist_menu._do_cover_images = display_mode ~= "mosaic_text" -- no need for do_hint_opened with History elseif display_mode == "list_image_meta" or display_mode == "list_only_meta" or display_mode == "list_image_filename" then -- list modes -- Replace some other original methods with those from our ListMenu local ListMenu = require("listmenu") hist_menu._recalculateDimen = ListMenu._recalculateDimen hist_menu._updateItemsBuildUI = ListMenu._updateItemsBuildUI -- Set ListMenu behaviour: hist_menu._do_cover_images = display_mode ~= "list_only_meta" hist_menu._do_filename_only = display_mode == "list_image_filename" -- no need for do_hint_opened with History end hist_menu._do_hint_opened = BookInfoManager:getSetting("history_hint_opened") end -- And do now what the original does _FileManagerHistory_updateItemTable_orig(self) end function CoverBrowser:setupHistoryDisplayMode(display_mode) if not DISPLAY_MODES[display_mode] then display_mode = nil -- unknow mode, fallback to classic end if init_done and display_mode == history_display_mode then -- no change return end if init_done then -- save new mode in db BookInfoManager:saveSetting("history_display_mode", display_mode) end -- remember current mode in module variable history_display_mode = display_mode logger.dbg("CoverBrowser: setting History display mode to:", display_mode or "classic") if not init_done and not display_mode then return -- starting in classic mode, nothing to patch end -- We only need to replace one FileManagerHistory method if not display_mode then -- classic mode -- Put back original methods FileManagerHistory.updateItemTable = _FileManagerHistory_updateItemTable_orig FileManagerHistory.display_mode = nil else -- Replace original method with the one defined above FileManagerHistory.updateItemTable = _FileManagerHistory_updateItemTable -- And let it know which display_mode we should use FileManagerHistory.display_mode = display_mode end end return CoverBrowser
agpl-3.0
cdettmering/fancyland
math/BoundingBox.lua
2
1131
--- BoundingBox --- -- Setup local access local Point = require(MATHPATH .. 'Point') local BoundingBox = {} local BoundingBox_mt = {} BoundingBox_mt.__index = BoundingBox function BoundingBox:new(min, max) local bb = {} bb._min = min or Point:new() bb._max = max or Point:new() return setmetatable(bb, BoundingBox_mt) end function BoundingBox.fromShape(shape) local pts = shape:points() if #pts <= 0 then return BoudningBox:new() end local min = pts[1] local max = pts[1] for _, pt in ipairs(pts) do if pt <= min then min = pt end if pt >= max then max = pt end end return BoundingBox:new(min, max) end function BoundingBox:min() return self._min end function BoundingBox:max() return self._max end function BoundingBox:height() return self:max().y - self:min().y end function BoundingBox:width() return self:max().x - self:min().x end function BoundingBox:center() local x = self:width() / 2 local y = self:height() / 2 return self:min() + Point:new(x, y) end return BoundingBox
gpl-3.0
Pulse-Eight/drivers
Control4/sky_q_ip_pulse-eight/lib/c4_object.lua
9
5060
--[[============================================================================= c4_object Class Copyright 2015 Control4 Corporation. All Rights Reserved. ===============================================================================]] function inheritsFrom( baseClass ) local new_class = {} local class_mt = { __index = new_class } function new_class:create(...) local newinst = {} setmetatable( newinst, class_mt ) -- Call the constructor when we create this class if newinst.construct then -- Allow returning a different obj than self. This allows for readonly tables etc... newinst = newinst:construct(...) or newinst end return newinst end if nil ~= baseClass then setmetatable( new_class, { __index = baseClass } ) end --[[============================================================================= Implementation of additional OO properties starts here ===============================================================================]] -- Return the class object of the instance function new_class:class() return new_class end --[[============================================================================= Return the super class object of the instance. Note Calling methods on the base class itself will modify the base table's static properties. In order to have call the base class' methods and have them modify the current object use super() or superAsSelf(). ===============================================================================]] function new_class:superClass() return baseClass end --[[============================================================================= Returns a table that allows calling of the base class's method while maintaining the objects state as the modified state of the base class' methods. For example consider the following statements (order matters): -- The child sees the parents property if the child hasn't overriden the property obj:superClass().id = "parent" obj.id == "parent" -- true -- Setting the property on the child overrides (hides) the parents property obj.id = "child" obj.id == "child" -- true -- The super() method pass obj:super().id == "parent" -- true obj:super().id = "child" obj:super().id == "parent" -- still true obj.id == "child" -- still true ===============================================================================]] function new_class:super() local holder = {} holder.child = self holder.parent = baseClass local mt = {} mt.__index = function(table, index) if table.parent[index] then return table.parent[index] else return table.child[index] end end -- Only set the new values to the child. mt.__newindex = function(table, key, value) table.child[key] = value end mt.__tostring = function(table) return tostring(table.child) end setmetatable(holder, mt) return holder end new_class.new = new_class.create --[[============================================================================= Return true if the caller is an instance of theClass ===============================================================================]] function new_class:isa( theClass ) local b_isa = false local cur_class = new_class while ( nil ~= cur_class ) and ( false == b_isa ) do if cur_class == theClass then b_isa = true else cur_class = cur_class:superClass() end end return b_isa end return new_class end --[[============================================================================= Inheritance unit tests ===============================================================================]] function __test_inheritance() local b = inheritsFrom(nil) b.construct = function(self, msg) self._msg = msg end local t = inheritsFrom(b) t.construct = function(self, msg) self:super():construct(msg) end t1 = t:new("t1") t2 = t:new("t2") assert(t1._msg == "t1", "t1 message is not equal to 't1' it''s: " .. t1._msg) assert(t2._msg == "t2", "t2 message is not equal to 't2' it''s: " .. t2._msg) assert(tostring(t1:super()) == tostring(t1), "tostrings don't match"); assert(t1:superClass() == b, "superClass and baseClass should be the same. They are not.") t1:superClass().id = "parent" assert(t1.id == "parent", "obect''s super class has invalid property value: ", t1.id) -- Setting the property on the child overrides (hides) the parents property t1.id = "child" assert(t1.id == "child", "object instance variable has invalid property value: " .. t1.id) -- The super() method maintains the self pointer to the child and not to the base assert(t1:super().id == "parent", "superAsSelf found invalid value for base class variable") t1:super().id = "child1" assert(t1:super().id == "parent", "Setting of instance variable hid base classes variable from itself"); assert(t1.id == "child1", "Settings of instance variable did not change child instance variable") end
apache-2.0
fastmailops/prosody
util/sasl/scram.lua
4
9503
-- sasl.lua v0.4 -- Copyright (C) 2008-2010 Tobias Markmann -- -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -- * Neither the name of Tobias Markmann nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. local s_match = string.match; local type = type local string = string local base64 = require "util.encodings".base64; local hmac_sha1 = require "util.hashes".hmac_sha1; local sha1 = require "util.hashes".sha1; local Hi = require "util.hashes".scram_Hi_sha1; local generate_uuid = require "util.uuid".generate; local saslprep = require "util.encodings".stringprep.saslprep; local nodeprep = require "util.encodings".stringprep.nodeprep; local log = require "util.logger".init("sasl"); local t_concat = table.concat; local char = string.char; local byte = string.byte; module "sasl.scram" --========================= --SASL SCRAM-SHA-1 according to RFC 5802 --[[ Supported Authentication Backends scram_{MECH}: -- MECH being a standard hash name (like those at IANA's hash registry) with '-' replaced with '_' function(username, realm) return stored_key, server_key, iteration_count, salt, state; end ]] local default_i = 4096 local function bp( b ) local result = "" for i=1, b:len() do result = result.."\\"..b:byte(i) end return result end local xor_map = {0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;1;0;3;2;5;4;7;6;9;8;11;10;13;12;15;14;2;3;0;1;6;7;4;5;10;11;8;9;14;15;12;13;3;2;1;0;7;6;5;4;11;10;9;8;15;14;13;12;4;5;6;7;0;1;2;3;12;13;14;15;8;9;10;11;5;4;7;6;1;0;3;2;13;12;15;14;9;8;11;10;6;7;4;5;2;3;0;1;14;15;12;13;10;11;8;9;7;6;5;4;3;2;1;0;15;14;13;12;11;10;9;8;8;9;10;11;12;13;14;15;0;1;2;3;4;5;6;7;9;8;11;10;13;12;15;14;1;0;3;2;5;4;7;6;10;11;8;9;14;15;12;13;2;3;0;1;6;7;4;5;11;10;9;8;15;14;13;12;3;2;1;0;7;6;5;4;12;13;14;15;8;9;10;11;4;5;6;7;0;1;2;3;13;12;15;14;9;8;11;10;5;4;7;6;1;0;3;2;14;15;12;13;10;11;8;9;6;7;4;5;2;3;0;1;15;14;13;12;11;10;9;8;7;6;5;4;3;2;1;0;}; local result = {}; local function binaryXOR( a, b ) for i=1, #a do local x, y = byte(a, i), byte(b, i); local lowx, lowy = x % 16, y % 16; local hix, hiy = (x - lowx) / 16, (y - lowy) / 16; local lowr, hir = xor_map[lowx * 16 + lowy + 1], xor_map[hix * 16 + hiy + 1]; local r = hir * 16 + lowr; result[i] = char(r) end return t_concat(result); end local function validate_username(username, _nodeprep) -- check for forbidden char sequences for eq in username:gmatch("=(.?.?)") do if eq ~= "2C" and eq ~= "3D" then return false end end -- replace =2C with , and =3D with = username = username:gsub("=2C", ","); username = username:gsub("=3D", "="); -- apply SASLprep username = saslprep(username); if username and _nodeprep ~= false then username = (_nodeprep or nodeprep)(username); end return username and #username>0 and username; end local function hashprep(hashname) return hashname:lower():gsub("-", "_"); end function getAuthenticationDatabaseSHA1(password, salt, iteration_count) if type(password) ~= "string" or type(salt) ~= "string" or type(iteration_count) ~= "number" then return false, "inappropriate argument types" end if iteration_count < 4096 then log("warn", "Iteration count < 4096 which is the suggested minimum according to RFC 5802.") end local salted_password = Hi(password, salt, iteration_count); local stored_key = sha1(hmac_sha1(salted_password, "Client Key")) local server_key = hmac_sha1(salted_password, "Server Key"); return true, stored_key, server_key end local function scram_gen(hash_name, H_f, HMAC_f) local function scram_hash(self, message) if not self.state then self["state"] = {} end if type(message) ~= "string" or #message == 0 then return "failure", "malformed-request" end if not self.state.name then -- we are processing client_first_message local client_first_message = message; -- TODO: fail if authzid is provided, since we don't support them yet self.state["client_first_message"] = client_first_message; self.state["gs2_cbind_flag"], self.state["authzid"], self.state["name"], self.state["clientnonce"] = client_first_message:match("^(%a),(.*),n=(.*),r=([^,]*).*"); -- we don't do any channel binding yet if self.state.gs2_cbind_flag ~= "n" and self.state.gs2_cbind_flag ~= "y" then return "failure", "malformed-request"; end if not self.state.name or not self.state.clientnonce then return "failure", "malformed-request", "Channel binding isn't support at this time."; end self.state.name = validate_username(self.state.name, self.profile.nodeprep); if not self.state.name then log("debug", "Username violates either SASLprep or contains forbidden character sequences.") return "failure", "malformed-request", "Invalid username."; end self.state["servernonce"] = generate_uuid(); -- retreive credentials if self.profile.plain then local password, state = self.profile.plain(self, self.state.name, self.realm) if state == nil then return "failure", "not-authorized" elseif state == false then return "failure", "account-disabled" end password = saslprep(password); if not password then log("debug", "Password violates SASLprep."); return "failure", "not-authorized", "Invalid password." end self.state.salt = generate_uuid(); self.state.iteration_count = default_i; local succ = false; succ, self.state.stored_key, self.state.server_key = getAuthenticationDatabaseSHA1(password, self.state.salt, default_i, self.state.iteration_count); if not succ then log("error", "Generating authentication database failed. Reason: %s", self.state.stored_key); return "failure", "temporary-auth-failure"; end elseif self.profile["scram_"..hashprep(hash_name)] then local stored_key, server_key, iteration_count, salt, state = self.profile["scram_"..hashprep(hash_name)](self, self.state.name, self.realm); if state == nil then return "failure", "not-authorized" elseif state == false then return "failure", "account-disabled" end self.state.stored_key = stored_key; self.state.server_key = server_key; self.state.iteration_count = iteration_count; self.state.salt = salt end local server_first_message = "r="..self.state.clientnonce..self.state.servernonce..",s="..base64.encode(self.state.salt)..",i="..self.state.iteration_count; self.state["server_first_message"] = server_first_message; return "challenge", server_first_message else -- we are processing client_final_message local client_final_message = message; self.state["channelbinding"], self.state["nonce"], self.state["proof"] = client_final_message:match("^c=(.*),r=(.*),.*p=(.*)"); if not self.state.proof or not self.state.nonce or not self.state.channelbinding then return "failure", "malformed-request", "Missing an attribute(p, r or c) in SASL message."; end if self.state.nonce ~= self.state.clientnonce..self.state.servernonce then return "failure", "malformed-request", "Wrong nonce in client-final-message."; end local ServerKey = self.state.server_key; local StoredKey = self.state.stored_key; local AuthMessage = "n=" .. s_match(self.state.client_first_message,"n=(.+)") .. "," .. self.state.server_first_message .. "," .. s_match(client_final_message, "(.+),p=.+") local ClientSignature = HMAC_f(StoredKey, AuthMessage) local ClientKey = binaryXOR(ClientSignature, base64.decode(self.state.proof)) local ServerSignature = HMAC_f(ServerKey, AuthMessage) if StoredKey == H_f(ClientKey) then local server_final_message = "v="..base64.encode(ServerSignature); self["username"] = self.state.name; return "success", server_final_message; else return "failure", "not-authorized", "The response provided by the client doesn't match the one we calculated."; end end end return scram_hash; end function init(registerMechanism) local function registerSCRAMMechanism(hash_name, hash, hmac_hash) registerMechanism("SCRAM-"..hash_name, {"plain", "scram_"..(hashprep(hash_name))}, scram_gen(hash_name:lower(), hash, hmac_hash)); end registerSCRAMMechanism("SHA-1", sha1, hmac_sha1); end return _M;
mit
apletnev/koreader
frontend/ui/widget/timewidget.lua
3
6213
local Blitbuffer = require("ffi/blitbuffer") local ButtonTable = require("ui/widget/buttontable") local CenterContainer = require("ui/widget/container/centercontainer") local CloseButton = require("ui/widget/closebutton") local Device = require("device") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local Font = require("ui/font") local HorizontalGroup = require("ui/widget/horizontalgroup") local InputContainer = require("ui/widget/container/inputcontainer") local LineWidget = require("ui/widget/linewidget") local OverlapGroup = require("ui/widget/overlapgroup") local NumberPickerWidget = require("ui/widget/numberpickerwidget") local Size = require("ui/size") local TextBoxWidget = require("ui/widget/textboxwidget") local TextWidget = require("ui/widget/textwidget") local UIManager = require("ui/uimanager") local VerticalGroup = require("ui/widget/verticalgroup") local WidgetContainer = require("ui/widget/container/widgetcontainer") local _ = require("gettext") local Screen = Device.screen local TimeWidget = InputContainer:new{ title_face = Font:getFace("x_smalltfont"), width = nil, height = nil, hour = 0, hour_max = 23, min = 0, ok_text = _("OK"), cancel_text = _("Cancel"), } function TimeWidget:init() self.medium_font_face = Font:getFace("ffont") self.light_bar = {} self.screen_width = Screen:getWidth() self.screen_height = Screen:getHeight() self.width = self.screen_width * 0.95 if Device:hasKeys() then self.key_events = { Close = { {"Back"}, doc = "close time widget" } } end if Device:isTouchDevice() then self.ges_events = { TapClose = { GestureRange:new{ ges = "tap", range = Geom:new{ w = self.screen_width, h = self.screen_height, } }, }, } end self:update() end function TimeWidget:update() local hour_widget = NumberPickerWidget:new{ show_parent = self, width = self.screen_width * 0.2, value = self.hour, value_min = 0, value_max = self.hour_max, value_step = 1, value_hold_step = 4, } local min_widget = NumberPickerWidget:new{ show_parent = self, width = self.screen_width * 0.2, value = self.min, value_min = 0, value_max = 59, value_step = 1, value_hold_step = 10, } local colon_space = TextBoxWidget:new{ text = ":", alignment = "center", face = self.title_face, bold = true, width = self.screen_width * 0.2, } local time_group = HorizontalGroup:new{ align = "center", hour_widget, colon_space, min_widget, } local time_title = FrameContainer:new{ padding = Size.padding.default, margin = Size.margin.title, bordersize = 0, TextWidget:new{ text = self.title_text, face = self.title_face, bold = true, width = self.screen_width * 0.95, }, } local time_line = LineWidget:new{ dimen = Geom:new{ w = self.width, h = Size.line.thick, } } local time_bar = OverlapGroup:new{ dimen = { w = self.width, h = time_title:getSize().h }, time_title, CloseButton:new{ window = self, padding_top = Size.margin.title, }, } local buttons = { { { text = self.cancel_text, callback = function() self:onClose() end, }, { text = self.ok_text, callback = function() if self.callback then self.hour = hour_widget:getValue() self.min = min_widget:getValue() self:callback(self) end self:onClose() end, }, } } local ok_cancel_buttons = ButtonTable:new{ width = self.width - 2*Size.padding.default, buttons = buttons, zero_sep = true, show_parent = self, } self.time_frame = FrameContainer:new{ radius = Size.radius.window, padding = 0, margin = 0, background = Blitbuffer.COLOR_WHITE, VerticalGroup:new{ align = "left", time_bar, time_line, CenterContainer:new{ dimen = Geom:new{ w = self.screen_width * 0.95, h = time_group:getSize().h * 1.2, }, time_group }, CenterContainer:new{ dimen = Geom:new{ w = self.width, h = ok_cancel_buttons:getSize().h, }, ok_cancel_buttons } } } self[1] = WidgetContainer:new{ align = "center", dimen = Geom:new{ x = 0, y = 0, w = self.screen_width, h = self.screen_height, }, FrameContainer:new{ bordersize = 0, self.time_frame, } } UIManager:setDirty(self, function() return "ui", self.time_frame.dimen end) end function TimeWidget:onCloseWidget() UIManager:setDirty(nil, function() return "partial", self.time_frame.dimen end) return true end function TimeWidget:onShow() UIManager:setDirty(self, function() return "ui", self.time_frame.dimen end) return true end function TimeWidget:onAnyKeyPressed() UIManager:close(self) return true end function TimeWidget:onTapClose(arg, ges_ev) if ges_ev.pos:notIntersectWith(self.time_frame.dimen) then self:onClose() end return true end function TimeWidget:onClose() UIManager:close(self) return true end return TimeWidget
agpl-3.0
kitala1/darkstar
scripts/zones/Den_of_Rancor/TextIDs.lua
3
1067
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6382; -- Obtained: <item> GIL_OBTAINED = 6383; -- Obtained <number> gil KEYITEM_OBTAINED = 6385; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7223; -- You can't fish here -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7325; -- You unlock the chest! CHEST_FAIL = 7326; -- Fails to open the chest. CHEST_TRAP = 7327; -- The chest was trapped! CHEST_WEAK = 7328; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7329; -- The chest was a mimic! CHEST_MOOGLE = 7330; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7331; -- The chest was but an illusion... CHEST_LOCKED = 7332; -- The chest appears to be locked. -- Other dialog LANTERN_OFFSET = 7195; -- The grating will not budge. -- conquest Base CONQUEST_BASE = 7036; -- Tallying conquest results...
gpl-3.0
apletnev/koreader
plugins/keepalive.koplugin/main.lua
4
2214
local ConfirmBox = require("ui/widget/confirmbox") local Device = require("device") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local _ = require("gettext") local menuItem = { text = _("Keep alive"), checked = false, } local disable local enable local function showConfirmBox() UIManager:show(ConfirmBox:new{ text = _("The system won't sleep while this message is showing.\n\nPress \"Stay alive\" if you prefer to keep the system on even after closing this notification. *This will drain the battery*.\n\nIf KOReader terminates before \"Close\" is pressed, please start and close the KeepAlive plugin again to ensure settings are reset."), cancel_text = _("Close"), cancel_callback = function() disable() menuItem.checked =false end, ok_text = _("Stay alive"), ok_callback = function() menuItem.checked = true end, }) end if Device:isKobo() then local PluginShare = require("pluginshare") enable = function() PluginShare.pause_auto_suspend = true end disable = function() PluginShare.pause_auto_suspend = false end elseif Device:isKindle() then disable = function() os.execute("lipc-set-prop com.lab126.powerd preventScreenSaver 0") end enable = function() os.execute("lipc-set-prop com.lab126.powerd preventScreenSaver 1") end elseif Device:isSDL() then local InfoMessage = require("ui/widget/infomessage") disable = function() UIManager:show(InfoMessage:new{ text = _("This is a dummy implementation of 'disable' function.") }) end enable = function() UIManager:show(InfoMessage:new{ text = _("This is a dummy implementation of 'enable' function.") }) end else return { disabled = true, } end menuItem.callback = function() enable() showConfirmBox() end local KeepAlive = WidgetContainer:new{ name = "keepalive", } function KeepAlive:init() self.ui.menu:registerToMainMenu(self) end function KeepAlive:addToMainMenu(menu_items) menu_items.keep_alive = menuItem end return KeepAlive
agpl-3.0
fqrouter/luci
libs/web/luasrc/cbi/datatypes.lua
16
6003
--[[ LuCI - Configuration Bind Interface - Datatype Tests (c) 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local ip = require "luci.ip" local math = require "math" local util = require "luci.util" local tonumber, tostring, type, unpack, select = tonumber, tostring, type, unpack, select module "luci.cbi.datatypes" _M['or'] = function(v, ...) local i for i = 1, select('#', ...), 2 do local f = select(i, ...) local a = select(i+1, ...) if type(f) ~= "function" then if f == v then return true end i = i - 1 elseif f(v, unpack(a)) then return true end end return false end _M['and'] = function(v, ...) local i for i = 1, select('#', ...), 2 do local f = select(i, ...) local a = select(i+1, ...) if type(f) ~= "function" then if f ~= v then return false end i = i - 1 elseif not f(v, unpack(a)) then return false end end return true end function neg(v, ...) return _M['or'](v:gsub("^%s*!%s*", ""), ...) end function list(v, subvalidator, subargs) if type(subvalidator) ~= "function" then return false end local token for token in v:gmatch("%S+") do if not subvalidator(token, unpack(subargs)) then return false end end return true end function bool(val) if val == "1" or val == "yes" or val == "on" or val == "true" then return true elseif val == "0" or val == "no" or val == "off" or val == "false" then return true elseif val == "" or val == nil then return true end return false end function uinteger(val) local n = tonumber(val) if n ~= nil and math.floor(n) == n and n >= 0 then return true end return false end function integer(val) local n = tonumber(val) if n ~= nil and math.floor(n) == n then return true end return false end function ufloat(val) local n = tonumber(val) return ( n ~= nil and n >= 0 ) end function float(val) return ( tonumber(val) ~= nil ) end function ipaddr(val) return ip4addr(val) or ip6addr(val) end function ip4addr(val) if val then return ip.IPv4(val) and true or false end return false end function ip4prefix(val) val = tonumber(val) return ( val and val >= 0 and val <= 32 ) end function ip6addr(val) if val then return ip.IPv6(val) and true or false end return false end function ip6prefix(val) val = tonumber(val) return ( val and val >= 0 and val <= 128 ) end function port(val) val = tonumber(val) return ( val and val >= 0 and val <= 65535 ) end function portrange(val) local p1, p2 = val:match("^(%d+)%-(%d+)$") if p1 and p2 and port(p1) and port(p2) then return true else return port(val) end end function macaddr(val) if val and val:match( "^[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+:" .. "[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+$" ) then local parts = util.split( val, ":" ) for i = 1,6 do parts[i] = tonumber( parts[i], 16 ) if parts[i] < 0 or parts[i] > 255 then return false end end return true end return false end function hostname(val) if val and (#val < 254) and ( val:match("^[a-zA-Z_]+$") or (val:match("^[a-zA-Z0-9_][a-zA-Z0-9_%-%.]*[a-zA-Z0-9]$") and val:match("[^0-9%.]")) ) then return true end return false end function host(val) return hostname(val) or ipaddr(val) end function network(val) return uciname(val) or host(val) end function wpakey(val) if #val == 64 then return (val:match("^[a-fA-F0-9]+$") ~= nil) else return (#val >= 8) and (#val <= 63) end end function wepkey(val) if val:sub(1, 2) == "s:" then val = val:sub(3) end if (#val == 10) or (#val == 26) then return (val:match("^[a-fA-F0-9]+$") ~= nil) else return (#val == 5) or (#val == 13) end end function string(val) return true -- Everything qualifies as valid string end function directory( val, seen ) local s = fs.stat(val) seen = seen or { } if s and not seen[s.ino] then seen[s.ino] = true if s.type == "dir" then return true elseif s.type == "lnk" then return directory( fs.readlink(val), seen ) end end return false end function file( val, seen ) local s = fs.stat(val) seen = seen or { } if s and not seen[s.ino] then seen[s.ino] = true if s.type == "reg" then return true elseif s.type == "lnk" then return file( fs.readlink(val), seen ) end end return false end function device( val, seen ) local s = fs.stat(val) seen = seen or { } if s and not seen[s.ino] then seen[s.ino] = true if s.type == "chr" or s.type == "blk" then return true elseif s.type == "lnk" then return device( fs.readlink(val), seen ) end end return false end function uciname(val) return (val:match("^[a-zA-Z0-9_]+$") ~= nil) end function range(val, min, max) val = tonumber(val) min = tonumber(min) max = tonumber(max) if val ~= nil and min ~= nil and max ~= nil then return ((val >= min) and (val <= max)) end return false end function min(val, min) val = tonumber(val) min = tonumber(min) if val ~= nil and min ~= nil then return (val >= min) end return false end function max(val, max) val = tonumber(val) max = tonumber(max) if val ~= nil and max ~= nil then return (val <= max) end return false end function rangelength(val, min, max) val = tostring(val) min = tonumber(min) max = tonumber(max) if val ~= nil and min ~= nil and max ~= nil then return ((#val >= min) and (#val <= max)) end return false end function minlength(val, min) val = tostring(val) min = tonumber(min) if val ~= nil and min ~= nil then return (#val >= min) end return false end function maxlength(val, max) val = tostring(val) max = tonumber(max) if val ~= nil and max ~= nil then return (#val <= max) end return false end function phonedigit(val) return (val:match("^[0-9\*#]+$") ~= nil) end
apache-2.0
kitala1/darkstar
scripts/globals/items/hellsteak_+1.lua
35
1728
----------------------------------------- -- ID: 5610 -- Item: hellsteak_+1 -- Food Effect: 240Min, All Races ----------------------------------------- -- Health 20 -- Strength 6 -- Intelligence -2 -- Health Regen While Healing 2 -- Attack % 19 -- Ranged ATT % 19 -- Dragon Killer 5 -- Demon Killer 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5610); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_STR, 6); target:addMod(MOD_INT, -2); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_ATTP, 19); target:addMod(MOD_RATTP, 19); target:addMod(MOD_DRAGON_KILLER, 5); target:addMod(MOD_DEMON_KILLER, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_STR, 6); target:delMod(MOD_INT, -2); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_ATTP, 19); target:delMod(MOD_RATTP, 19); target:delMod(MOD_DRAGON_KILLER, 5); target:delMod(MOD_DEMON_KILLER, 5); end;
gpl-3.0
apletnev/koreader
reader.lua
2
7239
#!./luajit io.stdout:write([[ --------------------------------------------- launching... _ _____ ____ _ | |/ / _ \| _ \ ___ __ _ __| | ___ _ __ | ' / | | | |_) / _ \/ _` |/ _` |/ _ \ '__| | . \ |_| | _ < __/ (_| | (_| | __/ | |_|\_\___/|_| \_\___|\__,_|\__,_|\___|_| [*] Current time: ]], os.date("%x-%X"), "\n\n") io.stdout:flush() -- load default settings require("defaults") local DataStorage = require("datastorage") pcall(dofile, DataStorage:getDataDir() .. "/defaults.persistent.lua") require("setupkoenv") -- read settings and check for language override -- has to be done before requiring other files because -- they might call gettext on load G_reader_settings = require("luasettings"):open( DataStorage:getDataDir().."/settings.reader.lua") local lang_locale = G_reader_settings:readSetting("language") local _ = require("gettext") if lang_locale then _.changeLang(lang_locale) end -- option parsing: local longopts = { debug = "d", profile = "p", help = "h", } local function showusage() print("usage: ./reader.lua [OPTION] ... path") print("Read all the books on your E-Ink reader") print("") print("-d start in debug mode") print("-v debug in verbose mode") print("-p enable Lua code profiling") print("-h show this usage help") print("") print("If you give the name of a directory instead of a file path, a file") print("chooser will show up and let you select a file") print("") print("If you don't pass any path, the last viewed document will be opened") print("") print("This software is licensed under the AGPLv3.") print("See http://github.com/koreader/koreader for more info.") end -- should check DEBUG option in arg and turn on DEBUG before loading other -- modules, otherwise DEBUG in some modules may not be printed. local dbg = require("dbg") if G_reader_settings:readSetting("debug") then dbg:turnOn() end local Profiler = nil local ARGV = arg local argidx = 1 while argidx <= #ARGV do local arg = ARGV[argidx] argidx = argidx + 1 if arg == "--" then break end -- parse longopts if arg:sub(1,2) == "--" then local opt = longopts[arg:sub(3)] if opt ~= nil then arg = "-"..opt end end -- code for each option if arg == "-h" then return showusage() elseif arg == "-d" then dbg:turnOn() elseif arg == "-v" then dbg:setVerbose(true) elseif arg == "-p" then Profiler = require("jit.p") Profiler.start("la") else -- not a recognized option, should be a filename argidx = argidx - 1 break end end local ConfirmBox = require("ui/widget/confirmbox") local Device = require("device") local Font = require("ui/font") local QuickStart = require("ui/quickstart") local UIManager = require("ui/uimanager") local lfs = require("libs/libkoreader-lfs") local function retryLastFile() return ConfirmBox:new{ text = _("Cannot open last file.\nThis could be because it was deleted or because external storage is still being mounted.\nDo you want to retry?"), ok_callback = function() local last_file = G_reader_settings:readSetting("lastfile") if lfs.attributes(last_file, "mode") == "file" then local ReaderUI = require("apps/reader/readerui") UIManager:nextTick(function() ReaderUI:showReader(last_file) end) else UIManager:show(retryLastFile()) end end, } end -- read some global reader setting here: -- font local fontmap = G_reader_settings:readSetting("fontmap") if fontmap ~= nil then for k, v in pairs(fontmap) do Font.fontmap[k] = v end end -- last file local last_file = G_reader_settings:readSetting("lastfile") local start_with = G_reader_settings:readSetting("start_with") -- load last opened file local open_last = start_with == "last" if open_last and last_file and lfs.attributes(last_file, "mode") ~= "file" then UIManager:show(retryLastFile()) last_file = nil elseif not QuickStart:isShown() then open_last = true last_file = QuickStart:getQuickStart() end -- night mode if G_reader_settings:readSetting("night_mode") then Device.screen:toggleNightMode() end if Device:needsTouchScreenProbe() then Device:touchScreenProbe() end -- Inform once about color rendering on newly supported devices -- (there are some android devices that may not have a color screen, -- and we are not (yet?) able to guess that fact) if Device.hasColorScreen() and not G_reader_settings:has("color_rendering") then -- enable it to prevent further display of this message G_reader_settings:saveSetting("color_rendering", true) local InfoMessage = require("ui/widget/infomessage") UIManager:show(InfoMessage:new{ text = _("Documents will be rendered in color on this device.\nIf your device is grayscale, you can disable color rendering in the screen sub-menu for reduced memory usage."), }) end local exit_code if ARGV[argidx] and ARGV[argidx] ~= "" then local file if lfs.attributes(ARGV[argidx], "mode") == "file" then file = ARGV[argidx] elseif open_last and last_file then file = last_file end -- if file is given in command line argument or open last document is set -- true, the given file or the last file is opened in the reader if file then local ReaderUI = require("apps/reader/readerui") UIManager:nextTick(function() ReaderUI:showReader(file) end) -- we assume a directory is given in command line argument -- the filemanger will show the files in that path else local FileManager = require("apps/filemanager/filemanager") local home_dir = G_reader_settings:readSetting("home_dir") or ARGV[argidx] UIManager:nextTick(function() FileManager:showFiles(home_dir) end) -- always open history on top of filemanager so closing history -- doesn't result in exit if start_with == "history" then local FileManagerHistory = require("apps/filemanager/filemanagerhistory") UIManager:nextTick(function() FileManagerHistory:onShowHist(last_file) end) end end exit_code = UIManager:run() elseif last_file then local ReaderUI = require("apps/reader/readerui") UIManager:nextTick(function() ReaderUI:showReader(last_file) end) exit_code = UIManager:run() else return showusage() end local function exitReader() local ReaderActivityIndicator = require("apps/reader/modules/readeractivityindicator") -- Save any device settings before closing G_reader_settings Device:saveSettings() G_reader_settings:close() -- Close lipc handles ReaderActivityIndicator:coda() -- shutdown hardware abstraction Device:exit() if Profiler then Profiler.stop() end if type(exit_code) == "number" then os.exit(exit_code) else os.exit(0) end end exitReader()
agpl-3.0
fqrouter/luci
applications/luci-freifunk-widgets/luasrc/controller/freifunk/widgets.lua
78
1124
--[[ LuCI - Lua Configuration Interface Copyright 2012 Manuel Munz <freifunk at somakoma de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local require = require module "luci.controller.freifunk.widgets" function index() local page = node("admin", "freifunk", "widgets") page.target = cbi("freifunk/widgets/widgets_overview") page.title = _("Widgets") page.i18n = "widgets" page.order = 30 local page = node("admin", "freifunk", "widgets", "widget") page.target = cbi("freifunk/widgets/widget") page.leaf = true local page = node("freifunk", "search_redirect") page.target = call("search_redirect") page.leaf = true end function search_redirect() local dsp = require "luci.dispatcher" local http = require "luci.http" local engine = http.formvalue("engine") local searchterms = http.formvalue("searchterms") or "" if engine then http.redirect(engine .. searchterms) else http.redirect(dsp.build_url()) end end
apache-2.0
DangerCove/libquvi-scripts
share/lua/website/ted.lua
2
2376
-- libquvi-scripts -- Copyright (C) 2012 Toni Gundogdu <legatvs@gmail.com> -- Copyright (C) 2011 Bastien Nocera <hadess@hadess.net> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- local Ted = {} -- Utility functions unique to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "ted%.com" r.formats = "default|best" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/talks/.+$"}) return r end -- Query available formats. function query_formats(self) self.formats = "default" Ted.is_external(self, quvi.fetch(self.page_url)) return self end -- Parse video URL. function parse(self) self.host_id = "ted" local p = quvi.fetch(self.page_url) if Ted.is_external(self, p) then return self end self.id = p:match('ti:"(%d+)"') or error("no match: media ID") self.title = p:match('<title>(.-)%s+|') or error("no match: media title") self.thumbnail_url = p:match('rel="image_src" href="(.-)"') or '' self.url = {p:match('(http://download.-)"') or error("no match: media stream URL")} return self end -- -- Utility functions -- function Ted.is_external(self, page) -- Some of the videos are hosted elsewhere. self.redirect_url = page:match('name="movie"%s+value="(.-)"') or '' return #self.redirect_url > 0 end -- vim: set ts=4 sw=4 tw=72 expandtab:
lgpl-2.1
crabman77/minetest-minetestforfun-server
mods/factions/factions.lua
9
21536
------------------------------------------------------------------------------- -- factions Mod by Sapier -- -- License WTFPL -- --! @file factions.lua --! @brief factions core file containing datastorage --! @copyright Sapier --! @author Sapier --! @date 2013-05-08 -- -- Contact sapier a t gmx net ------------------------------------------------------------------------------- --read some basic information local factions_worldid = minetest.get_worldpath() --! @class factions --! @brief main class for factions factions = {} --! @brief runtime data factions.data = {} factions.data.factions = {} factions.data.objects = {} factions.dynamic_data = {} factions.dynamic_data.membertable = {} factions.print = function(text) print("Factions: " .. dump(text)) end factions.dbg_lvl1 = function() end --factions.print -- errors factions.dbg_lvl2 = function() end --factions.print -- non cyclic trace factions.dbg_lvl3 = function() end --factions.print -- cyclic trace ------------------------------------------------------------------------------- -- name: add_faction(name) -- --! @brief add a faction --! @memberof factions --! @public -- --! @param name of faction to add --! --! @return true/false (succesfully added faction or not) ------------------------------------------------------------------------------- function factions.add_faction(name) if factions.data.factions[name] == nil then factions.data.factions[name] = {} factions.data.factions[name].reputation = {} factions.data.factions[name].base_reputation = {} factions.data.factions[name].adminlist = {} factions.data.factions[name].invitations = {} factions.dynamic_data.membertable[name] = {} factions.save() return true end return false end ------------------------------------------------------------------------------- -- name: set_base_reputation(faction1,faction2,value) -- --! @brief set base reputation between two factions --! @memberof factions --! @public -- --! @param faction1 first faction --! @param faction2 second faction --! @param value value to use --! --! @return true/false (succesfully added faction or not) ------------------------------------------------------------------------------- function factions.set_base_reputation(faction1,faction2,value) if factions.data.factions[faction1] ~= nil and factions.data.factions[faction2] ~= nil then factions.data.factions[faction1].base_reputation[faction2] = value factions.data.factions[faction2].base_reputation[faction1] = value factions.save() return true end return false end ------------------------------------------------------------------------------- -- name: get_base_reputation(faction1,faction2) -- --! @brief get base reputation between two factions --! @memberof factions --! @public -- --! @param faction1 first faction --! @param faction2 second faction --! --! @return reputation/0 if none set ------------------------------------------------------------------------------- function factions.get_base_reputation(faction1,faction2) factions.dbg_lvl3("get_base_reputation: " .. faction1 .. "<-->" .. faction2) if factions.data.factions[faction1] ~= nil and factions.data.factions[faction2] ~= nil then if factions.data.factions[faction1].base_reputation[faction2] ~= nil then return factions.data.factions[faction1].base_reputation[faction2] end end return 0 end ------------------------------------------------------------------------------- -- name: set_description(name,description) -- --! @brief set description for a faction --! @memberof factions --! @public -- --! @param name of faction --! @param description text describing a faction --! --! @return true/false (succesfully set description) ------------------------------------------------------------------------------- function factions.set_description(name,description) if factions.data.factions[name] ~= nil then factions.data.factions[name].description = description factions.save() return true end return false end ------------------------------------------------------------------------------- -- name: get_description(name) -- --! @brief get description for a faction --! @memberof factions --! @public -- --! @param name of faction --! --! @return description or "" ------------------------------------------------------------------------------- function factions.get_description(name) if factions.data.factions[name] ~= nil and factions.data.factions[name].description ~= nil then return factions.data.factions[name].description end return "" end ------------------------------------------------------------------------------- -- name: exists(name) -- --! @brief check if a faction exists --! @memberof factions --! @public --! @param name name to check --! --! @return true/false ------------------------------------------------------------------------------- function factions.exists(name) for key,value in pairs(factions.data.factions) do if key == name then return true end end return false end ------------------------------------------------------------------------------- -- name: get_faction_list() -- --! @brief get list of factions --! @memberof factions --! @public --! --! @return list of factions ------------------------------------------------------------------------------- function factions.get_faction_list() local retval = {} for key,value in pairs(factions.data.factions) do table.insert(retval,key) end return retval end ------------------------------------------------------------------------------- -- name: delete_faction(name) -- --! @brief delete a faction --! @memberof factions --! @public -- --! @param name of faction to delete --! --! @return true/false (succesfully added faction or not) ------------------------------------------------------------------------------- function factions.delete_faction(name) factions.data.factions[name] = nil factions.save() if factions.data.factions[name] == nil then return true end return false end ------------------------------------------------------------------------------- -- name: member_add(name,object) -- --! @brief add an entity or player to a faction --! @memberof factions --! @public -- --! @param name of faction to add object to --! @param object to add to faction --! --! @return true/false (succesfully added faction or not) ------------------------------------------------------------------------------- function factions.member_add(name, object) local new_entry = {} new_entry.factions = {} if object.object ~= nil then object = object.object end if not factions.exists(name) then print("Unable to add to NON existant faction >" .. name .. "<") return false end new_entry.name,new_entry.temporary = factions.get_name(object) factions.dbg_lvl2("Adding name=" .. dump(new_entry.name) .. " to faction: " .. name ) if new_entry.name ~= nil then if factions.data.objects[new_entry.name] == nil then factions.data.objects[new_entry.name] = new_entry end if factions.data.objects[new_entry.name].factions[name] == nil then factions.data.objects[new_entry.name].factions[name] = true factions.dynamic_data.membertable[name][new_entry.name] = true factions.data.factions[name].invitations[new_entry.name] = nil factions.save() return true end end --return false if no valid object or already member return false end ------------------------------------------------------------------------------- -- name: member_invite(name,playername) -- --! @brief invite a player for joining a faction --! @memberof factions --! @public -- --! @param name of faction to add object to --! @param name of player to invite --! --! @return true/false (succesfully added invitation or not) ------------------------------------------------------------------------------- function factions.member_invite(name, playername) if factions.data.factions[name] ~= nil and factions.data.factions[name].invitations[playername] == nil then factions.data.factions[name].invitations[playername] = true factions.save() return true end --return false if not a valid faction or player already invited return false end ------------------------------------------------------------------------------- -- name: member_remove(name,object) -- --! @brief remove an entity or player to a faction --! @memberof factions --! @public -- --! @param name of faction to add object to --! @param object to add to faction --! --! @return true/false (succesfully added faction or not) ------------------------------------------------------------------------------- function factions.member_remove(name,object) local id,type = factions.get_name(object) factions.dbg_lvl2("removing name=" .. dump(id) .. " to faction: " .. name ) if id ~= nil and factions.data.objects[id] ~= nil and factions.data.objects[id].factions[name] ~= nil then factions.data.objects[id].factions[name] = nil factions.dynamic_data.membertable[name][id] = nil factions.save() return true end if id ~= nil and factions.data.factions[name].invitations[id] ~= nil then factions.data.factions[name].invitations[id] = nil factions.save() return true end return false end ------------------------------------------------------------------------------- -- name: set_admin(name,playername,value) -- --! @brief set admin priviles for a playername --! @memberof factions --! @public -- --! @param name of faction to add object to --! @param playername to change rights --! @param value true/false has or has not admin privileges --! --! @return true/false (succesfully changed privileges) ------------------------------------------------------------------------------- function factions.set_admin(name,playername,value) --mobf_assert_backtrace(type(playername) == "string") if factions.data.factions[name] ~= nil then if value then factions.data.factions[name].adminlist[playername] = true factions.save() return true else factions.data.factions[name].adminlist[playername] = nil factions.save() return true end else print("FACTIONS: no faction >" .. name .. "< found") end return false end ------------------------------------------------------------------------------- -- name: set_free(name,value) -- --! @brief set faction to be joinable by everyone --! @memberof factions --! @public -- --! @param name of faction to add object to --! @param value true/false has or has not admin privileges --! --! @return true/false (succesfully added faction or not) ------------------------------------------------------------------------------- function factions.set_free(name,value) if factions.data.factions[name] ~= nil then if value then if factions.data.factions[name].open == nil then factions.data.factions[name].open = true factions.save() return true else return false end else if factions.data.factions[name].open == nil then return false else factions.data.factions[name].open = nil factions.save() return true end end end return false end ------------------------------------------------------------------------------- -- name: is_free(name) -- --! @brief check if a fraction is free to join --! @memberof factions --! @public -- --! @param name of faction to add object to -- --! @return true/false (free or not) ------------------------------------------------------------------------------- function factions.is_free(name) if factions.data.factions[name] ~= nil and factions.data.factions[name].open then return true end return false end ------------------------------------------------------------------------------- -- name: is_admin(name,playername) -- --! @brief read admin privilege of player --! @memberof factions --! @public -- --! @param name of faction to check rights --! @param playername to change rights --! --! @return true/false (succesfully added faction or not) ------------------------------------------------------------------------------- function factions.is_admin(name,playername) if factions.data.factions[name] ~= nil and factions.data.factions[name].adminlist[playername] == true then return true end return false end ------------------------------------------------------------------------------- -- name: is_invited(name,playername) -- --! @brief read invitation status of player --! @memberof factions --! @public -- --! @param name of faction to check for invitation --! @param playername to change rights --! --! @return true/false (succesfully added faction or not) ------------------------------------------------------------------------------- function factions.is_invited(name,playername) if factions.data.factions[name] ~= nil and ( factions.data.factions[name].invitations[playername] == true or factions.data.factions[name].open == true) then return true end return false end ------------------------------------------------------------------------------- -- name: get_factions(object) -- --! @brief get list of factions for an object --! @memberof factions --! @public -- --! @param object to get list for --! --! @return list of factions ------------------------------------------------------------------------------- function factions.get_factions(object) local id,type = factions.get_name(object) local retval = {} if id ~= nil and factions.data.objects[id] ~= nil then for key,value in pairs(factions.data.objects[id].factions) do table.insert(retval,key) end end return retval end ------------------------------------------------------------------------------- -- name: is_member(name,object) -- --! @brief check if object is member of name --! @memberof factions --! @public -- --! @param name of faction to check --! @param object to check --! --! @return true/false ------------------------------------------------------------------------------- function factions.is_member(name,object) local retval = false local id,type = factions.get_name(object) if id ~= nil and factions.data.objects[id] ~= nil then for key,value in pairs(factions.data.objects[id].factions) do if key == name then retval = true break end end end return retval end ------------------------------------------------------------------------------- -- name: get_reputation(name,object) -- --! @brief get reputation of an object --! @memberof factions --! @public -- --! @param name name of faction to check for reputation --! @param object object to get reputation for --! --! @return number value -100 to 100 0 being neutral, -100 beeing enemy 100 friend ------------------------------------------------------------------------------- function factions.get_reputation(name,object) local id,type = factions.get_name(object) factions.dbg_lvl3("get_reputation: " .. name .. "<-->" .. dump(id)) if id ~= nil and factions.data.factions[name] ~= nil then factions.dbg_lvl3("get_reputation: object reputation: " .. dump(factions.data.factions[name].reputation[id])) if factions.data.factions[name].reputation[id] == nil then factions.data.factions[name].reputation[id] = factions.calc_base_reputation(name,object) end return factions.data.factions[name].reputation[id] else factions.dbg_lvl3("get_reputation: didn't find any factions for: " .. name) end return 0 end ------------------------------------------------------------------------------- -- name: modify_reputation(name,object,delta) -- --! @brief modify reputation of an object for a faction --! @memberof factions --! @public -- --! @param name name of faction to modify reputation --! @param object object to change reputation --! @param delta value to change reputation --! --! @return true/false ------------------------------------------------------------------------------- function factions.modify_reputation(name,object,delta) local id,type = factions.get_name(object) if factions.data.factions[name] ~= nil then if factions.data.factions[name].reputation[id] == nil then factions.data.factions[name].reputation[id] = factions.calc_base_reputation(name,object) end factions.data.factions[name].reputation[id] = factions.data.factions[name].reputation[id] + delta factions.save() return true end return false end ------------------------------------------------------------------------------- -- name: get_name(object) -- --! @brief get textual name of object --! @memberof factions --! @private -- --! @param object fetch name for this --! --! @return name or nil,is temporary element ------------------------------------------------------------------------------- function factions.get_name(object) if object == nil then return nil,true end if object.object ~= nil then object = object.object end if object:is_player() then return object:get_player_name(),false else local luaentity = object:get_luaentity() if luaentity ~= nil then return tostring(luaentity),true end end return nil,true end ------------------------------------------------------------------------------- -- name: calc_base_reputation(name,object) -- --! @brief calculate initial reputation of object within a faction --! @memberof factions --! @private -- --! @param name name of faction --! @param object calc reputation for this --! --! @return reputation value ------------------------------------------------------------------------------- function factions.calc_base_reputation(name,object) --calculate initial reputation based uppon all groups local object_factions = factions.get_factions(object) local rep_value = 0 factions.dbg_lvl3("calc_base_reputation: " .. name .. " <--> " .. tostring(object)) if object_factions ~= nil then factions.dbg_lvl3("calc_base_reputation: " .. tostring(object) .. " is in " .. #object_factions .. " factions") for k,v in pairs(object_factions) do if factions.data.factions[v] == nil then print("FACTIONS: warning object is member of faction " .. v .. " which doesn't exist") else factions.dbg_lvl3("calc_base_reputation: " .. name .. " <--> " .. v .. " rep=" .. dump(factions.data.factions[v].base_reputation[name])) if factions.data.factions[v].base_reputation[name] ~= nil then rep_value = rep_value + factions.data.factions[v].base_reputation[name] end end end rep_value = rep_value / #object_factions end return rep_value end ------------------------------------------------------------------------------- -- name: save() -- --! @brief save data to file --! @memberof factions --! @private ------------------------------------------------------------------------------- function factions.save() --saving is done much more often than reading data to avoid delay --due to figuring out which data to save and which is temporary only --all data is saved here --this implies data needs to be cleant up on load local file,error = io.open(factions_worldid .. "/" .. "factions.conf","w") if file ~= nil then file:write(minetest.serialize(factions.data)) file:close() else minetest.log("error","MOD factions: unable to save factions world specific data!: " .. error) end end ------------------------------------------------------------------------------- -- name: load() -- --! @brief load data from file --! @memberof factions --! @private -- --! @return true/false ------------------------------------------------------------------------------- function factions.load() local file,error = io.open(factions_worldid .. "/" .. "factions.conf","r") if file ~= nil then local raw_data = file:read("*a") file:close() if raw_data ~= nil and raw_data ~= "" then local raw_table = minetest.deserialize(raw_data) --read object data local temp_objects = {} if raw_table.objects ~= nil then for key,value in pairs(raw_table.objects) do if value.temporary == false then factions.data.objects[key] = value else temp_objects[key] = true end end end if raw_table.factions ~= nil then for key,value in pairs(raw_table.factions) do factions.data.factions[key] = {} factions.data.factions[key].base_reputation = value.base_reputation factions.data.factions[key].adminlist = value.adminlist factions.data.factions[key].open = value.open factions.data.factions[key].invitations = value.invitations factions.data.factions[key].reputation = {} for repkey,repvalue in pairs(value.reputation) do if temp_objects[repkey] == nil then factions.data.factions[key].reputation[repkey] = repvalue end end factions.dynamic_data.membertable[key] = {} end end --populate dynamic faction member table for id,object in pairs(factions.data.objects) do for name,value in pairs(factions.data.objects[id].factions) do if value then if factions.dynamic_data.membertable[name] then -- One of the indexes above is nil. Which one? No idea. //MFF(Mg|07/29/15) factions.dynamic_data.membertable[name][id] = true end end end end end else local file,error = io.open(factions_worldid .. "/" .. "factions.conf","w") if file ~= nil then file:close() else minetest.log("error","MOD factions: unable to save factions world specific data!: " .. error) end end --create special faction players factions.add_faction("players") --autojoin players to faction players minetest.register_on_joinplayer( function(player) if player:is_player() then factions.member_add("players",player) end end ) end
unlicense
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/JumpTiles3D.lua
6
1237
-------------------------------- -- @module JumpTiles3D -- @extend TiledGrid3DAction -------------------------------- -- @function [parent=#JumpTiles3D] getAmplitudeRate -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#JumpTiles3D] setAmplitude -- @param self -- @param #float float -------------------------------- -- @function [parent=#JumpTiles3D] setAmplitudeRate -- @param self -- @param #float float -------------------------------- -- @function [parent=#JumpTiles3D] getAmplitude -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#JumpTiles3D] create -- @param self -- @param #float float -- @param #size_table size -- @param #unsigned int int -- @param #float float -- @return JumpTiles3D#JumpTiles3D ret (return value: cc.JumpTiles3D) -------------------------------- -- @function [parent=#JumpTiles3D] clone -- @param self -- @return JumpTiles3D#JumpTiles3D ret (return value: cc.JumpTiles3D) -------------------------------- -- @function [parent=#JumpTiles3D] update -- @param self -- @param #float float return nil
mit
kitala1/darkstar
scripts/zones/Toraimarai_Canal/npcs/qm11.lua
8
1511
----------------------------------- -- Area: Toraimarai Canal -- NPC: ??? -- Involved In Quest: Wild Card -- @zone 169 // not accurate -- @pos 220 16 -50 // not accurate ----------------------------------- package.loaded["scripts/zones/Toraimarai_Canal/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Toraimarai_Canal/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("rootProblem") == 2) then if (player:getVar("rootProblemQ1") == 2 and player:getVar("rootProblemQ2") == 2) then player:startEvent(0x30); end elseif(player:getVar("rootProblem") == 3) then player:startEvent(0x37); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x30 and option ~= 0) then SpawnMob(17469516,180):updateClaim(player); end end;
gpl-3.0
kitala1/darkstar
scripts/globals/mobskills/Throat_Stab.lua
7
1114
--------------------------------------------- -- Throat Stab -- -- Description: Deals damage to a single target reducing their HP to 5%. Resets enmity. -- Type: Physical -- Utsusemi/Blink absorb: No -- Range: Single Target -- Notes: Very short range, easily evaded by walking away from it. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/magic"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local currentHP = target:getHP(); -- remove all by 5% local damage = 0; -- if have more hp then 30%, then reduce to 5% if(currentHP / target:getMaxHP() > 0.2) then damage = currentHP * .95; else -- else you die damage = currentHP; end local dmg = MobFinalAdjustments(damage,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); mob:resetEnmity(target); return dmg; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Port_San_dOria/npcs/Fontoumant.lua
17
4406
----------------------------------- -- Area: Port San d'Oria -- NPC: Fontoumant -- Starts Quest: The Brugaire Consortium -- Involved in Quests: Riding on the Clouds -- @zone 232 -- @pos -10 -10 -122 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); if(player:getQuestStatus(SANDORIA,THE_BRUGAIRE_CONSORTIUM) == QUEST_ACCEPTED) then if(count == 1 and trade:getGil() == 100) then -- pay to replace package local prog = player:getVar("TheBrugaireConsortium-Parcels"); if(prog == 10 and player:hasItem(593) == false)then player:startEvent(0x0260); player:setVar("TheBrugaireConsortium-Parcels",11) elseif(prog == 20 and player:hasItem(594) == false) then player:startEvent(0x0261); player:setVar("TheBrugaireConsortium-Parcels",21) elseif(prog == 30 and player:hasItem(595) == false) then player:startEvent(0x0262); player:setVar("TheBrugaireConsortium-Parcels",31) end end end if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if(trade:hasItemQty(532,1) and count == 1) then -- Trade Magicmart Flyer player:messageSpecial(FLYER_REFUSED); end end if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_1") == 6) then if(trade:hasItemQty(1127,1) and count == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_1",0); player:tradeComplete(); player:addKeyItem(SCOWLING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SCOWLING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TheBrugaireConsortium = player:getQuestStatus(SANDORIA,THE_BRUGAIRE_CONSORTIUM); if(TheBrugaireConsortium == QUEST_AVAILABLE) then player:startEvent(0x01fd); elseif(TheBrugaireConsortium == QUEST_ACCEPTED) then local prog = player:getVar("TheBrugaireConsortium-Parcels"); if(prog == 11) then player:startEvent(0x01ff); elseif(prog == 21) then player:startEvent(0x0200); elseif(prog == 31) then player:startEvent(0x0203); else player:startEvent(0x0230); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); local freeSlots = player:getFreeSlotsCount(); if(csid == 0x01fd and option == 0) then if(freeSlots ~= 0)then player:addItem(593); player:messageSpecial(ITEM_OBTAINED,593); player:addQuest(SANDORIA,THE_BRUGAIRE_CONSORTIUM) player:setVar("TheBrugaireConsortium-Parcels",10) else player:startEvent(0x0219); end elseif(csid == 0x01ff) then if(freeSlots ~= 0)then player:addItem(594); player:messageSpecial(ITEM_OBTAINED,594); player:setVar("TheBrugaireConsortium-Parcels",20); else player:startEvent(0x0219); end elseif(csid == 0x0200) then if(freeSlots ~= 0)then player:addItem(595); player:messageSpecial(ITEM_OBTAINED,595); player:setVar("TheBrugaireConsortium-Parcels",30); else player:startEvent(0x0219); end elseif(csid == 0x0260 or csid == 0x0261 or csid == 0x0262) then player:tradeComplete() elseif(csid == 0x0203) then if(freeSlots ~= 0)then player:addItem(0x3001); player:messageSpecial(ITEM_OBTAINED,0x3001); player:addTitle(COURIER_EXTRAORDINAIRE); player:completeQuest(SANDORIA,THE_BRUGAIRE_CONSORTIUM); player:addFame(SANDORIA,SAN_FAME*30); player:setVar("TheBrugaireConsortium-Parcels",0); else player:startEvent(0x0219); end end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Giddeus/npcs/qm1.lua
8
1715
----------------------------------- -- Area: Giddeus -- NPC: ??? -- Involved In Quest: Dark Legacy -- @zone 145 -- @pos -58 0 -449 ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Giddeus/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) darkLegacyCS = player:getVar("darkLegacyCS"); if(darkLegacyCS == 3 or darkLegacyCS == 4) then if(trade:hasItemQty(4445,1) and trade:getItemCount() == 1) then -- Trade Yagudo Cherries player:tradeComplete(); player:messageSpecial(SENSE_OF_FOREBODING); SpawnMob(17371579,180):updateClaim(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getVar("darkLegacyCS") == 5 and player:hasKeyItem(DARKSTEEL_FORMULA) == false) then player:addKeyItem(DARKSTEEL_FORMULA); player:messageSpecial(KEYITEM_OBTAINED,DARKSTEEL_FORMULA); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Roblox/Core-Scripts
CoreScriptsRoot/Modules/AvatarContextMenu/ContextMenuItems.lua
1
10685
--[[ // FileName: ContextMenuItems.lua // Written by: TheGamer101 // Description: Module for creating the context menu items for the menu and doing the actions when they are clicked. ]] -- CONSTANTS local FRIEND_LAYOUT_ORDER = 1 local CHAT_LAYOUT_ORDER = 3 local WAVE_LAYOUT_ORDER = 4 local CUSTOM_LAYOUT_ORDER = 20 local MENU_ITEM_SIZE_X = 0.96 local MENU_ITEM_SIZE_Y = 0 local MENU_ITEM_SIZE_Y_OFFSET = 52 local THUMBNAIL_URL = "https://www.roblox.com/Thumbs/Avatar.ashx?x=200&y=200&format=png&userId=" local BUST_THUMBNAIL_URL = "https://www.roblox.com/bust-thumbnail/image?width=420&height=420&format=png&userId=" --- SERVICES local PlayersService = game:GetService("Players") local CoreGuiService = game:GetService("CoreGui") local StarterGui = game:GetService("StarterGui") local Chat = game:GetService("Chat") local RunService = game:GetService("RunService") local AnalyticsService = game:GetService("AnalyticsService") -- MODULES local RobloxGui = CoreGuiService:WaitForChild("RobloxGui") local CoreGuiModules = RobloxGui:WaitForChild("Modules") local SettingsModules = CoreGuiModules:WaitForChild("Settings") local AvatarMenuModules = CoreGuiModules:WaitForChild("AvatarContextMenu") local SettingsPages = SettingsModules:WaitForChild("Pages") local ContextMenuUtil = require(AvatarMenuModules:WaitForChild("ContextMenuUtil")) local PromptCreator = require(CoreGuiModules:WaitForChild("PromptCreator")) local PlayerDropDownModule = require(CoreGuiModules:WaitForChild("PlayerDropDown")) local ReportAbuseMenu = require(SettingsPages:WaitForChild("ReportAbuseMenu")) -- VARIABLES local LocalPlayer = PlayersService.LocalPlayer while not LocalPlayer do PlayersService.PlayerAdded:wait() LocalPlayer = PlayersService.LocalPlayer end local EnabledContextMenuItems = { [Enum.AvatarContextMenuOption.Chat] = true, [Enum.AvatarContextMenuOption.Friend] = true, [Enum.AvatarContextMenuOption.Emote] = true } local CustomContextMenuItems = {} local BlockingUtility = PlayerDropDownModule:CreateBlockingUtility() local ContextMenuItems = {} ContextMenuItems.__index = ContextMenuItems -- PRIVATE METHODS function ContextMenuItems:ClearMenuItems() local children = self.MenuItemFrame:GetChildren() for i = 1, #children do if children[i]:IsA("GuiObject") then children[i]:Destroy() end end end function ContextMenuItems:AddCustomAvatarMenuItem(menuOption, bindableEvent) CustomContextMenuItems[menuOption] = bindableEvent end function ContextMenuItems:RemoveCustomAvatarMenuItem(menuOption) CustomContextMenuItems[menuOption] = nil end function ContextMenuItems:IsContextAvatarEnumItem(enumItem) local enumItems = Enum.AvatarContextMenuOption:GetEnumItems() for i = 1, #enumItems do if enumItem == enumItems[i] then return true end end return false end function ContextMenuItems:EnableDefaultMenuItem(menuOption) EnabledContextMenuItems[menuOption] = true end function ContextMenuItems:RemoveDefaultMenuItem(menuOption) EnabledContextMenuItems[menuOption] = false end function ContextMenuItems:RegisterCoreMethods() local function addMenuItemFunc(args) --[[ menuOption, bindableEvent]] if type(args) == "table" then local name = "" if args[1] and type(args[1]) == "string" then name = args[1] else error("AddAvatarContextMenuOption first argument must be a table or Enum.AvatarContextMenuOption") end if args[2] and typeof(args[2]) == "Instance" and args[2].ClassName == "BindableEvent" then self:AddCustomAvatarMenuItem(name, args[2]) else error("AddAvatarContextMenuOption second table entry must be a BindableEvent") end elseif typeof(args) == "EnumItem" then if self:IsContextAvatarEnumItem(args) then self:EnableDefaultMenuItem(args) else error("AddAvatarContextMenuOption given EnumItem is not valid") end else error("AddAvatarContextMenuOption first argument must be a table or Enum.AvatarContextMenuOption") end end StarterGui:RegisterSetCore("AddAvatarContextMenuOption", addMenuItemFunc) local function removeMenuItemFunc(menuOption) if type(menuOption) == "string" then self:RemoveCustomAvatarMenuItem(menuOption) elseif typeof(menuOption) == "EnumItem" then if self:IsContextAvatarEnumItem(menuOption) then self:RemoveDefaultMenuItem(menuOption) else error("RemoveAvatarContextMenuOption given EnumItem is not valid") end else error("RemoveAvatarContextMenuOption first argument must be a string or Enum.AvatarContextMenuOption") end end StarterGui:RegisterSetCore("RemoveAvatarContextMenuOption", removeMenuItemFunc) end function ContextMenuItems:CreateCustomMenuItems() for buttonText, bindableEvent in pairs(CustomContextMenuItems) do AnalyticsService:TrackEvent("Game", "AvatarContextMenuCustomButton", "name: " .. tostring(buttonText)) local function customButtonFunc() bindableEvent:Fire(self.SelectedPlayer) end local customButton = ContextMenuUtil:MakeStyledButton("CustomButton", buttonText, UDim2.new(MENU_ITEM_SIZE_X, 0, MENU_ITEM_SIZE_Y, MENU_ITEM_SIZE_Y_OFFSET), customButtonFunc) customButton.Name = "CustomButton" customButton.LayoutOrder = CUSTOM_LAYOUT_ORDER customButton.Parent = self.MenuItemFrame end end -- PUBLIC METHODS local addFriendString = "Add Friend" local friendsString = "Friends" local friendRequestPendingString = "Friend Request Pending" local acceptFriendRequestString = "Accept Friend Request" local addFriendDisabledTransparency = 0.75 local friendStatusChangedConn = nil function ContextMenuItems:CreateFriendButton(status) local friendLabel = self.MenuItemFrame:FindFirstChild("FriendStatus") if friendLabel then friendLabel:Destroy() friendLabel = nil end if friendStatusChangedConn then friendStatusChangedConn:disconnect() end local friendLabelText = nil local addFriendFunc = function() if friendLabelText and friendLabel.Selectable then friendLabel.Selectable = false friendLabelText.TextTransparency = addFriendDisabledTransparency friendLabelText.Text = friendRequestPendingString AnalyticsService:ReportCounter("AvatarContextMenu-RequestFriendship") AnalyticsService:TrackEvent("Game", "RequestFriendship", "AvatarContextMenu") LocalPlayer:RequestFriendship(self.SelectedPlayer) end end friendLabel, friendLabelText = ContextMenuUtil:MakeStyledButton("FriendStatus", addFriendString, UDim2.new(MENU_ITEM_SIZE_X, 0, MENU_ITEM_SIZE_Y, MENU_ITEM_SIZE_Y_OFFSET), addFriendFunc) if status ~= Enum.FriendStatus.Friend then friendLabel.Selectable = true friendLabelText.TextTransparency = 0 else friendLabel.Selectable = false friendLabelText.TextTransparency = addFriendDisabledTransparency friendLabelText.Text = friendsString end friendStatusChangedConn = LocalPlayer.FriendStatusChanged:connect(function(player, friendStatus) if player == self.SelectedPlayer and friendLabelText then if not friendLabel.Selectable then if friendStatus == Enum.FriendStatus.Friend then friendLabelText.Text = friendsString end else if friendStatus == Enum.FriendStatus.FriendRequestReceived then friendLabelText.Text = acceptFriendRequestString end end end end) friendLabel.LayoutOrder = FRIEND_LAYOUT_ORDER friendLabel.Parent = self.MenuItemFrame end function ContextMenuItems:UpdateFriendButton(status) local friendLabel = self.MenuItemFrame:FindFirstChild("FriendStatus") if friendLabel then self:CreateFriendButton(status) end end function ContextMenuItems:CreateEmoteButton() local function wave() if self.CloseMenuFunc then self:CloseMenuFunc() end AnalyticsService:ReportCounter("AvatarContextMenu-Wave") AnalyticsService:TrackEvent("Game", "AvatarContextMenuWave", "placeId: " .. tostring(game.PlaceId)) PlayersService:Chat("/e wave") end local waveButton = self.MenuItemFrame:FindFirstChild("Wave") if not waveButton then waveButton = ContextMenuUtil:MakeStyledButton("Wave", "Wave", UDim2.new(MENU_ITEM_SIZE_X, 0, MENU_ITEM_SIZE_Y, MENU_ITEM_SIZE_Y_OFFSET), wave) waveButton.LayoutOrder = WAVE_LAYOUT_ORDER waveButton.Parent = self.MenuItemFrame end end function ContextMenuItems:CreateChatButton() local function chatFunc() if self.CloseMenuFunc then self:CloseMenuFunc() end AnalyticsService:ReportCounter("AvatarContextMenu-Chat") AnalyticsService:TrackEvent("Game", "AvatarContextMenuChat", "placeId: " .. tostring(game.PlaceId)) -- todo: need a proper api to set up text in the chat bar local ChatBar = nil pcall(function() ChatBar = LocalPlayer.PlayerGui.Chat.Frame.ChatBarParentFrame.Frame.BoxFrame.Frame.ChatBar end) if ChatBar then ChatBar.Text = "/w " .. self.SelectedPlayer.Name end local ChatModule = require(RobloxGui.Modules.ChatSelector) ChatModule:SetVisible(true) ChatModule:FocusChatBar() end local chatButton = self.MenuItemFrame:FindFirstChild("ChatStatus") if not chatButton then chatButton = ContextMenuUtil:MakeStyledButton("ChatStatus", "Chat", UDim2.new(MENU_ITEM_SIZE_X, 0, MENU_ITEM_SIZE_Y, MENU_ITEM_SIZE_Y_OFFSET), chatFunc) chatButton.LayoutOrder = CHAT_LAYOUT_ORDER end local success, canLocalUserChat = pcall(function() return Chat:CanUserChatAsync(LocalPlayer.UserId) end) local canChat = success and (RunService:IsStudio() or canLocalUserChat) if canChat then chatButton.Parent = self.MenuItemFrame else chatButton.Parent = nil end end function ContextMenuItems:BuildContextMenuItems(player) if not player then return end local friendStatus = ContextMenuUtil:GetFriendStatus(player) local isBlocked = BlockingUtility:IsPlayerBlockedByUserId(player.UserId) local isMuted = BlockingUtility:IsPlayerMutedByUserId(player.UserId) self:ClearMenuItems() self:SetSelectedPlayer(player) if EnabledContextMenuItems[Enum.AvatarContextMenuOption.Friend] then self:CreateFriendButton(friendStatus) end if EnabledContextMenuItems[Enum.AvatarContextMenuOption.Chat] then self:CreateChatButton() end if EnabledContextMenuItems[Enum.AvatarContextMenuOption.Emote] then self:CreateEmoteButton() end self:CreateCustomMenuItems() end function ContextMenuItems:SetSelectedPlayer(selectedPlayer) self.SelectedPlayer = selectedPlayer end function ContextMenuItems:SetCloseMenuFunc(closeMenuFunc) self.CloseMenuFunc = closeMenuFunc end function ContextMenuItems.new(menuItemFrame) local obj = setmetatable({}, ContextMenuItems) obj.MenuItemFrame = menuItemFrame obj.SelectedPlayer = nil obj:RegisterCoreMethods() return obj end return ContextMenuItems
apache-2.0
kitala1/darkstar
scripts/globals/items/bowl_of_cursed_soup.lua
35
1602
----------------------------------------- -- ID: 4235 -- Item: Bowl of Cursed Soup -- Food Effect: 180Min, All Races ----------------------------------------- -- Strength -7 -- Dexterity -7 -- Agility -7 -- Vitality -7 -- Intelligence -7 -- Mind -7 -- Charisma -7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4235); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -7); target:addMod(MOD_DEX, -7); target:addMod(MOD_AGI, -7); target:addMod(MOD_VIT, -7); target:addMod(MOD_INT, -7); target:addMod(MOD_MND, -7); target:addMod(MOD_CHR, -7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -7); target:delMod(MOD_DEX, -7); target:delMod(MOD_AGI, -7); target:delMod(MOD_VIT, -7); target:delMod(MOD_INT, -7); target:delMod(MOD_MND, -7); target:delMod(MOD_CHR, -7); end;
gpl-3.0
Behemyth/GameJamFall2015
GameJamFall2015/Libraries/bullet/Demos/OpenCLClothDemo/AMD/premake4.lua
12
1104
hasCL = findOpenCL_AMD() if (hasCL) then project "AppOpenCLClothDemo_AMD" defines { "USE_AMD_OPENCL","CL_PLATFORM_AMD"} initOpenCL_AMD() language "C++" kind "ConsoleApp" targetdir "../../.." libdirs {"../../../Glut"} links { "LinearMath", "BulletCollision", "BulletDynamics", "BulletSoftBody", "BulletSoftBodySolvers_OpenCL_AMD", "opengl32" } configuration { "Windows" } defines { "GLEW_STATIC"} configuration "x64" links { "glut64", "glew64s" } configuration "x32" links { "glut32", "glew32s" } configuration{} includedirs { "../../../src", "../../../Glut", "../../SharedOpenCL", "../../OpenGL" } files { "../cl_cloth_demo.cpp", "../../SharedOpenCL/btOpenCLUtils.cpp", "../../SharedOpenCL/btOpenCLUtils.h", "../../SharedOpenCL/btOpenCLInclude.h", "../../OpenGL/GLDebugDrawer.cpp", "../../OpenGL/stb_image.cpp", "../../OpenGL/stb_image.h", "../gl_win.cpp", "../clstuff.cpp", "../clstuff.h", "../gl_win.h", "../cloth.h" } end
mit
UB12/lionbot
plugins/invite.lua
1111
1195
do local function callbackres(extra, success, result) -- Callback for res_user in line 27 local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) then -- Ignore bans send_large_msg(chat, 'User is banned.') elseif is_gbanned(result.id) then -- Ignore globall bans send_large_msg(chat, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) -- Add user on chat end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end --if not is_admin(msg) then -- For admins only ! --return 'Only admins can invite.' --end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^[!/]invite (.*)$" }, run = run } end
gpl-2.0
kitala1/darkstar
scripts/zones/Apollyon/mobs/Cornu.lua
17
1135
----------------------------------- -- Area: Apollyon NE -- NPC: Sirins ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if(mobID ==16933066)then -- time T3 GetNPCByID(16932864+84):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+84):setStatus(STATUS_NORMAL); elseif(mobID ==16933069)then -- recover GetNPCByID(16932864+127):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+127):setStatus(STATUS_NORMAL); end end;
gpl-3.0
shahabsaf1/uzz-bot
plugins/remind.lua
362
1875
local filename='data/remind.lua' local cronned = load_from_file(filename) local function save_cron(msg, text,date) local origin = get_receiver(msg) if not cronned[date] then cronned[date] = {} end local arr = { origin, text } ; table.insert(cronned[date], arr) serialize_to_file(cronned, filename) return 'Saved!' end local function delete_cron(date) for k,v in pairs(cronned) do if k == date then cronned[k]=nil end end serialize_to_file(cronned, filename) end local function cron() for date, values in pairs(cronned) do if date < os.time() then --time's up send_msg(values[1][1], "Time's up:\n"..values[1][2], ok_cb, false) delete_cron(date) --TODO: Maybe check for something else? Like user end end end local function actually_run(msg, delay,text) if (not delay or not text) then return "Usage: !remind [delay: 2h3m1s] text" end save_cron(msg, text,delay) return "I'll remind you on " .. os.date("%x at %H:%M:%S",delay) .. " about '" .. text .. "'" end local function run(msg, matches) local sum = 0 for i = 1, #matches-1 do local b,_ = string.gsub(matches[i],"[a-zA-Z]","") if string.find(matches[i], "s") then sum=sum+b end if string.find(matches[i], "m") then sum=sum+b*60 end if string.find(matches[i], "h") then sum=sum+b*3600 end end local date=sum+os.time() local text = matches[#matches] local text = actually_run(msg, date, text) return text end return { description = "remind plugin", usage = { "!remind [delay: 2hms] text", "!remind [delay: 2h3m] text", "!remind [delay: 2h3m1s] text" }, patterns = { "^!remind ([0-9]+[hmsdHMSD]) (.+)$", "^!remind ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$", "^!remind ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$" }, run = run, cron = cron }
gpl-2.0
crabman77/minetest-minetestforfun-server
minetestforfun_game/mods/beds/spawns.lua
7
1385
local world_path = minetest.get_worldpath() local org_file = world_path .. "/beds_spawns" local file = world_path .. "/beds_spawns" local bkwd = false -- check for PA's beds mod spawns local cf = io.open(world_path .. "/beds_player_spawns", "r") if cf ~= nil then io.close(cf) file = world_path .. "/beds_player_spawns" bkwd = true end function beds.read_spawns() local spawns = beds.spawn local input = io.open(file, "r") if input and not bkwd then repeat local x = input:read("*n") if x == nil then break end local y = input:read("*n") local z = input:read("*n") local name = input:read("*l") spawns[name:sub(2)] = {x = x, y = y, z = z} until input:read(0) == nil io.close(input) elseif input and bkwd then beds.spawn = minetest.deserialize(input:read("*all")) input:close() beds.save_spawns() os.rename(file, file .. ".backup") file = org_file else spawns = {} end end function beds.save_spawns() if not beds.spawn then return end local output = io.open(org_file, "w") for i, v in pairs(beds.spawn) do output:write(v.x.." "..v.y.." "..v.z.." "..i.."\n") end io.close(output) end function beds.set_spawns() for name,_ in pairs(beds.player) do local player = minetest.get_player_by_name(name) local p = player:getpos() beds.spawn[name] = p end beds.save_spawns() end beds.read_spawns()
unlicense
crabman77/minetest-minetestforfun-server
mods/plantlife_modpack/trunks/crafting.lua
9
4425
-- Code by Mossmanikin ----------------------------------------------------------------------------------------------- -- TWiGS ----------------------------------------------------------------------------------------------- minetest.register_craft({ -- *leaves --> twigs output = "trunks:twig_1 2", recipe = {{"group:leafdecay"}} }) if minetest.get_modpath("moretrees") ~= nil then minetest.register_craft({ -- moretrees_leaves --> twigs output = "trunks:twig_1 2", recipe = {{"group:moretrees_leaves"}} }) minetest.register_craft({ -- except moretrees:palm_leaves output = "moretrees:palm_leaves", recipe = {{"moretrees:palm_leaves"}} }) end if minetest.get_modpath("bushes") ~= nil then minetest.register_craft({ -- BushLeaves --> twigs output = "trunks:twig_1 2", recipe = {{"bushes:BushLeaves1"}} }) minetest.register_craft({ output = "trunks:twig_1 2", recipe = {{"bushes:BushLeaves2"}} }) minetest.register_craft({ -- bushbranches --> twigs output = "trunks:twig_1 4", recipe = {{"bushes:bushbranches1"}} }) minetest.register_craft({ output = "trunks:twig_1 4", recipe = {{"bushes:bushbranches2"}} }) minetest.register_craft({ output = "trunks:twig_1 4", recipe = {{"bushes:bushbranches2"}} }) minetest.register_craft({ output = "trunks:twig_1 4", recipe = {{"bushes:bushbranches3"}} }) end minetest.register_craft({ -- twigs block --> twigs output = "trunks:twig_1 8", recipe = {{"trunks:twigs"}} }) minetest.register_craft({ -- twigs_slab --> twigs output = "trunks:twig_1 4", recipe = {{"trunks:twigs_slab"}} }) minetest.register_craft({ -- twigs_roof --> twigs output = "trunks:twig_1 4", recipe = {{"trunks:twigs_roof"}} }) minetest.register_craft({ -- twigs_roof_corner --> twigs output = "trunks:twig_1 3", recipe = {{"trunks:twigs_roof_corner"}} }) minetest.register_craft({ -- twigs_roof_corner_2 --> twigs output = "trunks:twig_1 3", recipe = {{"trunks:twigs_roof_corner_2"}} }) ----------------------------------------------------------------------------------------------- -- STiCK ----------------------------------------------------------------------------------------------- minetest.register_craft({ -- twig --> stick output = "default:stick", recipe = {{"trunks:twig_1"}} }) ----------------------------------------------------------------------------------------------- -- TWiGS BLoCK ----------------------------------------------------------------------------------------------- minetest.register_craft({ -- twigs --> twigs block output = "trunks:twigs", recipe = { {"trunks:twig_1","trunks:twig_1","trunks:twig_1"}, {"trunks:twig_1", "" ,"trunks:twig_1"}, {"trunks:twig_1","trunks:twig_1","trunks:twig_1"}, } }) ----------------------------------------------------------------------------------------------- -- TWiGS SLaBS ----------------------------------------------------------------------------------------------- minetest.register_craft({ -- twigs blocks --> twigs_slabs output = "trunks:twigs_slab 6", recipe = { {"trunks:twigs","trunks:twigs","trunks:twigs"}, } }) ----------------------------------------------------------------------------------------------- -- TWiGS RooFS ----------------------------------------------------------------------------------------------- minetest.register_craft({ -- twigs blocks --> twigs_roofs output = "trunks:twigs_roof 4", recipe = { {"trunks:twigs",""}, {"","trunks:twigs"}, } }) minetest.register_craft({ output = "trunks:twigs_roof 4", recipe = { {"","trunks:twigs"}, {"trunks:twigs",""}, } }) ----------------------------------------------------------------------------------------------- -- TWiGS RooF CoRNeRS ----------------------------------------------------------------------------------------------- minetest.register_craft({ -- twigs blocks --> twigs_roof_corners output = "trunks:twigs_roof_corner 8", recipe = { { "" ,"trunks:twigs", "" }, {"trunks:twigs", "" ,"trunks:twigs"}, } }) ----------------------------------------------------------------------------------------------- -- TWiGS RooF CoRNeRS 2 ----------------------------------------------------------------------------------------------- minetest.register_craft({ -- twigs blocks --> twigs_roof_corner_2's output = "trunks:twigs_roof_corner_2 8", recipe = { {"trunks:twigs", "" ,"trunks:twigs"}, { "" ,"trunks:twigs", "" }, } })
unlicense
kitala1/darkstar
scripts/globals/effects/int_down.lua
19
1095
----------------------------------- -- -- EFFECT_INT_DOWN -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) if((target:getStat(MOD_INT) - effect:getPower()) < 0) then effect:setPower(target:getStat(MOD_INT)); end target:addMod(MOD_INT,-effect:getPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) -- the effect restore intelligence of 1 every 3 ticks. local downINT_effect_size = effect:getPower() if(downINT_effect_size > 0) then effect:setPower(downINT_effect_size - 1) target:delMod(MOD_INT,-1); end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local downINT_effect_size = effect:getPower() if(downINT_effect_size > 0) then target:delMod(MOD_INT,-downINT_effect_size); end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Dangruf_Wadi/npcs/Treasure_Chest.lua
12
2567
----------------------------------- -- Area: Dangruf Wadi -- NPC: Treasure Chest -- @zone 191 ----------------------------------- package.loaded["scripts/zones/Dangruf_Wadi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/treasure"); require("scripts/zones/Dangruf_Wadi/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1028,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if((trade:hasItemQty(1028,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if(pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if(success ~= -2) then player:tradeComplete(); if(math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if(loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1028); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
cdettmering/fancyland
LayerController.lua
1
3773
-- LayerController --- -- Visual: Shows how the camera moves along the layer over time. -- -- Step 1: -- ----------------------------------------------------- -- | Trees | Caves | Mountains | Trees | Trees | Caves | -- ----------------------------------------------------- -- ---------- -- | Camera | -- ---------- -- -- Step 2: -- ----------------------------------------------------- -- | Trees | Caves | Mountains | Trees | Trees | Caves | -- ----------------------------------------------------- -- ---------- -- | Camera | -- ---------- -- -- Step 3: -- ----------------------------------------------------- -- | Trees | Caves | Mountains | Trees | Trees | Caves | -- ----------------------------------------------------- -- ---------- -- | Camera | -- ---------- -- -- Step 4: -- ----------------------------------------------------- -- | Trees | Caves | Mountains | Trees | Trees | Caves | -- ----------------------------------------------------- -- ---------- -- | Camera | -- ---------- -- -- Step N: -- ----------------------------------------------------- -- | Trees | Caves | Mountains | Trees | Trees | Caves | -- ----------------------------------------------------- -- ---------- -- | Camera | -- ---------- -- Setup local access local Camera = require('Camera') local floor = math.floor local LayerController = {} local LayerController_mt = {} LayerController_mt.__index = LayerController local function mapXPositionToTexture(x) -- first figure out which 'cell' the x position maps to local cell = floor(x / NATIVE_WIDTH) -- add 1, because that computation will give us a 0 based index, and Lua -- uses a 1 based index cell = cell + 1 return cell end function LayerController:new(layer) local controller = {} controller._layer = layer return setmetatable(controller, LayerController_mt) end function LayerController:layer() return self._layer end function LayerController:draw(x) -- The Layer's perception of where it should draw is based on the speed of -- the Layer. x = x * self._layer.speed -- Grab the 3 textures to draw, the texture after the current cell is always -- drawn so there isnt a blank hole when the current texture scrolls by. -- The previous texture is also drawn, since the boundaries between -- the textures is crossed in the middle of the screen (where the -- Vampire is). local firstTexture = mapXPositionToTexture(x) local secondTexture = firstTexture + 1 local thirdTexture = firstTexture - 1 -- compute how much x offset it should be drawn at, based on the current -- X position. local firstX = (firstTexture - 1) * NATIVE_WIDTH local secondX = (secondTexture - 1) * NATIVE_WIDTH local thirdX = (thirdTexture -1) * NATIVE_WIDTH -- Since the layers have a parallax effect, we cannot use an umbrella push, pop -- like in a normal game. local save = Camera._positionX Camera.setAbsolutePosition(x, 0) Camera.push() -- if nil, don't draw just leave blank if self._layer.textures[firstTexture] ~= nil then love.graphics.draw(self._layer.textures[firstTexture], firstX, 0, 0, 1, 1, 0, 0) end if self._layer.textures[secondTexture] ~= nil then love.graphics.draw(self._layer.textures[secondTexture], secondX, 0, 0, 1, 1, 0, 0) end if self._layer.textures[thirdTexture] ~= nil then love.graphics.draw(self._layer.textures[thirdTexture], thirdX, 0, 0, 1, 1, 0, 0) end Camera.pop() Camera.setAbsolutePosition(save, 0) end return LayerController
gpl-3.0
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Texture2D.lua
3
5591
-------------------------------- -- @module Texture2D -- @extend Ref -------------------------------- -- @function [parent=#Texture2D] getMaxT -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Texture2D] getStringForFormat -- @param self -- @return char#char ret (return value: char) -------------------------------- -- overload function: initWithImage(cc.Image, cc.Texture2D::PixelFormat) -- -- overload function: initWithImage(cc.Image) -- -- @function [parent=#Texture2D] initWithImage -- @param self -- @param #cc.Image image -- @param #cc.Texture2D::PixelFormat pixelformat -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Texture2D] getMaxS -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Texture2D] updateWithData -- @param self -- @param #void void -- @param #int int -- @param #int int -- @param #int int -- @param #int int -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Texture2D] hasPremultipliedAlpha -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Texture2D] initWithMipmaps -- @param self -- @param #cc._MipmapInfo map -- @param #int int -- @param #cc.Texture2D::PixelFormat pixelformat -- @param #int int -- @param #int int -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Texture2D] getPixelsHigh -- @param self -- @return int#int ret (return value: int) -------------------------------- -- overload function: getBitsPerPixelForFormat(cc.Texture2D::PixelFormat) -- -- overload function: getBitsPerPixelForFormat() -- -- @function [parent=#Texture2D] getBitsPerPixelForFormat -- @param self -- @param #cc.Texture2D::PixelFormat pixelformat -- @return unsigned int#unsigned int ret (retunr value: unsigned int) -------------------------------- -- @function [parent=#Texture2D] getName -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- overload function: initWithString(char, cc.FontDefinition) -- -- overload function: initWithString(char, string, float, size_table, cc.TextHAlignment, cc.TextVAlignment) -- -- @function [parent=#Texture2D] initWithString -- @param self -- @param #char char -- @param #string str -- @param #float float -- @param #size_table size -- @param #cc.TextHAlignment texthalignment -- @param #cc.TextVAlignment textvalignment -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Texture2D] setMaxT -- @param self -- @param #float float -------------------------------- -- @function [parent=#Texture2D] drawInRect -- @param self -- @param #rect_table rect -------------------------------- -- @function [parent=#Texture2D] getContentSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#Texture2D] setAliasTexParameters -- @param self -------------------------------- -- @function [parent=#Texture2D] setAntiAliasTexParameters -- @param self -------------------------------- -- @function [parent=#Texture2D] generateMipmap -- @param self -------------------------------- -- @function [parent=#Texture2D] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Texture2D] getPixelFormat -- @param self -- @return Texture2D::PixelFormat#Texture2D::PixelFormat ret (return value: cc.Texture2D::PixelFormat) -------------------------------- -- @function [parent=#Texture2D] setGLProgram -- @param self -- @param #cc.GLProgram glprogram -------------------------------- -- @function [parent=#Texture2D] getContentSizeInPixels -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#Texture2D] getPixelsWide -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#Texture2D] drawAtPoint -- @param self -- @param #cc.Vec2 vec2 -------------------------------- -- @function [parent=#Texture2D] getGLProgram -- @param self -- @return GLProgram#GLProgram ret (return value: cc.GLProgram) -------------------------------- -- @function [parent=#Texture2D] hasMipmaps -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Texture2D] setMaxS -- @param self -- @param #float float -------------------------------- -- @function [parent=#Texture2D] setDefaultAlphaPixelFormat -- @param self -- @param #cc.Texture2D::PixelFormat pixelformat -------------------------------- -- @function [parent=#Texture2D] getDefaultAlphaPixelFormat -- @param self -- @return Texture2D::PixelFormat#Texture2D::PixelFormat ret (return value: cc.Texture2D::PixelFormat) -------------------------------- -- @function [parent=#Texture2D] PVRImagesHavePremultipliedAlpha -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Texture2D] Texture2D -- @param self return nil
mit
kitala1/darkstar
scripts/zones/Riverne-Site_A01/npcs/Unstable_Displacement.lua
36
1068
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement -- ENM Battlefield ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Riverne-Site_A01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(SPACE_SEEMS_DISTORTED); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
IBYoung/oceanbase
oceanbase_0.4/tools/mysql_stress/kucun.lua
24
1063
-- `stress_sqls' table list all sqls used to stress stress_sqls = { { sql = [[ insert into ipm_inventory_detail ( opt_type, opt_num, inventory_id, user_id, item_id, sku_id, bizorderid, childbizorderid, quantity, gmt_create, gmt_modified, status, version, time_out, time_number, opt_gmt_create, area_id, feature, flag, store_code, reserved_by_cache, store_quantity, reserved_quantity ) values( 901, ?, 229470000034651912, 734912947, 16189925503, 25981667911, 228580756797565, 228580756807565, 1, current_time(), current_time(), 1, 0, TIMESTAMP'2013-02-24 14:24:16', 0, TIMESTAMP'2013-02-24 14:07:16', 440608, null, 2, 'IC', 0, 31, 1 ) when row_count(update ipm_inventory set version=version+1, gmt_modified=current_time(), quantity = 100009070, reserve_quantity = reserve_quantity + 1 where item_id = ? and sku_id = 0 and type = 901 and store_code = 'IC' and (100009070 - reserve_quantity - 1) >= 0) = 1; ]], params = { {type = "distinct_int"}, {type = "int", range_min = 1, range_max = 20}, } }, }
gpl-2.0
kitala1/darkstar
scripts/zones/Apollyon/mobs/Dee_Wapa_the_Desolator.lua
17
2385
----------------------------------- -- Area: Apollyon CS -- NPC: Dee_Wapa_the_Desolator ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local mobID = mob:getID(); local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); SpawnMob(16933148):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933147):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933149):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933146):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local mobID = mob:getID(); local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); local lifepourcent= ((mob:getHP()/mob:getMaxHP())*100); local instancetime = target:getSpecialBattlefieldLeftTime(5); if(lifepourcent < 50 and GetNPCByID(16933247):getAnimation() == 8)then SpawnMob(16933151):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933150):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); SpawnMob(16933152):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetNPCByID(16933247):setAnimation(9); end if(instancetime < 13)then if(IsMobDead(16933129)==false)then GetMobByID(16933129):updateEnmity(target); elseif(IsMobDead(16933137)==false)then GetMobByID(16933137):updateEnmity(target); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if((IsMobDead(16933129)==false or IsMobDead(16933137)==false) and alreadyReceived(killer,3,GetInstanceRegion(1294)) == false)then killer:addTimeToSpecialBattlefield(5,5); addLimbusList(killer,4,GetInstanceRegion(1294)); end end;
gpl-3.0
LuaDist2/lua_cliargs
spec/printer_spec.lua
3
6891
local helpers = require 'spec_helper' local trim = helpers.trim describe('printer', function() local cli before_each(function() cli = require("cliargs.core")() end) describe('#generate_usage', function() local function assert_msg(expected_msg) local actual_msg = cli.printer.generate_usage() assert.equal(trim(expected_msg), trim(actual_msg)) end it('works with 0 arguments', function() assert_msg 'Usage:' end) it('works with 1 argument', function() cli:argument('INPUT', 'path to the input file') assert_msg [==[ Usage: [--] INPUT ]==] end) it('works with 2+ arguments', function() cli:argument('INPUT', '...') cli:argument('OUTPUT', '...') assert_msg [==[ Usage: [--] INPUT OUTPUT ]==] end) it('prints the app name', function() cli:set_name('foo') assert_msg 'Usage: foo' end) it('prints options', function() cli:option('--foo=VALUE', '...') assert_msg [==[ Usage: [OPTIONS] ]==] end) it('prints flags', function() cli:flag('--foo', '...') assert_msg [==[ Usage: [OPTIONS] ]==] end) it('prints a splat arg with reptitions == 1', function() cli:splat('OUTPUT', '...', nil, 1) assert_msg [==[ Usage: [--] [OUTPUT] ]==] end) it('prints a splat arg with reptitions == 2', function() cli:splat('OUTPUT', '...', nil, 2) assert_msg [==[ Usage: [--] [OUTPUT-1 [OUTPUT-2]] ]==] end) it('prints a splat arg with reptitions > 2', function() cli:splat('OUTPUT', '...', nil, 5) assert_msg [==[ Usage: [--] [OUTPUT-1 [OUTPUT-2 [...]]] ]==] end) end) describe('#generate_help', function() local function assert_msg(expected_msg) local actual_msg = cli.printer.generate_help() assert.equal(trim(expected_msg), trim(actual_msg)) end it('works with nothing', function() assert_msg '' end) it('works with 1 argument', function() cli:argument('INPUT', 'path to the input file') assert_msg [==[ ARGUMENTS: INPUT path to the input file (required) ]==] end) it('works with 2+ arguments', function() cli:argument('INPUT', 'path to the input file') cli:argument('OUTPUT', 'path to the output file') assert_msg [==[ ARGUMENTS: INPUT path to the input file (required) OUTPUT path to the output file (required) ]==] end) it('works with 1 option', function() cli:option('--compress=VALUE', 'compression algorithm to use') assert_msg [==[ OPTIONS: --compress=VALUE compression algorithm to use ]==] end) it("prints an option's default value", function() cli:option('--compress=VALUE', 'compression algorithm to use', 'lzma') assert_msg [==[ OPTIONS: --compress=VALUE compression algorithm to use (default: lzma) ]==] end) it("prints a repeatable option", function() cli:option('--compress=VALUE', 'compression algorithm to use', { 'lzma' }) assert_msg [==[ OPTIONS: --compress=VALUE compression algorithm to use (default: []) ]==] end) it('works with many options', function() cli:option('--compress=VALUE', 'compression algorithm to use') cli:option('-u, --url=URL', '...') assert_msg [==[ OPTIONS: --compress=VALUE compression algorithm to use -u, --url=URL ... ]==] end) context('given a flag', function() it('prints it under OPTIONS', function() cli:flag('-q, --quiet', '...') assert_msg [==[ OPTIONS: -q, --quiet ... ]==] end) end) context('given a flag with a default value but is not negatable', function() it('does not print "on" or "off"', function() cli:flag('--quiet', '...', true) assert_msg [==[ OPTIONS: --quiet ... ]==] end) end) context('given a negatable flag', function() it('prints it along with its default value', function() cli:flag('--[no-]quiet', '...', true) cli:flag('--[no-]debug', '...', false) assert_msg [==[ OPTIONS: --[no-]quiet ... (default: on) --[no-]debug ... (default: off) ]==] end) end) context('given a splat arg', function() it('prints it with a repetition of 1', function() cli:splat("INPUTS", "directories to read from") assert_msg [==[ ARGUMENTS: INPUTS directories to read from (optional) ]==] end) it('prints it with a repetition of > 1', function() cli:splat("INPUTS", "directories to read from", nil, 3) assert_msg [==[ ARGUMENTS: INPUTS directories to read from (optional) ]==] end) it('prints it without a default value', function() cli:splat("INPUTS", "directories to read from") assert_msg [==[ ARGUMENTS: INPUTS directories to read from (optional) ]==] end) it('prints it with a default value', function() cli:splat("INPUTS", "directories to read from", 'foo') assert_msg [==[ ARGUMENTS: INPUTS directories to read from (optional, default: foo) ]==] end) end) end) describe('#dump_internal_state', function() local original_arg before_each(function() original_arg = _G['arg'] _G['arg'] = { 'spec/printer_spec.lua' } end) after_each(function() _G['arg'] = original_arg end) it('works', function() cli:argument('OUTPUT', '...') cli:splat('INPUTS', '...', nil, 100) cli:option('-c, --compress=VALUE', '...') cli:flag('-q, --quiet', '...', true) assert.equal(trim [==[ ======= Provided command line ============= Number of arguments: 1 = 'spec/printer_spec.lua' ======= Parsed command line =============== Arguments: OUTPUT => 'nil' Optional arguments:INPUTS; allowed are 100 arguments Optional parameters: -c, --compress=VALUE => nil (nil) -q, --quiet => nil (nil) =========================================== ]==], trim(cli.printer.dump_internal_state({}))) end) it('does not fail with an optarg of 1 reptitions', function() cli:splat('INPUTS', '...', nil, 1) cli.printer.dump_internal_state({}) end) it('does not fail with an optarg of many reptitions', function() cli:splat('INPUTS', '...', nil, 5) cli.printer.dump_internal_state({}) end) end) end)
mit
Whitechaser/darkstar
scripts/zones/Bastok_Markets/npcs/Umberto.lua
5
1263
----------------------------------- -- Area: Bastok Markets -- NPC: Umberto -- Type: Quest NPC -- Involved in Quest: Too Many Chefs -- !pos -56.896 -5 -134.267 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getVar("TOO_MANY_CHEFS") == 5) then -- end Quest Too Many Chefs player:startEvent(473); else player:startEvent(411); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 473) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,5674); else player:addItem(5674); player:messageSpecial(ITEM_OBTAINED,5674); player:addFame(BASTOK,30); player:setVar("TOO_MANY_CHEFS",0); player:completeQuest(BASTOK,TOO_MANY_CHEFS); end end end;
gpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/weapon/melee/sword/sword_lightsaber_obi.lua
1
5132
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_weapon_melee_sword_sword_lightsaber_obi = object_weapon_melee_sword_shared_sword_lightsaber_obi:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/ithorian_male.iff", "object/creature/player/ithorian_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/wookiee_male.iff", "object/creature/player/wookiee_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff" }, -- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK, -- HEAVYLIGHTNINGBEAMATTACK, HEAVYPARTICLEBEAMATTACK, HEAVYROCKETLAUNCHERATTACK, HEAVYLAUNCHERATTACK attackType = MELEEATTACK, -- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, FORCE, LIGHTSABER damageType = LIGHTSABER, -- NONE, LIGHT, MEDIUM, HEAVY armorPiercing = MEDIUM, -- combat_rangedspecialize_bactarifle, combat_rangedspecialize_rifle, combat_rangedspecialize_pistol, combat_rangedspecialize_heavy, combat_rangedspecialize_carbine -- combat_meleespecialize_unarmed, combat_meleespecialize_twohand, combat_meleespecialize_polearm, combat_meleespecialize_onehand, combat_general, -- combat_meleespecialize_twohandlightsaber, combat_meleespecialize_polearmlightsaber, combat_meleespecialize_onehandlightsaber xpType = "combat_meleespecialize_onehandlightsaber", -- See http://www.ocdsoft.com/files/certifications.xls certificationsRequired = { "cert_onehandlightsaber" }, -- See http://www.ocdsoft.com/files/accuracy.xls creatureAccuracyModifiers = { "onehandlightsaber_accuracy" }, -- See http://www.ocdsoft.com/files/defense.xls defenderDefenseModifiers = { "melee_defense" }, -- Leave as "dodge" for now, may have additions later defenderSecondaryDefenseModifiers = { "saber_block" }, defenderToughnessModifiers = { "lightsaber_toughness" }, -- See http://www.ocdsoft.com/files/speed.xls speedModifiers = { "onehandlightsaber_speed" }, -- Leave blank for now damageModifiers = { }, -- The values below are the default values. To be used for blue frog objects primarily healthAttackCost = 20, actionAttackCost = 35, mindAttackCost = 40, forceCost = 15, pointBlankRange = 0, pointBlankAccuracy = 20, idealRange = 3, idealAccuracy = 15, maxRange = 5, maxRangeAccuracy = 5, minDamage = 50, maxDamage = 130, attackSpeed = 4.8, woundsRatio = 15, } ObjectTemplates:addTemplate(object_weapon_melee_sword_sword_lightsaber_obi, "object/weapon/melee/sword/sword_lightsaber_obi.iff")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/commands/melee1hSpinAttack1.lua
2
2475
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. --true = 1, false = 0 Melee1hSpinAttack1Command = { name = "melee1hspinattack1", damageMultiplier = 2.0, speedMultiplier = 1.5, healthCostMultiplier = 1.0, actionCostMultiplier = 1.0, mindCostMultiplier = 1.5, accuracyBonus = 25, animationCRC = hashCode("attack_high_right_medium_2"), combatSpam = "slashspin", weaponType = ONEHANDMELEEWEAPON, areaAction = true, areaRange = 16, range = -1 } AddCommand(Melee1hSpinAttack1Command)
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/weapon/melee/special/objects.lua
3
6053
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. object_weapon_melee_special_shared_blacksun_razor = SharedWeaponObjectTemplate:new { clientTemplateFileName = "object/weapon/melee/special/shared_blacksun_razor.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/wp_sp_blacksun_knuckler.apt", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/hold_r.iff", attackType = 1, certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "clientdata/weapon/client_melee_knuckler.cdf", clientGameObjectType = 131073, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 1, containerVolumeLimit = 0, customizationVariableMapping = {}, detailedDescription = "@weapon_detail:blacksun_razor", gameObjectType = 131073, locationReservationRadius = 0, lookAtText = "@weapon_lookat:blacksun_razor", noBuildRadius = 0, objectName = "@weapon_name:blacksun_razor", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/default_weapon.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, weaponEffect = "bolt", weaponEffectIndex = 0, clientObjectCRC = 3357199743, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/weapon/base/shared_base_weapon.iff", "object/weapon/melee/base/shared_base_melee.iff"} ]] } ObjectTemplates:addClientTemplate(object_weapon_melee_special_shared_blacksun_razor, "object/weapon/melee/special/shared_blacksun_razor.iff") object_weapon_melee_special_shared_vibroknuckler = SharedWeaponObjectTemplate:new { clientTemplateFileName = "object/weapon/melee/special/shared_vibroknuckler.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/wp_sp_vibroknuckler.apt", arrangementDescriptorFilename = "abstract/slot/arrangement/wearables/hold_r.iff", attackType = 1, certificationsRequired = {}, clearFloraRadius = 0, clientDataFile = "clientdata/weapon/client_melee_knuckler.cdf", clientGameObjectType = 131073, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 1, containerVolumeLimit = 0, customizationVariableMapping = {}, detailedDescription = "@weapon_detail:vibroknuckler", gameObjectType = 131073, locationReservationRadius = 0, lookAtText = "@weapon_lookat:vibroknuckler", noBuildRadius = 0, objectName = "@weapon_name:vibroknuckler", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/default_weapon.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "", surfaceType = 0, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, weaponEffect = "bolt", weaponEffectIndex = 0, clientObjectCRC = 1697024206, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/weapon/base/shared_base_weapon.iff", "object/weapon/melee/base/shared_base_melee.iff"} ]] } ObjectTemplates:addClientTemplate(object_weapon_melee_special_shared_vibroknuckler, "object/weapon/melee/special/shared_vibroknuckler.iff")
agpl-3.0
Whitechaser/darkstar
scripts/globals/spells/bluemagic/head_butt.lua
2
2176
----------------------------------------- -- Spell: Head Butt -- Damage varies with TP. Additional effect: "Stun" -- Spell cost: 12 MP -- Monster Type: Beastmen -- Spell Type: Physical (Blunt) -- Blue Magic Points: 3 -- Stat Bonus: DEX+2 -- Level: 12 -- Casting Time: 0.5 seconds -- Recast Time: 10 seconds -- Skillchain Element(s): Lightning (can open Liquefaction or Detonation; can close Impaction or Fusion) -- Combos: None ----------------------------------------- require("scripts/globals/bluemagic"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local params = {}; params.diff = nil; params.attribute = MOD_INT; params.skillType = SKILL_BLU; params.bonus = 0; params.effect = dsp.effects.STUN; local resist = applyResistanceEffect(caster, target, spell, params) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_DAMAGE; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_IMPACTION; params.numhits = 1; params.multiplier = 1.75; params.tp150 = 2.125; params.tp300 = 2.25; params.azuretp = 2.375; params.duppercap = 17; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; local damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (resist > 0.25) then -- This line may need adjusting for retail accuracy. target:addStatusEffect(dsp.effects.STUN, 1, 0, 5 * resist); end return damage; end;
gpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/tangible/ship/components/engine/eng_haor_chall_old_engine.lua
3
2316
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_ship_components_engine_eng_haor_chall_old_engine = object_tangible_ship_components_engine_shared_eng_haor_chall_old_engine:new { } ObjectTemplates:addTemplate(object_tangible_ship_components_engine_eng_haor_chall_old_engine, "object/tangible/ship/components/engine/eng_haor_chall_old_engine.iff")
agpl-3.0
Whitechaser/darkstar
scripts/zones/Windurst_Waters/npcs/Fomina.lua
5
1378
----------------------------------- -- Area: Windurst Waters -- NPC: Fomina -- Only sells when Windurst controlls Elshimo Lowlands -- Confirmed shop stock, August 2013 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/conquest"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local RegionOwner = GetRegionOwner(ELSHIMOLOWLANDS); if (RegionOwner ~= NATION_WINDURST) then player:showText(npc,FOMINA_CLOSED_DIALOG); else player:showText(npc,FOMINA_OPEN_DIALOG); local stock = { 612, 55, -- Kazham Peppers 4432, 55, -- Kazham Pineapple 4390, 36, -- Mithran Tomato 626, 234, -- Black Pepper 630, 88, -- Ogre Pumpkin 632, 110, -- Kukuru Bean 1411, 1656 -- Phalaenopsis } showShop(player,WINDURST,stock); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Whitechaser/darkstar
scripts/zones/Palborough_Mines/npcs/Old_Toolbox.lua
5
1066
----------------------------------- -- Area: Palborough Mines -- NPC: Old Toolbox -- Continues Quest: The Eleventh's Hour ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Palborough_Mines/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,THE_ELEVENTH_S_HOUR) == QUEST_ACCEPTED and player:hasKeyItem(OLD_TOOLBOX) == false) then player:startEvent(23); else player:startEvent(22); end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); if (csid == 23 and option == 0) then player:addKeyItem(OLD_TOOLBOX); end end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/tangible/ship/components/weapon/wpn_sfs_imperial_blaster_2.lua
3
2320
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_ship_components_weapon_wpn_sfs_imperial_blaster_2 = object_tangible_ship_components_weapon_shared_wpn_sfs_imperial_blaster_2:new { } ObjectTemplates:addTemplate(object_tangible_ship_components_weapon_wpn_sfs_imperial_blaster_2, "object/tangible/ship/components/weapon/wpn_sfs_imperial_blaster_2.iff")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/mobile/bol.lua
3
2128
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_mobile_bol = object_mobile_shared_bol:new { } ObjectTemplates:addTemplate(object_mobile_bol, "object/mobile/bol.iff")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/tangible/food/crafted/drink_ruby_bliel.lua
3
3367
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_food_crafted_drink_ruby_bliel = object_tangible_food_crafted_shared_drink_ruby_bliel:new { templateType = CONSUMABLE, duration = 17, filling = 10, nutrition = 10, effectType = 3, -- Event Based Buff eventTypes = {MEDPACKUSED}, fillingMin = 22, fillingMax = 18, flavorMin = 12, flavorMax = 22, nutritionMin = 20, nutritionMax = 35, quantityMin = 4, quantityMax = 5, modifiers = { "heal_recovery", 0 }, buffName = "food.heal_recovery", buffCRC = 0, speciesRestriction = "", numberExperimentalProperties = {1, 1, 1, 1, 2, 2, 2, 2, 1}, experimentalProperties = {"XX", "XX", "XX", "XX", "OQ", "PE", "DR", "FL", "DR", "PE", "DR", "OQ", "XX"}, experimentalWeights = {1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 3, 1, 1}, experimentalGroupTitles = {"null", "null", "null", "null", "exp_nutrition", "exp_flavor", "exp_quantity", "exp_filling", "null"}, experimentalSubGroupTitles = {"null", "null", "hitpoints", "quantity_bonus", "nutrition", "flavor", "quantity", "filling", "stomach"}, experimentalMin = {0, 0, 1000, 0, 75, 60, 60, 80, 1}, experimentalMax = {0, 0, 1000, 0, 120, 120, 100, 120, 1}, experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0, 0}, experimentalCombineType = {0, 0, 4, 1, 1, 1, 1, 1, 1}, } ObjectTemplates:addTemplate(object_tangible_food_crafted_drink_ruby_bliel, "object/tangible/food/crafted/drink_ruby_bliel.iff")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/building/naboo/filler_building_naboo_style_4.lua
3
2264
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_building_naboo_filler_building_naboo_style_4 = object_building_naboo_shared_filler_building_naboo_style_4:new { } ObjectTemplates:addTemplate(object_building_naboo_filler_building_naboo_style_4, "object/building/naboo/filler_building_naboo_style_4.iff")
agpl-3.0
DailyShana/ygopro-scripts
c39701395.lua
9
1096
--調和の宝札 function c39701395.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DRAW) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c39701395.cost) e1:SetTarget(c39701395.target) e1:SetOperation(c39701395.activate) c:RegisterEffect(e1) end function c39701395.filter(c) return c:IsType(TYPE_TUNER) and c:IsRace(RACE_DRAGON) and c:IsAttackBelow(1000) and c:IsDiscardable() end function c39701395.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c39701395.filter,tp,LOCATION_HAND,0,1,nil) end Duel.DiscardHand(tp,c39701395.filter,1,1,REASON_COST+REASON_DISCARD) end function c39701395.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,2) end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(2) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2) end function c39701395.activate(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) end
gpl-2.0
Qihoo360/nginx-openresty-windows
luajit-root-x64/luajit/share/luajit-2.1.0-alpha/jit/vmdef.lua
18
7301
-- This is a generated file. DO NOT EDIT! return { bcnames = "ISLT ISGE ISLE ISGT ISEQV ISNEV ISEQS ISNES ISEQN ISNEN ISEQP ISNEP ISTC ISFC IST ISF ISTYPEISNUM MOV NOT UNM LEN ADDVN SUBVN MULVN DIVVN MODVN ADDNV SUBNV MULNV DIVNV MODNV ADDVV SUBVV MULVV DIVVV MODVV POW CAT KSTR KCDATAKSHORTKNUM KPRI KNIL UGET USETV USETS USETN USETP UCLO FNEW TNEW TDUP GGET GSET TGETV TGETS TGETB TGETR TSETV TSETS TSETB TSETM TSETR CALLM CALL CALLMTCALLT ITERC ITERN VARG ISNEXTRETM RET RET0 RET1 FORI JFORI FORL IFORL JFORL ITERL IITERLJITERLLOOP ILOOP JLOOP JMP FUNCF IFUNCFJFUNCFFUNCV IFUNCVJFUNCVFUNCC FUNCCW", irnames = "LT GE LE GT ULT UGE ULE UGT EQ NE ABC RETF NOP BASE PVAL GCSTEPHIOP LOOP USE PHI RENAMEPROF KPRI KINT KGC KPTR KKPTR KNULL KNUM KINT64KSLOT BNOT BSWAP BAND BOR BXOR BSHL BSHR BSAR BROL BROR ADD SUB MUL DIV MOD POW NEG ABS ATAN2 LDEXP MIN MAX FPMATHADDOV SUBOV MULOV AREF HREFK HREF NEWREFUREFO UREFC FREF STRREFLREF ALOAD HLOAD ULOAD FLOAD XLOAD SLOAD VLOAD ASTOREHSTOREUSTOREFSTOREXSTORESNEW XSNEW TNEW TDUP CNEW CNEWI BUFHDRBUFPUTBUFSTRTBAR OBAR XBAR CONV TOBIT TOSTR STRTO CALLN CALLA CALLL CALLS CALLXSCARG ", irfpm = { [0]="floor", "ceil", "trunc", "sqrt", "exp", "exp2", "log", "log2", "log10", "sin", "cos", "tan", "other", }, irfield = { [0]="str.len", "func.env", "func.pc", "thread.env", "tab.meta", "tab.array", "tab.node", "tab.asize", "tab.hmask", "tab.nomm", "udata.meta", "udata.udtype", "udata.file", "cdata.ctypeid", "cdata.ptr", "cdata.int", "cdata.int64", "cdata.int64_4", }, ircall = { [0]="lj_str_cmp", "lj_str_find", "lj_str_new", "lj_strscan_num", "lj_strfmt_int", "lj_strfmt_num", "lj_strfmt_char", "lj_strfmt_putint", "lj_strfmt_putnum", "lj_strfmt_putquoted", "lj_strfmt_putfxint", "lj_strfmt_putfnum_int", "lj_strfmt_putfnum_uint", "lj_strfmt_putfnum", "lj_strfmt_putfstr", "lj_strfmt_putfchar", "lj_buf_putmem", "lj_buf_putstr", "lj_buf_putchar", "lj_buf_putstr_reverse", "lj_buf_putstr_lower", "lj_buf_putstr_upper", "lj_buf_putstr_rep", "lj_buf_puttab", "lj_buf_tostr", "lj_tab_new_ah", "lj_tab_new1", "lj_tab_dup", "lj_tab_clear", "lj_tab_newkey", "lj_tab_len", "lj_gc_step_jit", "lj_gc_barrieruv", "lj_mem_newgco", "lj_math_random_step", "lj_vm_modi", "sinh", "cosh", "tanh", "fputc", "fwrite", "fflush", "lj_vm_floor", "lj_vm_ceil", "lj_vm_trunc", "sqrt", "exp", "lj_vm_exp2", "log", "lj_vm_log2", "log10", "sin", "cos", "tan", "lj_vm_powi", "pow", "atan2", "ldexp", "lj_vm_tobit", "softfp_add", "softfp_sub", "softfp_mul", "softfp_div", "softfp_cmp", "softfp_i2d", "softfp_d2i", "softfp_ui2d", "softfp_f2d", "softfp_d2ui", "softfp_d2f", "softfp_i2f", "softfp_ui2f", "softfp_f2i", "softfp_f2ui", "fp64_l2d", "fp64_ul2d", "fp64_l2f", "fp64_ul2f", "fp64_d2l", "fp64_d2ul", "fp64_f2l", "fp64_f2ul", "lj_carith_divi64", "lj_carith_divu64", "lj_carith_modi64", "lj_carith_modu64", "lj_carith_powi64", "lj_carith_powu64", "lj_cdata_newv", "lj_cdata_setfin", "strlen", "memcpy", "memset", "lj_vm_errno", "lj_carith_mul64", "lj_carith_shl64", "lj_carith_shr64", "lj_carith_sar64", "lj_carith_rol64", "lj_carith_ror64", }, traceerr = { [0]="error thrown or hook called during recording", "trace too long", "trace too deep", "too many snapshots", "blacklisted", "NYI: bytecode %d", "leaving loop in root trace", "inner loop in root trace", "loop unroll limit reached", "bad argument type", "JIT compilation disabled for function", "call unroll limit reached", "down-recursion, restarting", "NYI: C function %p", "NYI: FastFunc %s", "NYI: unsupported variant of FastFunc %s", "NYI: return to lower frame", "store with nil or NaN key", "missing metamethod", "looping index lookup", "NYI: mixed sparse/dense table", "symbol not in cache", "NYI: unsupported C type conversion", "NYI: unsupported C function type", "guard would always fail", "too many PHIs", "persistent type instability", "failed to allocate mcode memory", "machine code too long", "hit mcode limit (retrying)", "too many spill slots", "inconsistent register allocation", "NYI: cannot assemble IR instruction %d", "NYI: PHI shuffling too complex", "NYI: register coalescing too complex", }, ffnames = { [0]="Lua", "C", "assert", "type", "next", "pairs", "ipairs_aux", "ipairs", "getmetatable", "setmetatable", "getfenv", "setfenv", "rawget", "rawset", "rawequal", "unpack", "select", "tonumber", "tostring", "error", "pcall", "xpcall", "loadfile", "load", "loadstring", "dofile", "gcinfo", "collectgarbage", "newproxy", "print", "coroutine.status", "coroutine.running", "coroutine.create", "coroutine.yield", "coroutine.resume", "coroutine.wrap_aux", "coroutine.wrap", "math.abs", "math.floor", "math.ceil", "math.sqrt", "math.log10", "math.exp", "math.sin", "math.cos", "math.tan", "math.asin", "math.acos", "math.atan", "math.sinh", "math.cosh", "math.tanh", "math.frexp", "math.modf", "math.log", "math.atan2", "math.pow", "math.fmod", "math.ldexp", "math.min", "math.max", "math.random", "math.randomseed", "bit.tobit", "bit.bnot", "bit.bswap", "bit.lshift", "bit.rshift", "bit.arshift", "bit.rol", "bit.ror", "bit.band", "bit.bor", "bit.bxor", "bit.tohex", "string.byte", "string.char", "string.sub", "string.rep", "string.reverse", "string.lower", "string.upper", "string.dump", "string.find", "string.match", "string.gmatch_aux", "string.gmatch", "string.gsub", "string.format", "table.maxn", "table.insert", "table.concat", "table.sort", "table.new", "table.clear", "io.method.close", "io.method.read", "io.method.write", "io.method.flush", "io.method.seek", "io.method.setvbuf", "io.method.lines", "io.method.__gc", "io.method.__tostring", "io.open", "io.popen", "io.tmpfile", "io.close", "io.read", "io.write", "io.flush", "io.input", "io.output", "io.lines", "io.type", "os.execute", "os.remove", "os.rename", "os.tmpname", "os.getenv", "os.exit", "os.clock", "os.date", "os.time", "os.difftime", "os.setlocale", "debug.getregistry", "debug.getmetatable", "debug.setmetatable", "debug.getfenv", "debug.setfenv", "debug.getinfo", "debug.getlocal", "debug.setlocal", "debug.getupvalue", "debug.setupvalue", "debug.upvalueid", "debug.upvaluejoin", "debug.sethook", "debug.gethook", "debug.debug", "debug.traceback", "jit.on", "jit.off", "jit.flush", "jit.status", "jit.attach", "jit.util.funcinfo", "jit.util.funcbc", "jit.util.funck", "jit.util.funcuvname", "jit.util.traceinfo", "jit.util.traceir", "jit.util.tracek", "jit.util.tracesnap", "jit.util.tracemc", "jit.util.traceexitstub", "jit.util.ircalladdr", "jit.opt.start", "jit.profile.start", "jit.profile.stop", "jit.profile.dumpstack", "ffi.meta.__index", "ffi.meta.__newindex", "ffi.meta.__eq", "ffi.meta.__len", "ffi.meta.__lt", "ffi.meta.__le", "ffi.meta.__concat", "ffi.meta.__call", "ffi.meta.__add", "ffi.meta.__sub", "ffi.meta.__mul", "ffi.meta.__div", "ffi.meta.__mod", "ffi.meta.__pow", "ffi.meta.__unm", "ffi.meta.__tostring", "ffi.meta.__pairs", "ffi.meta.__ipairs", "ffi.clib.__index", "ffi.clib.__newindex", "ffi.clib.__gc", "ffi.callback.free", "ffi.callback.set", "ffi.cdef", "ffi.new", "ffi.cast", "ffi.typeof", "ffi.istype", "ffi.sizeof", "ffi.alignof", "ffi.offsetof", "ffi.errno", "ffi.string", "ffi.copy", "ffi.fill", "ffi.abi", "ffi.metatype", "ffi.gc", "ffi.load", }, }
bsd-2-clause
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/weapon/ranged/pistol/pistol_srcombat.lua
2
6211
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_weapon_ranged_pistol_pistol_srcombat = object_weapon_ranged_pistol_shared_pistol_srcombat:new { playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/ithorian_male.iff", "object/creature/player/ithorian_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/wookiee_male.iff", "object/creature/player/wookiee_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff" }, -- RANGEDATTACK, MELEEATTACK, FORCEATTACK, TRAPATTACK, GRENADEATTACK, HEAVYACIDBEAMATTACK, -- HEAVYLIGHTNINGBEAMATTACK, HEAVYPARTICLEBEAMATTACK, HEAVYROCKETLAUNCHERATTACK, HEAVYLAUNCHERATTACK attackType = RANGEDATTACK, -- ENERGY, KINETIC, ELECTRICITY, STUN, BLAST, HEAT, COLD, ACID, FORCE, LIGHTSABER damageType = ENERGY, -- NONE, LIGHT, MEDIUM, HEAVY armorPiercing = LIGHT, -- combat_rangedspecialize_bactarifle, combat_rangedspecialize_rifle, combat_rangedspecialize_pistol, combat_rangedspecialize_heavy, combat_rangedspecialize_carbine -- combat_meleespecialize_unarmed, combat_meleespecialize_twohand, combat_meleespecialize_polearm, combat_meleespecialize_onehand, combat_general, -- combat_meleespecialize_twohandlightsaber, combat_meleespecialize_polearmlightsaber, combat_meleespecialize_onehandlightsaber xpType = "combat_rangedspecialize_pistol", -- See http://www.ocdsoft.com/files/certifications.xls certificationsRequired = { "cert_pistol_srcombat" }, -- See http://www.ocdsoft.com/files/accuracy.xls creatureAccuracyModifiers = { "pistol_accuracy" }, creatureAimModifiers = { "pistol_aim", "aim" }, -- See http://www.ocdsoft.com/files/defense.xls defenderDefenseModifiers = { "ranged_defense" }, -- Leave as "dodge" for now, may have additions later defenderSecondaryDefenseModifiers = { "dodge" }, -- See http://www.ocdsoft.com/files/speed.xls speedModifiers = { "pistol_speed" }, -- Leave blank for now damageModifiers = { }, -- The values below are the default values. To be used for blue frog objects primarily healthAttackCost = 23, actionAttackCost = 36, mindAttackCost = 13, forceCost = 0, pointBlankRange = 0, pointBlankAccuracy = 5, idealRange = 12, idealAccuracy = -20, maxRange = 48, maxRangeAccuracy = -80, minDamage = 45, maxDamage = 100, attackSpeed = 3.75, woundsRatio = 13, numberExperimentalProperties = {1, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2, 2}, experimentalProperties = {"XX", "XX", "CD", "OQ", "CD", "OQ", "CD", "OQ", "CD", "OQ", "CD", "OQ", "CD", "OQ", "CD", "OQ", "XX", "XX", "CD", "OQ", "CD", "OQ", "CD", "OQ", "CD", "OQ"}, experimentalWeights = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, experimentalGroupTitles = {"null", "null", "expDamage", "expDamage", "expDamage", "expDamage", "expEffeciency", "exp_durability", "expRange", "null", "null", "null", "expEffeciency", "expEffeciency", "expEffeciency"}, experimentalSubGroupTitles = {"null", "null", "mindamage", "maxdamage", "attackspeed", "woundchance", "roundsused", "hitpoints", "zerorangemod", "maxrangemod", "midrange", "midrangemod", "attackhealthcost", "attackactioncost", "attackmindcost"}, experimentalMin = {0, 0, 32, 70, 4.9, 9, 5, 750, 0, -80, 12, -20, 30, 47, 17}, experimentalMax = {0, 0, 59, 130, 3.8, 17, 20, 1500, 10, -80, 12, -20, 16, 25, 9}, experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, experimentalCombineType = {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, } ObjectTemplates:addTemplate(object_weapon_ranged_pistol_pistol_srcombat, "object/weapon/ranged/pistol/pistol_srcombat.iff")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/tangible/component/bio/bio_component_clothing_casual_entertainer.lua
3
3159
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_component_bio_bio_component_clothing_casual_entertainer = object_tangible_component_bio_shared_bio_component_clothing_casual_entertainer:new { numberExperimentalProperties = {1, 1, 1, 1, 1, 3, 1, 3}, experimentalProperties = {"XX", "XX", "XX", "XX", "XX", "FL", "OQ", "PE", "XX", "FL", "OQ", "PE"}, experimentalWeights = {1, 1, 1, 1, 1, 2, 5, 3, 1, 2, 5, 3}, experimentalGroupTitles = {"null", "null", "null", "null", "null", "exp_effectiveness", "null", "exp_effectiveness"}, experimentalSubGroupTitles = {"null", "null", "decayrate", "hitpoints", "@obj_attr_n:bio_comp_healing_dance_wound", "cat_skill_mod_bonus.@stat_n:healing_dance_wound", "@obj_attr_n:bio_comp_healing_music_wound", "cat_skill_mod_bonus.@stat_n:healing_music_wound"}, experimentalMin = {0, 0, 30, 1000, 108, 1, 109, 1}, experimentalMax = {0, 0, 50, 1000, 108, 10, 109, 10}, experimentalPrecision = {0, 0, 0, 0, 0, 0, 0, 0}, experimentalCombineType = {0, 0, 1, 4, 1, 1, 1, 1}, } ObjectTemplates:addTemplate(object_tangible_component_bio_bio_component_clothing_casual_entertainer, "object/tangible/component/bio/bio_component_clothing_casual_entertainer.iff")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/mobile/falumpaset_hue.lua
3
2172
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_mobile_falumpaset_hue = object_mobile_shared_falumpaset_hue:new { } ObjectTemplates:addTemplate(object_mobile_falumpaset_hue, "object/mobile/falumpaset_hue.iff")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/draft_schematic/item/objects.lua
3
105107
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. object_draft_schematic_item_shared_craftable_bug_habitat = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_craftable_bug_habitat.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3662038442, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_craftable_bug_habitat, "object/draft_schematic/item/shared_craftable_bug_habitat.iff") object_draft_schematic_item_shared_item_agitator_motor = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_agitator_motor.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3332388159, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_agitator_motor, "object/draft_schematic/item/shared_item_agitator_motor.iff") object_draft_schematic_item_shared_item_ballot_box_terminal = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_ballot_box_terminal.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2213189419, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_ballot_box_terminal, "object/draft_schematic/item/shared_item_ballot_box_terminal.iff") object_draft_schematic_item_shared_item_base_tool = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_base_tool.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3261161372, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_base_tool, "object/draft_schematic/item/shared_item_base_tool.iff") object_draft_schematic_item_shared_item_battery_droid = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_battery_droid.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3508567807, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff", "object/draft_schematic/item/shared_item_base_tool.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_battery_droid, "object/draft_schematic/item/shared_item_battery_droid.iff") object_draft_schematic_item_shared_item_chance_cube = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_chance_cube.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3203266155, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_chance_cube, "object/draft_schematic/item/shared_item_chance_cube.iff") object_draft_schematic_item_shared_item_clothing_station = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_clothing_station.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1775090103, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_clothing_station, "object/draft_schematic/item/shared_item_clothing_station.iff") object_draft_schematic_item_shared_item_clothing_tool = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_clothing_tool.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1505349903, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_clothing_tool, "object/draft_schematic/item/shared_item_clothing_tool.iff") object_draft_schematic_item_shared_item_configurable_sided_dice = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_configurable_sided_dice.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1370957893, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_configurable_sided_dice, "object/draft_schematic/item/shared_item_configurable_sided_dice.iff") object_draft_schematic_item_shared_item_firework_eighteen = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_firework_eighteen.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3660502688, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_firework_eighteen, "object/draft_schematic/item/shared_item_firework_eighteen.iff") object_draft_schematic_item_shared_item_firework_eleven = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_firework_eleven.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2713986341, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_firework_eleven, "object/draft_schematic/item/shared_item_firework_eleven.iff") object_draft_schematic_item_shared_item_firework_five = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_firework_five.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 879669640, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_firework_five, "object/draft_schematic/item/shared_item_firework_five.iff") object_draft_schematic_item_shared_item_firework_four = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_firework_four.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3323326153, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_firework_four, "object/draft_schematic/item/shared_item_firework_four.iff") object_draft_schematic_item_shared_item_firework_one = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_firework_one.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2052759177, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_firework_one, "object/draft_schematic/item/shared_item_firework_one.iff") object_draft_schematic_item_shared_item_firework_show = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_firework_show.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2196218270, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_firework_show, "object/draft_schematic/item/shared_item_firework_show.iff") object_draft_schematic_item_shared_item_firework_ten = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_firework_ten.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1345222985, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_firework_ten, "object/draft_schematic/item/shared_item_firework_ten.iff") object_draft_schematic_item_shared_item_firework_three = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_firework_three.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1853917921, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_firework_three, "object/draft_schematic/item/shared_item_firework_three.iff") object_draft_schematic_item_shared_item_firework_two = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_firework_two.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2570243587, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_firework_two, "object/draft_schematic/item/shared_item_firework_two.iff") object_draft_schematic_item_shared_item_fishing_pole = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_fishing_pole.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 4197036370, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_fishing_pole, "object/draft_schematic/item/shared_item_fishing_pole.iff") object_draft_schematic_item_shared_item_food_station = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_food_station.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 697822739, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_food_station, "object/draft_schematic/item/shared_item_food_station.iff") object_draft_schematic_item_shared_item_food_tool = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_food_tool.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1492600411, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_food_tool, "object/draft_schematic/item/shared_item_food_tool.iff") object_draft_schematic_item_shared_item_generic_tool = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_generic_tool.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2914524854, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_generic_tool, "object/draft_schematic/item/shared_item_generic_tool.iff") object_draft_schematic_item_shared_item_hundred_sided_dice = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_hundred_sided_dice.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 292809069, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_hundred_sided_dice, "object/draft_schematic/item/shared_item_hundred_sided_dice.iff") object_draft_schematic_item_shared_item_jedi_tool = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_jedi_tool.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3722220294, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_jedi_tool, "object/draft_schematic/item/shared_item_jedi_tool.iff") object_draft_schematic_item_shared_item_parrot_cage = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_parrot_cage.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2785425064, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_parrot_cage, "object/draft_schematic/item/shared_item_parrot_cage.iff") object_draft_schematic_item_shared_item_powerup_weapon_melee_generic = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_melee_generic.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 247131041, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_melee_generic, "object/draft_schematic/item/shared_item_powerup_weapon_melee_generic.iff") object_draft_schematic_item_shared_item_powerup_weapon_melee_lightsaber = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_melee_lightsaber.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 964828866, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_melee_lightsaber, "object/draft_schematic/item/shared_item_powerup_weapon_melee_lightsaber.iff") object_draft_schematic_item_shared_item_powerup_weapon_mine_explosive = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_mine_explosive.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 797092971, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_mine_explosive, "object/draft_schematic/item/shared_item_powerup_weapon_mine_explosive.iff") object_draft_schematic_item_shared_item_powerup_weapon_ranged_five = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_ranged_five.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1412684588, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_ranged_five, "object/draft_schematic/item/shared_item_powerup_weapon_ranged_five.iff") object_draft_schematic_item_shared_item_powerup_weapon_ranged_four = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_ranged_four.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2789770349, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_ranged_four, "object/draft_schematic/item/shared_item_powerup_weapon_ranged_four.iff") object_draft_schematic_item_shared_item_powerup_weapon_ranged_one = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_ranged_one.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 926910485, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_ranged_one, "object/draft_schematic/item/shared_item_powerup_weapon_ranged_one.iff") object_draft_schematic_item_shared_item_powerup_weapon_ranged_six = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_ranged_six.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1911715488, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_ranged_six, "object/draft_schematic/item/shared_item_powerup_weapon_ranged_six.iff") object_draft_schematic_item_shared_item_powerup_weapon_ranged_three = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_ranged_three.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2672814198, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_ranged_three, "object/draft_schematic/item/shared_item_powerup_weapon_ranged_three.iff") object_draft_schematic_item_shared_item_powerup_weapon_ranged_two = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_ranged_two.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3562526879, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_ranged_two, "object/draft_schematic/item/shared_item_powerup_weapon_ranged_two.iff") object_draft_schematic_item_shared_item_powerup_weapon_thrown_explosive = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_thrown_explosive.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3975490857, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_thrown_explosive, "object/draft_schematic/item/shared_item_powerup_weapon_thrown_explosive.iff") object_draft_schematic_item_shared_item_powerup_weapon_thrown_wiring = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_powerup_weapon_thrown_wiring.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2101449408, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_powerup_weapon_thrown_wiring, "object/draft_schematic/item/shared_item_powerup_weapon_thrown_wiring.iff") object_draft_schematic_item_shared_item_public_clothing_station = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_public_clothing_station.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 860687270, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_public_clothing_station, "object/draft_schematic/item/shared_item_public_clothing_station.iff") object_draft_schematic_item_shared_item_public_food_station = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_public_food_station.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 925875807, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_public_food_station, "object/draft_schematic/item/shared_item_public_food_station.iff") object_draft_schematic_item_shared_item_public_structure_station = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_public_structure_station.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1326594481, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_public_structure_station, "object/draft_schematic/item/shared_item_public_structure_station.iff") object_draft_schematic_item_shared_item_public_weapon_station = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_public_weapon_station.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2519720442, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_public_weapon_station, "object/draft_schematic/item/shared_item_public_weapon_station.iff") object_draft_schematic_item_shared_item_recycler_chemical = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_recycler_chemical.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 780076423, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_recycler_chemical, "object/draft_schematic/item/shared_item_recycler_chemical.iff") object_draft_schematic_item_shared_item_recycler_creature = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_recycler_creature.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2037307449, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_recycler_creature, "object/draft_schematic/item/shared_item_recycler_creature.iff") object_draft_schematic_item_shared_item_recycler_flora = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_recycler_flora.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 134662469, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_recycler_flora, "object/draft_schematic/item/shared_item_recycler_flora.iff") object_draft_schematic_item_shared_item_recycler_metal = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_recycler_metal.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3962708535, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_recycler_metal, "object/draft_schematic/item/shared_item_recycler_metal.iff") object_draft_schematic_item_shared_item_recycler_ore = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_recycler_ore.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2090788459, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_recycler_ore, "object/draft_schematic/item/shared_item_recycler_ore.iff") object_draft_schematic_item_shared_item_repairkit_armor = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_repairkit_armor.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1371712760, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff", "object/draft_schematic/item/shared_item_base_tool.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_repairkit_armor, "object/draft_schematic/item/shared_item_repairkit_armor.iff") object_draft_schematic_item_shared_item_repairkit_clothing = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_repairkit_clothing.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2082185823, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff", "object/draft_schematic/item/shared_item_base_tool.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_repairkit_clothing, "object/draft_schematic/item/shared_item_repairkit_clothing.iff") object_draft_schematic_item_shared_item_repairkit_droid = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_repairkit_droid.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2481009784, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff", "object/draft_schematic/item/shared_item_base_tool.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_repairkit_droid, "object/draft_schematic/item/shared_item_repairkit_droid.iff") object_draft_schematic_item_shared_item_repairkit_structure = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_repairkit_structure.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3616819013, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff", "object/draft_schematic/item/shared_item_base_tool.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_repairkit_structure, "object/draft_schematic/item/shared_item_repairkit_structure.iff") object_draft_schematic_item_shared_item_repairkit_weapon = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_repairkit_weapon.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1278219253, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff", "object/draft_schematic/item/shared_item_base_tool.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_repairkit_weapon, "object/draft_schematic/item/shared_item_repairkit_weapon.iff") object_draft_schematic_item_shared_item_shellfish_harvester = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_shellfish_harvester.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1302103457, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_shellfish_harvester, "object/draft_schematic/item/shared_item_shellfish_harvester.iff") object_draft_schematic_item_shared_item_six_sided_dice = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_six_sided_dice.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2953774166, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_six_sided_dice, "object/draft_schematic/item/shared_item_six_sided_dice.iff") object_draft_schematic_item_shared_item_space_station = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_space_station.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1829585398, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_space_station, "object/draft_schematic/item/shared_item_space_station.iff") object_draft_schematic_item_shared_item_space_tool = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_space_tool.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 245803278, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_space_tool, "object/draft_schematic/item/shared_item_space_tool.iff") object_draft_schematic_item_shared_item_structure_station = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_structure_station.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2562544992, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_structure_station, "object/draft_schematic/item/shared_item_structure_station.iff") object_draft_schematic_item_shared_item_structure_tool = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_structure_tool.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1567438265, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_structure_tool, "object/draft_schematic/item/shared_item_structure_tool.iff") object_draft_schematic_item_shared_item_survey_tool_flora = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_survey_tool_flora.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1375088999, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_survey_tool_flora, "object/draft_schematic/item/shared_item_survey_tool_flora.iff") object_draft_schematic_item_shared_item_survey_tool_gas = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_survey_tool_gas.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 256520291, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_survey_tool_gas, "object/draft_schematic/item/shared_item_survey_tool_gas.iff") object_draft_schematic_item_shared_item_survey_tool_liquid = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_survey_tool_liquid.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 780227147, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_survey_tool_liquid, "object/draft_schematic/item/shared_item_survey_tool_liquid.iff") object_draft_schematic_item_shared_item_survey_tool_mineral = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_survey_tool_mineral.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1449938755, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_survey_tool_mineral, "object/draft_schematic/item/shared_item_survey_tool_mineral.iff") object_draft_schematic_item_shared_item_survey_tool_moisture = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_survey_tool_moisture.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3420859733, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_survey_tool_moisture, "object/draft_schematic/item/shared_item_survey_tool_moisture.iff") object_draft_schematic_item_shared_item_survey_tool_solar = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_survey_tool_solar.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2148903380, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_survey_tool_solar, "object/draft_schematic/item/shared_item_survey_tool_solar.iff") object_draft_schematic_item_shared_item_survey_tool_wind = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_survey_tool_wind.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2695222848, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_survey_tool_wind, "object/draft_schematic/item/shared_item_survey_tool_wind.iff") object_draft_schematic_item_shared_item_ten_sided_dice = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_ten_sided_dice.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 3387294730, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_ten_sided_dice, "object/draft_schematic/item/shared_item_ten_sided_dice.iff") object_draft_schematic_item_shared_item_tumble_blender = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_tumble_blender.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 2328709231, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_tumble_blender, "object/draft_schematic/item/shared_item_tumble_blender.iff") object_draft_schematic_item_shared_item_twelve_sided_dice = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_twelve_sided_dice.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1478333642, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_twelve_sided_dice, "object/draft_schematic/item/shared_item_twelve_sided_dice.iff") object_draft_schematic_item_shared_item_twenty_sided_dice = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_twenty_sided_dice.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 1156487020, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_twenty_sided_dice, "object/draft_schematic/item/shared_item_twenty_sided_dice.iff") object_draft_schematic_item_shared_item_weapon_station = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_weapon_station.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 580576987, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_weapon_station, "object/draft_schematic/item/shared_item_weapon_station.iff") object_draft_schematic_item_shared_item_weapon_tool = SharedDraftSchematicObjectTemplate:new { clientTemplateFileName = "object/draft_schematic/item/shared_item_weapon_tool.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "", arrangementDescriptorFilename = "abstract/slot/arrangement/arrangement_datapad.iff", clearFloraRadius = 0, clientDataFile = "", clientGameObjectType = 2049, collisionActionBlockFlags = 0, collisionActionFlags = 0, collisionActionPassFlags = 0, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 0, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 0, detailedDescription = "string_id_table", gameObjectType = 2049, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "string_id_table", onlyVisibleInTools = 0, portalLayoutFilename = "", scale = 0, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "", snapToTerrain = 0, surfaceType = 0, totalCellNumber = 0, clientObjectCRC = 806231782, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/intangible/base/shared_base_intangible.iff", "object/draft_schematic/base/shared_base_draft_schematic.iff"} ]] } ObjectTemplates:addClientTemplate(object_draft_schematic_item_shared_item_weapon_tool, "object/draft_schematic/item/shared_item_weapon_tool.iff")
agpl-3.0
KingRaptor/Zero-K
units/arm_venom.lua
1
4806
unitDef = { unitname = [[arm_venom]], name = [[Venom]], description = [[Lightning Riot Spider]], acceleration = 0.26, brakeRate = 0.78, buildCostMetal = 200, buildPic = [[arm_venom.png]], canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[38 38 38]], collisionVolumeType = [[ellipsoid]], corpse = [[DEAD]], customParams = { description_fr = [[Araignée à effet de zone EMP]], description_de = [[Unterstützende EMP Spinne]], helptext = [[The Venom is an all-terrain unit designed to paralyze enemies so other units can easily destroy them. It moves particularly fast for a riot unit and in addition to paralysis it does a small amount of damage. Works well in tandem with the Recluse to keep enemies from closing range with the fragile skirmisher.]], helptext_fr = [[Le Venom est une araignée tout terrain rapide spécialement conçue pour paralyser l'ennemi afin que d'autres unités puissent les détruire rapidement et sans risques. Sa faible portée est compensée par son effet de zone pouvant affecter plusieurs unités à proximité de sa cible. Est particulièrement efficace en tandem avec le Recluse ou l'Hermit.]], helptext_de = [[Venom ist eine geländeunabhängige Einheit, welche Gegner paralysieren kann, damit andere Einheiten diese einfach zerstören können. Venom besitzt eine AoE und ist nützlich, um gengerische Schwärme in Schach zu halten.]], aimposoffset = [[0 0 0]], midposoffset = [[0 -6 0]], modelradius = [[19]], }, explodeAs = [[BIG_UNITEX]], footprintX = 3, footprintZ = 3, iconType = [[spiderriotspecial]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 750, maxSlope = 72, maxVelocity = 2.7, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[TKBOT3]], noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE SUB]], objectName = [[venom.s3o]], script = [[arm_venom.lua]], selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:YELLOW_LIGHTNING_MUZZLE]], [[custom:YELLOW_LIGHTNING_GROUNDFLASH]], }, }, sightDistance = 440, trackOffset = 0, trackStrength = 10, trackStretch = 1, trackType = [[ChickenTrackPointyShort]], trackWidth = 54, turnRate = 1600, weapons = { { def = [[spider]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP]], }, }, weaponDefs = { spider = { name = [[Electro-Stunner]], areaOfEffect = 160, collideFriendly = false, craterBoost = 0, craterMult = 0, customParams = { extra_damage = [[18]], light_color = [[0.75 0.75 0.56]], light_radius = 190, }, damage = { default = 600.5, }, duration = 8, explosionGenerator = [[custom:LIGHTNINGPLOSION160AoE]], fireStarter = 0, heightMod = 1, impulseBoost = 0, impulseFactor = 0, intensity = 12, interceptedByShieldType = 1, noSelfDamage = true, paralyzer = true, paralyzeTime = 3, range = 240, reloadtime = 1.75, rgbColor = [[1 1 0.7]], soundStart = [[weapon/lightning_fire]], soundTrigger = true, texture1 = [[lightning]], thickness = 10, turret = true, weaponType = [[LightningCannon]], weaponVelocity = 450, }, }, featureDefs = { DEAD = { blocking = false, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[venom_wreck.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2a.s3o]], }, }, } return lowerkeys({ arm_venom = unitDef })
gpl-2.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/tangible/mission/quest_item/grondorn_muse_q2_needed.lua
3
2292
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_mission_quest_item_grondorn_muse_q2_needed = object_tangible_mission_quest_item_shared_grondorn_muse_q2_needed:new { } ObjectTemplates:addTemplate(object_tangible_mission_quest_item_grondorn_muse_q2_needed, "object/tangible/mission/quest_item/grondorn_muse_q2_needed.iff")
agpl-3.0
DailyShana/ygopro-scripts
c3657444.lua
3
3683
--サイバー・ヴァリー function c3657444.initial_effect(c) --be target local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(3657444,0)) e1:SetCategory(CATEGORY_DRAW) e1:SetCode(EVENT_BE_BATTLE_TARGET) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCost(c3657444.cost1) e1:SetTarget(c3657444.target1) e1:SetOperation(c3657444.operation1) c:RegisterEffect(e1) --draw local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(3657444,1)) e2:SetCategory(CATEGORY_DRAW) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetTarget(c3657444.target2) e2:SetOperation(c3657444.operation2) c:RegisterEffect(e2) --salvage local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(3657444,2)) e3:SetCategory(CATEGORY_TODECK) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_MZONE) e3:SetTarget(c3657444.target3) e3:SetOperation(c3657444.operation3) c:RegisterEffect(e3) end function c3657444.cost1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c3657444.target1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c3657444.operation1(e,tp,eg,ep,ev,re,r,rp) Duel.Draw(tp,1,REASON_EFFECT) Duel.SkipPhase(1-tp,PHASE_BATTLE,RESET_PHASE+PHASE_BATTLE,1) end function c3657444.filter2(c) return c:IsFaceup() and c:IsAbleToRemove() end function c3657444.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and c3657444.filter2(chkc) end if chk==0 then return e:GetHandler():IsAbleToRemove() and Duel.IsPlayerCanDraw(tp,2) and Duel.IsExistingTarget(c3657444.filter2,tp,LOCATION_MZONE,0,1,e:GetHandler()) end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectTarget(tp,c3657444.filter2,tp,LOCATION_MZONE,0,1,1,e:GetHandler()) g:AddCard(e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,2,0,0) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2) end function c3657444.operation2(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsFacedown() or not c:IsRelateToEffect(e) or not tc:IsRelateToEffect(e) then return end local sg=Group.FromCards(c,tc) Duel.Remove(sg,POS_FACEUP,REASON_EFFECT) Duel.BreakEffect() Duel.Draw(tp,2,REASON_EFFECT) end function c3657444.filter3(c) return c:IsAbleToDeck() and not c:IsHasEffect(EFFECT_NECRO_VALLEY) end function c3657444.target3(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemove() and Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,LOCATION_HAND,0,1,nil) and Duel.IsExistingMatchingCard(c3657444.filter3,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,2,0,0) Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,tp,LOCATION_GRAVE) end function c3657444.operation3(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local hg=Duel.SelectMatchingCard(tp,Card.IsAbleToRemove,tp,LOCATION_HAND,0,1,1,nil) if hg:GetCount()>0 then hg:AddCard(c) Duel.Remove(hg,POS_FACEUP,REASON_EFFECT) Duel.BreakEffect() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local gg=Duel.SelectMatchingCard(tp,c3657444.filter3,tp,LOCATION_GRAVE,0,1,1,nil) if gg:GetCount()>0 then Duel.SendtoDeck(gg,nil,0,REASON_EFFECT) Duel.ConfirmCards(1-tp,gg) end end end
gpl-2.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/mobile/faction/imperial/storm_commando.lua
1
1449
storm_commando = Creature:new { objectName = "@mob/creature_names:storm_commando", randomNameType = NAME_STORMTROOPER_TAG, socialGroup = "imperial", faction = "imperial", level = 29, chanceHit = 0.38, damageMin = 300, damageMax = 310, baseXp = 3005, baseHAM = 6100, baseHAMmax = 9900, armor = 0, resists = {20,20,20,30,-1,30,-1,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + KILLER + STALKER, optionsBitmask = 128, diet = HERBIVORE, templates = {"object/mobile/dressed_stormtrooper_white_black.iff"}, lootGroups = { { groups = { {group = "color_crystals", chance = 100000}, {group = "junk", chance = 4700000}, {group = "rifles", chance = 1000000}, {group = "pistols", chance = 1000000}, {group = "melee_weapons", chance = 1000000}, {group = "carbines", chance = 1000000}, {group = "clothing_attachments", chance = 100000}, {group = "armor_attachments", chance = 100000}, {group = "wearables_common", chance = 1000000} } } }, weapons = {"stormtrooper_weapons"}, conversationTemplate = "", reactionStf = "@npc_reaction/stormtrooper", personalityStf = "@hireling/hireling_stormtrooper", attacks = merge(riflemanmaster,carbineermaster,brawlermaster) } CreatureTemplates:addCreatureTemplate(storm_commando, "storm_commando")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/mobile/talus/chunker_bully.lua
1
1779
chunker_bully = Creature:new { objectName = "@mob/creature_names:chunker_bully", randomNameType = NAME_GENERIC_TAG, socialGroup = "chunker", faction = "thug", level = 10, chanceHit = 0.280000, damageMin = 90, damageMax = 110, baseXp = 356, baseHAM = 810, baseHAMmax = 990, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0.000000, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + STALKER, diet = HERBIVORE, templates = {"object/mobile/dressed_mugger.iff", "object/mobile/dressed_robber_human_male_01.iff", "object/mobile/dressed_criminal_thug_zabrak_female_01.iff", "object/mobile/dressed_criminal_thug_aqualish_female_02.iff", "object/mobile/dressed_criminal_thug_aqualish_male_02.iff", "object/mobile/dressed_desperado_bith_female_01.iff", "object/mobile/dressed_criminal_thug_human_female_01.iff", "object/mobile/dressed_goon_twk_female_01.iff", "object/mobile/dressed_criminal_thug_human_male_01.iff", "object/mobile/dressed_robber_twk_female_01.iff", "object/mobile/dressed_villain_trandoshan_male_01.iff", "object/mobile/dressed_desperado_bith_male_01.iff", "object/mobile/dressed_mugger.iff"}, lootGroups = { { groups = { {group = "junk", chance = 1200000}, {group = "rifles", chance = 700000}, {group = "melee_knife", chance = 700000}, {group = "pistols", chance = 700000}, {group = "carbines", chance = 700000}, {group = "chunker_common", chance = 6000000}, } } }, weapons = {"ranged_weapons"}, reactionStf = "@npc_reaction/slang", attacks = merge(marksmannovice,brawlernovice) } CreatureTemplates:addCreatureTemplate(chunker_bully, "chunker_bully")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/mobile/warren_agro_droid_s01.lua
3
2200
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_mobile_warren_agro_droid_s01 = object_mobile_shared_warren_agro_droid_s01:new { } ObjectTemplates:addTemplate(object_mobile_warren_agro_droid_s01, "object/mobile/warren_agro_droid_s01.iff")
agpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/mobile/space_imperial_tier3_yavin.lua
3
2220
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_mobile_space_imperial_tier3_yavin = object_mobile_shared_space_imperial_tier3_yavin:new { } ObjectTemplates:addTemplate(object_mobile_space_imperial_tier3_yavin, "object/mobile/space_imperial_tier3_yavin.iff")
agpl-3.0
Whitechaser/darkstar
scripts/globals/spells/bluemagic/blitzstrahl.lua
2
1987
----------------------------------------- -- Spell: Blitzstrahl -- Deals lightning damage to an enemy. Additional effect: "Stun" -- Spell cost: 70 MP -- Monster Type: Arcana -- Spell Type: Magical (Lightning) -- Blue Magic Points: 4 -- Stat Bonus: DEX+3 -- Level: 44 -- Casting Time: 4.5 seconds -- Recast Time: 29.25 seconds -- Magic Bursts on: Impaction, Fragmentation, Light -- Combos: None ----------------------------------------- require("scripts/globals/bluemagic"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.multiplier = 1.5625; params.tMultiplier = 1.0; params.duppercap = 61; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; params.mnd_wsc = 0.1; params.chr_wsc = 0.0; local damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local params = {}; params.diff = caster:getStat(MOD_INT) - target:getStat(MOD_INT); params.attribute = MOD_INT; params.skillType = BLUE_SKILL; params.bonus = 1.0; local resist = applyResistance(caster, target, spell, params); if (damage > 0 and resist > 0.0625) then local typeEffect = dsp.effects.STUN; target:delStatusEffect(typeEffect); -- Wiki says it can overwrite itself or other binds target:addStatusEffect(typeEffect,1,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/commands/bodyShot3.lua
2
2446
--Copyright (C) 2007 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. --true = 1, false = 0 BodyShot3Command = { name = "bodyshot3", damageMultiplier = 4, speedMultiplier = 1, healthCostMultiplier = 0.75, actionCostMultiplier = 1.25, mindCostMultiplier = 0.75, accuracyBonus = 50, poolsToDamage = HEALTH_ATTRIBUTE, animationCRC = hashCode("fire_1_special_single_light"), combatSpam = "bodyshot", weaponType = PISTOLWEAPON, range = -1 } AddCommand(BodyShot3Command)
agpl-3.0
KingRaptor/Zero-K
LuaUI/Widgets/unit_dynamic_avoidance_ex.lua
1
138612
local versionName = "v2.879" -------------------------------------------------------------------------------- -- -- file: cmd_dynamic_Avoidance.lua -- brief: a collision avoidance system -- using: "non-Linear Dynamic system approach to modelling behavior" -SiomeGoldenstein, Edward Large, DimitrisMetaxas -- code: Msafwan -- -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Dynamic Avoidance System", desc = versionName .. " Avoidance AI behaviour for constructor, cloakies, ground-combat unit and gunships.\n\nNote: Customize the settings by Space+Click on unit-state icons.", author = "msafwan", date = "March 8, 2014", --clean up June 25, 2013 license = "GNU GPL, v2 or later", layer = 20, enabled = false -- loaded by default? } end -------------------------------------------------------------------------------- -- Functions: local spGetTeamUnits = Spring.GetTeamUnits local spGetAllUnits = Spring.GetAllUnits local spGetTeamResources = Spring.GetTeamResources local spGetGroundHeight = Spring.GetGroundHeight local spGiveOrderToUnit =Spring.GiveOrderToUnit local spGiveOrderArrayToUnitArray = Spring.GiveOrderArrayToUnitArray local spGetMyTeamID = Spring.GetMyTeamID local spIsUnitAllied = Spring.IsUnitAllied local spGetUnitPosition =Spring.GetUnitPosition local spGetUnitVelocity = Spring.GetUnitVelocity local spGetUnitDefID = Spring.GetUnitDefID local spGetUnitSeparation = Spring.GetUnitSeparation local spGetUnitDirection =Spring.GetUnitDirection local spGetUnitsInRectangle =Spring.GetUnitsInRectangle local spGetVisibleUnits = Spring.GetVisibleUnits local spGetCommandQueue = Spring.GetCommandQueue local spGetGameSeconds = Spring.GetGameSeconds local spGetFeaturePosition = Spring.GetFeaturePosition local spGetPlayerInfo = Spring.GetPlayerInfo local spGetUnitStates = Spring.GetUnitStates local spGetUnitIsCloaked = Spring.GetUnitIsCloaked local spGetUnitTeam = Spring.GetUnitTeam local spGetUnitLastAttacker = Spring.GetUnitLastAttacker local spGetUnitHealth = Spring.GetUnitHealth local spGetUnitWeaponState = Spring.GetUnitWeaponState local spGetUnitShieldState = Spring.GetUnitShieldState local spGetUnitIsStunned = Spring.GetUnitIsStunned local spGetGameFrame = Spring.GetGameFrame local spSendCommands = Spring.SendCommands local spGetSelectedUnits = Spring.GetSelectedUnits local spGetUnitIsDead = Spring.GetUnitIsDead local spValidUnitID = Spring.ValidUnitID local spValidFeatureID = Spring.ValidFeatureID local spGetUnitRulesParam = Spring.GetUnitRulesParam local CMD_STOP = CMD.STOP local CMD_ATTACK = CMD.ATTACK local CMD_GUARD = CMD.GUARD local CMD_INSERT = CMD.INSERT local CMD_REMOVE = CMD.REMOVE local CMD_MOVE = CMD.MOVE local CMD_OPT_INTERNAL = CMD.OPT_INTERNAL local CMD_OPT_SHIFT = CMD.OPT_SHIFT local CMD_RECLAIM = CMD.RECLAIM local CMD_RESURRECT = CMD.RESURRECT local CMD_REPAIR = CMD.REPAIR VFS.Include("LuaRules/Utilities/versionCompare.lua") local LOS_MULT = (Spring.Utilities.IsCurrentVersionNewerThan(100, 0) and 1) or 32 --local spRequestPath = Spring.RequestPath local mathRandom = math.random --local spGetUnitSensorRadius = Spring.GetUnitSensorRadius -------------------------------------------------------------------------------- -- Constant: -- Switches: local turnOnEcho =0 --1:Echo out all numbers for debugging the system, 2:Echo out alert when fail. (default = 0) local activateAutoReverseG=1 --integer:[0,1], activate a one-time-reverse-command when unit is about to collide with an enemy (default = 1) local activateImpatienceG=0 --integer:[0,1], auto disable auto-reverse & half the 'distanceCONSTANT' after 6 continuous auto-avoidance (3 second). In case the unit stuck (default = 0) -- Graph constant: local distanceCONSTANTunitG = 410 --increase obstacle awareness over distance. (default = 410 meter, ie: ZK's stardust range) local useLOS_distanceCONSTANTunit_G = true --this replace "distanceCONSTANTunitG" obstacle awareness (push) strenght with unit's LOS, ie: unit with different range suit better. (default = true, for tuning: use false) local safetyMarginCONSTANTunitG = 0.175 --obstacle graph windower (a "safety margin" constant). Shape the obstacle graph so that its fatter and more sloppier at extremities: ie: probably causing unit to prefer to turn more left or right (default = 0.175 radian) local smCONSTANTunitG = 0.175 -- obstacle graph offset (a "safety margin" constant). Offset the obstacle effect: to prefer avoid torward more left or right??? (default = 0.175 radian) local aCONSTANTg = {math.pi/4 , math.pi/2} -- attractor graph; scale the attractor's strenght. Less equal to a lesser turning toward attraction(default = math.pi/10 radian (MOVE),math.pi/4 (GUARD & ATTACK)) (max value: math.pi/2 (because both contribution from obstacle & target will sum to math.pi)). local obsCONSTANTg = {math.pi/4, math.pi/2} -- obstacle graph; scale the obstacle's strenght. Less equal to a lesser turning away from avoidance(default = math.pi/10 radian (MOVE), math.pi/4 (GUARD & ATTACK)). --aCONSTANTg Note: math.pi/4 is equal to about 45 degrees turning (left or right). aCONSTANTg is the maximum amount of turning toward target and the actual turning depend on unit's direction. Activated by 'graphCONSTANTtrigger[1]' --an antagonist to aCONSTANg (obsCONSTANTg or obstacle graph) also use math.pi/4 (45 degree left or right) but actual maximum value varies depend on number of enemy, but already normalized. Activated by 'graphCONSTANTtrigger[2]' local windowingFuncMultG = 1 --? (default = 1 multiplier) local normalizeObsGraphG = true --// if 'true': normalize turn angle to a maximum of "obsCONSTANTg", if 'false': allow turn angle to grow as big as it can (depend on number of enemy, limited by "maximumTurnAngleG"). local stdDecloakDist_fG = 75 --//a decloak distance size for Scythe is put as standard. If other unit has bigger decloak distance then it will be scalled based on this -- Obstacle/Target competetive interaction constant: local cCONSTANT1g = {0.01,1,2} --attractor constant; effect the behaviour. ie: selection between 4 behaviour state. (default = 0.01x (All), 1x (Cloakies),2x (alwaysAvoid)) (behaviour:(MAINTAIN USER's COMMAND)|(IGNORE USER's COMMAND|(IGNORE USER's COMMAND)) local cCONSTANT2g = {0.01,1,2} --repulsor constant; effect behaviour. (default = 0.01x (All), 1x (Cloakies),2x (alwaysAvoid)) (behaviour:(MAINTAIN USER's COMMAND)|(IGNORE USER's COMMAND|(IGNORE USER's COMMAND)) local gammaCONSTANT2and1g = {0.05,0.05,0.05} -- balancing constant; effect behaviour. . (default = 0.05x (All), 0.05x (Cloakies)) local alphaCONSTANT1g = {500,0.4,0.4} -- balancing constant; effect behaviour. (default = 500x (All), 0.4x (Cloakies)) (behaviour:(MAINTAIN USER's COMMAND)|(IGNORE USER's COMMAND)) --Move Command constant: local halfTargetBoxSize_g = {400, 0, 185, 50} --aka targetReachBoxSizeTrigger, set the distance from a target which widget should de-activate (default: MOVE = 400m (ie:800x800m box/2x constructor range), RECLAIM/RESURRECT=0 (always flee), REPAIR=185 (1x constructor's range), GUARD = 50 (arbitrary)) local cMD_DummyG = 248 --a fake command ID to flag an idle unit for pure avoidance. (arbitrary value, change if it overlap with existing command) local cMD_Dummy_atkG = 249 --same as cMD_DummyG except to differenciate between idle & attacking --Angle constant: --http://en.wikipedia.org/wiki/File:Degree-Radian_Conversion.svg local noiseAngleG =0.1 --(default is pi/36 rad); add random angle (range from 0 to +-math.pi/36) to the new angle. To prevent a rare state that contribute to unit going straight toward enemy local collisionAngleG= 0.1 --(default is pi/6 rad) a "field of vision" (range from 0 to +-math.pi/366) where auto-reverse will activate local fleeingAngleG= 0.7 --(default is pi/4 rad) angle of enemy with respect to unit (range from 0 to +-math.pi/4) where unit is considered as facing a fleeing enemy (to de-activate avoidance to perform chase). Set to 0 to de-activate. local maximumTurnAngleG = math.pi --(default is pi rad) safety measure. Prevent overturn (eg: 360+xx degree turn) --pi is 180 degrees --Update constant: local cmd_then_DoCalculation_delayG = 0.25 --elapsed second (Wait) before issuing new command (default: 0.25 second) -- Distance or velocity constant: local timeToContactCONSTANTg= cmd_then_DoCalculation_delayG --time scale for move command; to calculate collision calculation & command lenght (default = 0.5 second). Will change based on user's Ping local safetyDistanceCONSTANT_fG=205 --range toward an obstacle before unit auto-reverse (default = 205 meter, ie: half of ZK's stardust range) reference:80 is a size of BA's solar local extraLOSRadiusCONSTANTg=205 --add additional distance for unit awareness over the default LOS. (default = +205 meter radius, ie: to 'see' radar blip).. Larger value measn unit detect enemy sooner, else it will rely on its own LOS. local velocityScalingCONSTANTg=1.1 --scale command lenght. (default= 1 multiplier) *Small value cause avoidance to jitter & stop prematurely* local velocityAddingCONSTANTg=50 --add or remove command lenght (default = 50 elmo/second) *Small value cause avoidance to jitter & stop prematurely* --Weapon Reload and Shield constant: local reloadableWeaponCriteriaG = 0.5 --second at which reload time is considered high enough to be a "reload-able". eg: 0.5second local criticalShieldLevelG = 0.5 --percent at which shield is considered low and should activate avoidance. eg: 50% local minimumRemainingReloadTimeG = 0.9 --seconds before actual reloading finish which avoidance should de-activate (note: overriden by 1/4 of weapon's reload time if its bigger). eg: 0.9 second before finish (or 7 second for armspy) local thresholdForArtyG = 459 --elmo (weapon range) before unit is considered an arty. Arty will never set enemy as target and will always avoid. default: 459elmo (1 elmo smaller than Rocko range) local maximumMeleeRangeG = 101 --elmo (weapon range) before unit is considered a melee. Melee will target enemy and do not avoid at halfTargetBoxSize_g[1]. default: 101elmo (1 elmo bigger than Sycthe range) local secondPerGameFrameG = 1/30 --engine depended second-per-frame (for calculating remaining reload time). eg: 0.0333 second-per-frame or 0.5sec/15frame --Command Timeout constants: local commandTimeoutG = 2 --multiply by 1.1 second local consRetreatTimeoutG = 15 --multiply by 1.1 second, is overriden by epicmenu option --NOTE: --angle measurement and direction setting is based on right-hand coordinate system, but Spring uses left-hand coordinate system. --So, math.sin is for x, and math.cos is for z, and math.atan2 input is x,z (is swapped with respect to the usual x y convention). --those swap conveniently translate left-hand coordinate system into right-hand coordinate system. -------------------------------------------------------------------------------- --Variables: local unitInMotionG={} --store unitID local skippingTimerG={0,0,echoTimestamp=0, networkDelay=0, averageDelay = 0.3, storedDelay = {}, index = 1, sumOfAllNetworkDelay=0, sumCounter=0} --variable: store the timing for next update, and store values for calculating average network delay. local commandIndexTableG= {} --store latest widget command for comparison local myTeamID_gbl=-1 local myPlayerID=-1 local gaiaTeamID = Spring.GetGaiaTeamID() local attackerG= {} --for recording last attacker local commandTTL_G = {} --for recording command's age. To check for expiration. Note: Each table entry is indexed by unitID local iNotLagging_gbl = true --//variable: indicate if player(me) is lagging in current game. If lagging then do not process anything. local selectedCons_Meta_gbl = {} --//variable: remember which Constructor is selected by player. local waitForNetworkDelay_gbl = nil local issuedOrderTo_G = {} local allyClusterInfo_gbl = {coords={},age=0} -------------------------------------------------------------------------------- --Methods: ---------------------------------Level 0 options_path = 'Game/Unit AI/Dynamic Avoidance' --//for use 'with gui_epicmenu.lua' options_order = {'enableCons','enableCloaky','enableGround','enableGunship','enableReturnToBase','consRetreatTimeoutOption', 'cloakyAlwaysFlee','enableReloadAvoidance','retreatAvoidance','dbg_RemoveAvoidanceSplitSecond', 'dbg_IgnoreSelectedCons'} options = { enableCons = { name = 'Enable for constructors', type = 'bool', value = true, desc = 'Enable constructor\'s avoidance feature (WILL NOT include Commander).\n\nConstructors will avoid enemy while having move order. Constructor also return to base when encountering enemy during area-reclaim or area-ressurect command, and will try to avoid enemy while having build or repair or reclaim queue except when hold-position is issued.\n\nTips: order area-reclaim to the whole map, work best for cloaked constructor, but buggy for flying constructor. Default:On', }, enableCloaky = { name = 'Enable for cloakies', type = 'bool', value = true, desc = 'Enable cloakies\' avoidance feature.\n\nCloakable bots will avoid enemy while having move order. Cloakable will also flee from enemy when idle except when hold-position state is used.\n\nTips: is optimized for Sycthe- your Sycthe will less likely to accidentally bump into enemy unit. Default:On', }, enableGround = { name = 'Enable for ground units', type = 'bool', value = true, desc = 'Enable for ground units (INCLUDE Commander).\n\nAll ground unit will avoid enemy while being outside camera view and/or while reloading except when hold-position state is used.\n\nTips:\n1) is optimized for masses of Thug or Zeus.\n2) You can use Guard to make your unit swarm the guarded unit in presence of enemy.\nDefault:On', }, enableGunship = { name = 'Enable for gunships', type = 'bool', value = false, desc = 'Enable gunship\'s avoidance behaviour .\n\nGunship will avoid enemy while outside camera view and/or while reloading except when hold-position state is used.\n\nTips: to create a hit-&-run behaviour- set the fire-state options to hold-fire (can be buggy). Default:Off', }, -- enableAmphibious = { -- name = 'Enable for amphibious', -- type = 'bool', -- value = true, -- desc = 'Enable amphibious unit\'s avoidance feature (including Commander, and submarine). Unit avoid enemy while outside camera view OR when reloading, but units with hold position state is excluded..', -- }, enableReloadAvoidance = { name = "Jink during attack", type = 'bool', value = true, desc = "Unit with slow reload will randomly jink to random direction when attacking. NOTE: This have no benefit and bad versus fast attacker or fast weapon but have high chance of dodging versus slow ballistic weapon. Default:On", }, enableReturnToBase = { name = "Find base", type = 'bool', value = true, desc = "Allow constructor to return to base when having area-reclaim or area-ressurect command, else it will return to center of the circle when retreating. \n\nTips: build 3 new buildings at new location to identify as base, unit will automatically select nearest base. Default:On", }, consRetreatTimeoutOption = { name = 'Constructor retreat auto-expire:', type = 'number', value = 3, desc = "Amount in second before constructor retreat command auto-expire (is deleted), and then constructor will return to its previous area-reclaim command.\n\nTips: small value is better.", min=3,max=15,step=1, OnChange = function(self) consRetreatTimeoutG = self.value Spring.Echo(string.format ("%.1f", 1.1*consRetreatTimeoutG) .. " second") end, }, cloakyAlwaysFlee = { name = 'Cloakies always flee', type = 'bool', value = false, desc = 'Force cloakies & constructor to always flee from enemy when idle except if they are under hold-position state. \n\nNote: Unit can wander around and could put themselves in danger. Default:Off', }, retreatAvoidance = { name = 'Retreating unit always flee', type = 'bool', value = true, desc = 'Force retreating unit to always avoid the enemy (Note: this require the use of RETREAT functionality provided by cmd_retreat.lua widget a.k.a unit retreat widget). Default:On', }, dbg_RemoveAvoidanceSplitSecond = { name = 'Debug: Constructor instant retreat', type = 'bool', value = true, desc = "Widget to issue a retreat order first before issuing an avoidance (to reduce chance of avoidance putting constructor into more danger).\n\nDefault:On.", advanced = true, }, dbg_IgnoreSelectedCons ={ name = 'Debug: Ignore current selection', type = 'bool', value = false, desc = "Selected constructor(s) will be ignored by widget.\nNote: there's a second delay before unit is ignored/re-acquire after selection/de-selection.\n\nDefault:Off", --advanced = true, }, } function widget:Initialize() skippingTimerG.echoTimestamp = spGetGameSeconds() myPlayerID=Spring.GetMyPlayerID() local _, _, spec = Spring.GetPlayerInfo(myPlayerID) if spec then widgetHandler:RemoveWidget() return false end myTeamID_gbl= spGetMyTeamID() if (turnOnEcho == 1) then Spring.Echo("myTeamID_gbl(Initialize)" .. myTeamID_gbl) end end function widget:PlayerChanged(playerID) if Spring.GetSpectatingState() then widgetHandler:RemoveWidget() end end --execute different function at different timescale function widget:Update() -------retrieve global table, localize global table local commandIndexTable=commandIndexTableG local unitInMotion = unitInMotionG local skippingTimer = skippingTimerG local attacker = attackerG local commandTTL = commandTTL_G local selectedCons_Meta = selectedCons_Meta_gbl local cmd_then_DoCalculation_delay = cmd_then_DoCalculation_delayG local myTeamID = myTeamID_gbl local waitForNetworkDelay = waitForNetworkDelay_gbl local allyClusterInfo = allyClusterInfo_gbl ----- if iNotLagging_gbl then local now=spGetGameSeconds() --REFRESH UNIT LIST-- *not synced with avoidance* if (now >= skippingTimer[1]) then --wait until 'skippingTimer[1] second', then do "RefreshUnitList()" if (turnOnEcho == 1) then Spring.Echo("-----------------------RefreshUnitList") end unitInMotion, attacker, commandTTL, selectedCons_Meta =RefreshUnitList(attacker, commandTTL) --create unit list allyClusterInfo["age"]=allyClusterInfo["age"]+1 --indicate that allyClusterInfo is 1 cycle older local projectedDelay=ReportedNetworkDelay(myPlayerID, 1.1) --create list every 1.1 second OR every (0+latency) second, depending on which is greater. skippingTimer[1]=now+projectedDelay --wait until next 'skippingTimer[1] second' --check if under lockdown for overextended time if waitForNetworkDelay then if now - waitForNetworkDelay[1] > 4 then for unitID,_ in pairs(issuedOrderTo_G) do issuedOrderTo_G[unitID] = nil end waitForNetworkDelay = nil end end if (turnOnEcho == 1) then Spring.Echo("-----------------------RefreshUnitList") end end --GATHER SOME INFORMATION ON UNITS-- *part 1, start* if (now >=skippingTimer[2]) and (not waitForNetworkDelay) then --wait until 'skippingTimer[2] second', and wait for 'LUA message received', and wait for 'cycle==1', then do "DoCalculation()" if (turnOnEcho == 1) then Spring.Echo("-----------------------DoCalculation") end local infoForDoCalculation = { unitInMotion,commandIndexTable, attacker, selectedCons_Meta,myTeamID, skippingTimer, now, commandTTL, waitForNetworkDelay,allyClusterInfo } local outputTable,isAvoiding =DoCalculation(infoForDoCalculation) commandIndexTable = outputTable["commandIndexTable"] commandTTL = outputTable["commandTTL"] waitForNetworkDelay = outputTable["waitForNetworkDelay"] allyClusterInfo = outputTable["allyClusterInfo"] if isAvoiding then skippingTimer.echoTimestamp = now -- --prepare delay statistic to measure new delay (aka: reset stopwatch), --same as "CalculateNetworkDelay("restart", , )"^/ else skippingTimer[2] = now + cmd_then_DoCalculation_delay --wait until 'cmd_then_DoCalculation_delayG'. The longer the better. The delay allow reliable unit direction to be derived from unit's motion end if (turnOnEcho == 1) then Spring.Echo("-----------------------DoCalculation") end end if (turnOnEcho == 1) then Spring.Echo("unitInMotion(Update):") Spring.Echo(unitInMotion) end end -------return global table allyClusterInfo_gbl = allyClusterInfo commandIndexTableG=commandIndexTable unitInMotionG = unitInMotion skippingTimerG = skippingTimer attackerG = attacker commandTTL_G = commandTTL selectedCons_Meta_gbl = selectedCons_Meta waitForNetworkDelay_gbl = waitForNetworkDelay ----- end function widget:GameProgress(serverFrameNum) --//see if player are lagging behind the server in the current game. If player is lagging then trigger a switch, (this switch will tell the widget to stop processing units). local myFrameNum = spGetGameFrame() local frameNumDiff = serverFrameNum - myFrameNum if frameNumDiff > 120 then --// 120 frame means: a 4 second lag. Consider me is lagging if my frame differ from server by more than 4 second. iNotLagging_gbl = false else --// consider me not lagging if my frame differ from server's frame for less than 4 second. iNotLagging_gbl = true end end function widget:UnitDestroyed(unitID, unitDefID, unitTeam) if commandTTL_G[unitID] then --empty watch list for this unit when unit die commandTTL_G[unitID] = nil end if commandIndexTableG[unitID] then commandIndexTableG[unitID] = nil end if myTeamID_gbl==unitTeam and issuedOrderTo_G[unitID] then CountdownNetworkDelayWait(unitID) end end function widget:UnitGiven(unitID, unitDefID, newTeam,oldTeam) if oldTeam == myTeamID_gbl then if commandTTL_G[unitID] then --empty watch list for this unit is shared away commandTTL_G[unitID] = nil end if commandIndexTableG[unitID] then commandIndexTableG[unitID] = nil end end if myTeamID_gbl==oldTeam and issuedOrderTo_G[unitID] then CountdownNetworkDelayWait(unitID) end end function widget:UnitCommand(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions) if myTeamID_gbl==unitTeam and issuedOrderTo_G[unitID] then if (CMD.INSERT == cmdID and cmdParams[2] == CMD_MOVE) and cmdParams[4] == issuedOrderTo_G[unitID][1] and cmdParams[5] == issuedOrderTo_G[unitID][2] and cmdParams[6] == issuedOrderTo_G[unitID][3] then CountdownNetworkDelayWait(unitID) end end end ---------------------------------Level 0 Top level ---------------------------------Level1 Lower level -- return a refreshed unit list, else return a table containing NIL function RefreshUnitList(attacker, commandTTL) local stdDecloakDist = stdDecloakDist_fG local thresholdForArty = thresholdForArtyG local maximumMeleeRange = maximumMeleeRangeG ---------------------------------------------------------- local allMyUnits = spGetTeamUnits(myTeamID_gbl) local arrayIndex=0 local relevantUnit={} local selectedUnits = (spGetSelectedUnits()) or {} local selectedUnits_Meta = {} local selectedCons_Meta = {} for i = 1, #selectedUnits, 1 do local unitID = selectedUnits[i] selectedUnits_Meta[unitID]=true end local metaForVisibleUnits = {} local visibleUnits=spGetVisibleUnits(myTeamID_gbl) for _, unitID in ipairs(visibleUnits) do --memorize units that is in view of camera metaForVisibleUnits[unitID]="yes" --flag "yes" for visible unit (in view) and by default flag "nil" for out of view unit end for _, unitID in ipairs(allMyUnits) do if unitID~=nil then --skip end of the table -- additional hitchiking function: refresh attacker's list attacker = RetrieveAttackerList (unitID, attacker) -- additional hitchiking function: refresh WATCHDOG's list commandTTL = RefreshWatchdogList (unitID, commandTTL) -- local unitDefID = spGetUnitDefID(unitID) local unitDef = UnitDefs[unitDefID] local unitSpeed =unitDef["speed"] local decloakScaling = math.max((unitDef["decloakDistance"] or 0),stdDecloakDist)/stdDecloakDist local unitInView = metaForVisibleUnits[unitID] --transfer "yes" or "nil" from meta table into a local variable local _,_,inbuild = spGetUnitIsStunned(unitID) if (unitSpeed>0) and (not inbuild) then local unitType = 0 --// category that control WHEN avoidance is activated for each unit. eg: Category 2 only enabled when not in view & when guarding units. Used by 'GateKeeperOrCommandFilter()' local fixedPointType = 1 --//category that control WHICH avoidance behaviour to use. eg: Category 2 priotize avoidance and prefer to ignore user's command when enemy is close. Used by 'CheckWhichFixedPointIsStable()' if (unitDef.isBuilder or unitDef["canCloak"]) and not unitDef.customParams.commtype then --include only constructor and cloakies, and not com unitType =1 --//this unit-type will do avoidance even in camera view local isBuilder_ignoreTrue = false if unitDef.isBuilder then isBuilder_ignoreTrue = (options.dbg_IgnoreSelectedCons.value == true and selectedUnits_Meta[unitID] == true) --is (epicMenu force-selection-ignore is true? AND unit is a constructor?) if selectedUnits_Meta[unitID] then selectedCons_Meta[unitID] = true --remember selected Constructor end end if (unitDef.isBuilder and options.enableCons.value==false) or (isBuilder_ignoreTrue) then --//if ((Cons epicmenu option is false) OR (epicMenu force-selection-ignore is true)) AND it is a constructor, then... exclude (this) Cons unitType = 0 --//this unit-type excluded from avoidance end if unitDef["canCloak"] then --only cloakies + constructor that is cloakies fixedPointType=2 --//use aggressive behaviour (avoid more & more likely to ignore the users) if options.enableCloaky.value==false or (isBuilder_ignoreTrue) then --//if (Cloaky option is false) OR (epicMenu force-selection-ignore is true AND unit is a constructor) then exclude Cloaky unitType = 0 end end --elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) and not unitDef["canSubmerge"] then --include all ground unit, but excluding com & amphibious elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) then --include all ground unit, including com unitType =2 --//this unit type only have avoidance outside camera view & while reloading (in camera view) if options.enableGround.value==false then --//if Ground unit epicmenu option is false then exclude Ground unit unitType = 0 end elseif (unitDef.hoverAttack== true) then --include gunships unitType =3 --//this unit-type only have avoidance outside camera view & while reloading (in camera view) if options.enableGunship.value==false then --//if Gunship epicmenu option is false then exclude Gunship unitType = 0 end -- elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) and unitDef["canSubmerge"] then --include all amphibious unit & com -- unitType =4 --//this unit type only have avoidance outside camera view -- if options.enableAmphibious.value==false then --//if Gunship epicmenu option is false then exclude Gunship -- unitType = 0 -- end end if (unitType>0) then local unitShieldPower, reloadableWeaponIndex,reloadTime,range,weaponType= -1, -1,-1,-1,-1 unitShieldPower, reloadableWeaponIndex,reloadTime,range = CheckWeaponsAndShield(unitDef) arrayIndex=arrayIndex+1 if range < maximumMeleeRange then weaponType = 0 elseif range< thresholdForArty then weaponType = 1 else weaponType = 2 end relevantUnit[arrayIndex]={unitID = unitID, unitType = unitType, unitSpeed = unitSpeed, fixedPointType = fixedPointType, decloakScaling = decloakScaling,weaponInfo = {unitShieldPower = unitShieldPower, reloadableWeaponIndex = reloadableWeaponIndex,reloadTime = reloadTime,range=range}, isVisible = unitInView, weaponType = weaponType} end end if (turnOnEcho == 1) then --for debugging Spring.Echo("unitID(RefreshUnitList)" .. unitID) Spring.Echo("unitDef[humanName](RefreshUnitList)" .. unitDef["humanName"]) Spring.Echo("((unitDef[builder] or unitDef[canCloak]) and unitDef[speed]>0)(RefreshUnitList):") Spring.Echo((unitDef.isBuilder or unitDef["canCloak"]) and unitDef["speed"]>0) end end end relevantUnit["count"]=arrayIndex -- store the array's lenght if (turnOnEcho == 1) then Spring.Echo("allMyUnits(RefreshUnitList): ") Spring.Echo(allMyUnits) Spring.Echo("relevantUnit(RefreshUnitList): ") Spring.Echo(relevantUnit) end return relevantUnit, attacker, commandTTL, selectedCons_Meta end -- detect initial enemy separation to detect "fleeing enemy" later function DoCalculation(passedInfo) local unitInMotion = passedInfo[1] local attacker = passedInfo[3] local selectedCons_Meta = passedInfo[4] ----- local isAvoiding = nil local persistentData = { commandIndexTable= passedInfo[2], myTeamID= passedInfo[5], skippingTimer = passedInfo[6], now = passedInfo[7], commandTTL=passedInfo[8], waitForNetworkDelay=passedInfo[9], allyClusterInfo= passedInfo[10], } local gateKeeperOutput = { cQueueTemp=nil, allowExecution=nil, reloadAvoidance=nil, } local idTargetOutput = { targetCoordinate = nil, newCommand = nil, boxSizeTrigger = nil, graphCONSTANTtrigger = nil, fixedPointCONSTANTtrigger = nil, case = nil, targetID = nil, } if unitInMotion["count"] and unitInMotion["count"]>0 then --don't execute if no unit present for i=1, unitInMotion["count"], 1 do local unitID= unitInMotion[i]["unitID"] --get unitID for commandqueue if not spGetUnitIsDead(unitID) and (spGetUnitTeam(unitID)==persistentData["myTeamID"]) then --prevent execution if unit died during transit local cQueue = spGetCommandQueue(unitID,-1) gateKeeperOutput = GateKeeperOrCommandFilter(cQueue,persistentData, unitInMotion[i]) --filter/alter unwanted unit state by reading the command queue if gateKeeperOutput["allowExecution"] then --cQueue = cQueueTemp --cQueueTemp has been altered for identification, copy it to cQueue for use in DoCalculation() phase (note: command is not yet issued) --local boxSizeTrigger= unitInMotion[i][2] idTargetOutput=IdentifyTargetOnCommandQueue(cQueue,persistentData,gateKeeperOutput,unitInMotion[i]) --check old or new command if selectedCons_Meta[unitID] and idTargetOutput["boxSizeTrigger"]~= 4 then --if unitIsSelected and NOT using GUARD 'halfboxsize' (ie: is not guarding) then: idTargetOutput["boxSizeTrigger"] = 1 -- override all reclaim/ressurect/repair's deactivation 'halfboxsize' with the one for MOVE command (give more tolerance when unit is selected) end local reachedTarget = TargetBoxReached(unitID, idTargetOutput) --check if widget should ignore command if ((idTargetOutput["newCommand"] and gateKeeperOutput["cQueueTemp"][1].id==CMD_MOVE) or gateKeeperOutput["cQueueTemp"][2].id==CMD_MOVE) and (unitInMotion[i]["isVisible"]~= "yes") then --if unit is issued a move Command and is outside user's view. Note: is using cQueueTemp because cQueue can be NIL reachedTarget = false --force unit to continue avoidance despite close to target (try to circle over target until seen by user) elseif (idTargetOutput["case"] == "none") then reachedTarget = true --do not process unhandled command. This fix a case of unwanted behaviour when ZK's SmartAI issued a fight command on top of Avoidance's order and cause conflicting behaviour. elseif (not gateKeeperOutput["reloadAvoidance"] and idTargetOutput["case"] == 'attack') then reachedTarget = true --do not process direct attack command. Avoidance is not good enough for melee unit end if reachedTarget then --if reached target if not idTargetOutput["newCommand"] then spGiveOrderToUnit(unitID,CMD_REMOVE,{cQueue[1].tag,},{}) --remove previously given (avoidance) command if reached target end persistentData["commandIndexTable"][unitID]=nil --empty the commandIndex (command history) else --execute when target not reached yet local losRadius = GetUnitLOSRadius(idTargetOutput["case"],unitInMotion[i]) --get LOS. also custom LOS for case=="attack" & weapon range >0 local isMeleeAttacks = (idTargetOutput["case"] == 'attack' and unitInMotion[i]["weaponType"] == 0) local excludedEnemyID = (isMeleeAttacks) and idTargetOutput["targetID"] local surroundingUnits = GetAllUnitsInRectangle(unitID, losRadius, attacker,excludedEnemyID) --catalogue enemy if surroundingUnits["count"]~=0 then --execute when enemy exist --local unitType =unitInMotion[i]["unitType"] --local unitSSeparation, losRadius = CatalogueMovingObject(surroundingUnits, unitID, lastPosition, unitType, losRadius) --detect initial enemy separation & alter losRadius when unit submerged local unitSSeparation, losRadius = CatalogueMovingObject(surroundingUnits, unitID, losRadius) --detect initial enemy separation & alter losRadius when unit submerged local impatienceTrigger = GetImpatience(idTargetOutput,unitID, persistentData) if (turnOnEcho == 1) then Spring.Echo("unitsSeparation(DoCalculation):") Spring.Echo(unitsSeparation) end local avoidanceCommand,orderArray= InsertCommandQueue(unitID,cQueue,gateKeeperOutput["cQueueTemp"],idTargetOutput["newCommand"],persistentData)--delete old widget command, update commandTTL, and send constructor to base for retreat if avoidanceCommand or (not options.dbg_RemoveAvoidanceSplitSecond.value) then if idTargetOutput["targetCoordinate"][1] == -1 then --no target idTargetOutput["targetCoordinate"] = UseNearbyAllyAsTarget(unitID,persistentData) --eg: when retreating to nearby ally end local newX, newZ = AvoidanceCalculator(losRadius,surroundingUnits,unitSSeparation,impatienceTrigger,persistentData,idTargetOutput,unitInMotion[i]) --calculate move solution local newY=spGetGroundHeight(newX,newZ) --Inserting command queue:-- if (cQueue==nil or #cQueue<2) and gateKeeperOutput["cQueueTemp"][1].id == cMD_DummyG then --if #cQueueSyncTest is less than 2 mean unit has widget's mono-command, and cMD_DummyG mean its idle & out of view: orderArray[#orderArray+1]={CMD_INSERT, {0, CMD_MOVE, CMD.OPT_SHIFT, newX, newY, newZ}, {"alt"}} -- using SHIFT prevent unit from returning to old position. NOTE: we NEED to use insert here (rather than use direct move command) because in high-ping situation (where user's command do not register until last minute) user's command will get overriden if both widget's and user's command arrive at same time. else orderArray[#orderArray+1]={CMD_INSERT, {0, CMD_MOVE, CMD_OPT_INTERNAL, newX, newY, newZ}, {"alt"}} --spGiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_MOVE, CMD_OPT_INTERNAL, newX, newY, newZ}, {"alt"}), insert new command (Note: CMD_OPT_INTERNAL is used to mark that this command is widget issued and need not special treatment. ie: It won't get repeated if Repeat state is used.) end local lastIndx = persistentData["commandTTL"][unitID][1] --commandTTL[unitID]'s table lenght persistentData["commandTTL"][unitID][lastIndx+1] = {countDown = commandTimeoutG, widgetCommand= {newX, newZ}} --//remember this command on watchdog's commandTTL table. It has 4x*RefreshUnitUpdateRate* to expire persistentData["commandTTL"][unitID][1] = lastIndx+1 --refresh commandTTL[unitID]'s table lenght persistentData["commandIndexTable"][unitID]["widgetX"]=newX --update the memory table. So that next update can use to check if unit has new or old (widget's) command persistentData["commandIndexTable"][unitID]["widgetZ"]=newZ --end-- end local orderCount = #orderArray if orderCount >0 then spGiveOrderArrayToUnitArray ({unitID},orderArray) isAvoiding = true if persistentData["waitForNetworkDelay"] then persistentData["waitForNetworkDelay"][2] = persistentData["waitForNetworkDelay"][2] + 1 else persistentData["waitForNetworkDelay"] = {spGetGameSeconds(),1} end local moveOrderParams = orderArray[orderCount][2] issuedOrderTo_G[unitID] = {moveOrderParams[4], moveOrderParams[5], moveOrderParams[6]} end end end --reachedTarget end --GateKeeperOrCommandFilter(cQueue, unitInMotion[i]) ==true end --if spGetUnitIsDead(unitID)==false end end --if unitInMotion[1]~=nil return persistentData,isAvoiding --send separation result away end function CountdownNetworkDelayWait(unitID) issuedOrderTo_G[unitID] = nil if waitForNetworkDelay_gbl then waitForNetworkDelay_gbl[2] = waitForNetworkDelay_gbl[2] - 1 if waitForNetworkDelay_gbl[2]==0 then waitForNetworkDelay_gbl = nil ----------------- local skippingTimer = skippingTimerG --is global table local cmd_then_DoCalculation_delay = cmd_then_DoCalculation_delayG local now =spGetGameSeconds() skippingTimer.networkDelay = now - skippingTimer.echoTimestamp --get the delay between previous Command and the latest 'LUA message Receive' --Method 2: use rolling average skippingTimer.storedDelay[skippingTimer.index] = skippingTimer.networkDelay --store network delay value in a rolling table skippingTimer.index = skippingTimer.index+1 --table index ++ if skippingTimer.index > 11 then --roll the table/wrap around, so that the index circle the table. The 11-th sequence is for storing the oldest value, 1-st to 10-th sequence is for the average skippingTimer.index = 1 end skippingTimer.averageDelay = skippingTimer.averageDelay + skippingTimer.networkDelay/10 - (skippingTimer.storedDelay[skippingTimer.index] or 0.3)/10 --add new delay and minus old delay, also use 0.3sec as the old delay if nothing is stored yet. -- skippingTimer[2] = now + cmd_then_DoCalculation_delay --wait until 'cmd_then_DoCalculation_delayG'. The longer the better. The delay allow reliable unit direction to be derived from unit's motion skippingTimerG = skippingTimer end end end function ReportedNetworkDelay(playerIDa, defaultDelay) local _,_,_,_,_,totalDelay,_,_,_,_= Spring.GetPlayerInfo(playerIDa) if totalDelay==nil or totalDelay<=defaultDelay then return defaultDelay --if ping is too low: set the minimum delay else return totalDelay --take account for lag + wait a little bit for any command to properly update end end ---------------------------------Level1 ---------------------------------Level2 (level 1's call-in) function RetrieveAttackerList (unitID, attacker) local unitHealth,_,_,_,_ = spGetUnitHealth(unitID) if attacker[unitID] == nil then --if attacker table is empty then fill with default value attacker[unitID] = {id = nil, countDown = 0, myHealth = unitHealth} end if attacker[unitID].countDown >0 then attacker[unitID].countDown = attacker[unitID].countDown - 1 end --count-down until zero and stop if unitHealth< attacker[unitID].myHealth then --if underattack then find out the attackerID local attackerID = spGetUnitLastAttacker(unitID) if attackerID~=nil then --if attackerID is found then mark the attackerID for avoidance attacker[unitID].countDown = attacker[unitID].countDown + 3 --//add 3xUnitRefresh-rate (~3.3second) to attacker's TTL attacker[unitID].id = attackerID end end attacker[unitID].myHealth = unitHealth --refresh health data return attacker end function RefreshWatchdogList (unitID, commandTTL) if commandTTL[unitID] == nil then --if commandTTL table is empty then insert an empty table commandTTL[unitID] = {1,} --Note: first entry is table lenght else --//if commandTTL is not empty then perform check and update its content appropriately. Its not empty when widget has issued a new command --//Method1: the following function do work offline but not online because widget's command appears delayed (latency) and this cause missmatch with what commandTTL expect to see: it doesn't see the command thus it assume the command already been deleted. --[[ local cQueue = spGetCommandQueue(unitID, 1) for i=#commandTTL[unitID], 1, -1 do local firstParam, secondParam = 0, 0 if cQueue[1]~=nil then firstParam, secondParam = cQueue[1].params[1], cQueue[1].params[3] end if (firstParam == commandTTL[unitID][i].widgetCommand[1]) and (secondParam == commandTTL[unitID][i].widgetCommand[2]) then --//if current command is similar to the one once issued by widget then countdown its TTL if commandTTL[unitID][i].countDown >0 then commandTTL[unitID][i].countDown = commandTTL[unitID][i].countDown - 1 --count-down until zero and stop elseif commandTTL[unitID][i].countDown ==0 then --if commandTTL is found to reach ZERO then remove the command, assume a 'TIMEOUT', then remove *this* watchdog entry spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[1].tag}, {} ) commandTTL[unitID][i] = nil end break --//exit the iteration, save the rest of the commandTTL for checking on next update/next cQueue. Since later commandTTL is for cQueue[2](next qeueu) then it is more appropriate to compare it later (currently we only check cQueue[1] for timeout/expiration). else --//if current command is a NEW command (not similar to the one catalogued in commandTTL as widget-issued), then delete this watchdog entry. LUA Operator "#" will automatically register the 'nil' as 'end of table' for future updates commandTTL[unitID][i] = nil --commandTTL[unitID][i].miss = commandTTL[unitID][i].miss +1 --//when unit's command doesn't match the one on watchdog-list then mark the entry as "miss"+1 . end end --]] --//Method2: work by checking for cQueue after the command has expired. No latency could be as long as command's expiration time so it solve Method1's issue. local returnToReclaimOffset = 1 -- for i=commandTTL[unitID][1], 2, -1 do --iterate downward over commandTTL, empty last entry when possible. Note: first table entry is the table's lenght, so we iterate down to only index 2 if commandTTL[unitID][i] ~= nil then if commandTTL[unitID][i].countDown >0 then commandTTL[unitID][i].countDown = commandTTL[unitID][i].countDown - (1*returnToReclaimOffset) --count-down until zero and stop. Each iteration is minus 1 and then exit loop after 1 enty, or when countDown==0 remove command and then go to next entry and minus 2 and exit loop. break --//exit the iteration, do not go to next iteration until this entry expire first... elseif commandTTL[unitID][i].countDown <=0 then --if commandTTL is found to reach ZERO then remove the command, assume a 'TIMEOUT', then remove *this* watchdog entry local cQueue = spGetCommandQueue(unitID, 1) --// get unit's immediate command local firstParam, secondParam = 0, 0 if cQueue[1]~=nil then firstParam, secondParam = cQueue[1].params[1], cQueue[1].params[3] --if cQueue not empty then use it... x, z, end if (firstParam == commandTTL[unitID][i].widgetCommand[1]) and (secondParam == commandTTL[unitID][i].widgetCommand[2]) then --//if current command is similar to the one once issued by widget then delete it spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[1].tag}, {} ) end commandTTL[unitID][i] = nil --empty watchdog entry commandTTL[unitID][1] = i-1 --refresh table lenght returnToReclaimOffset = 2 --when the loop iterate back to a reclaim command: remove 2 second from its countdown (accelerate expiration by 2 second). This is for aesthetic reason and didn't effect system's mechanic. Since constructor always retreat with 2 command (avoidance+return to base), remove the countdown from the avoidance. end end end end return commandTTL end function CheckWeaponsAndShield (unitDef) --global variable local reloadableWeaponCriteria = reloadableWeaponCriteriaG --minimum reload time for reloadable weapon ---- local unitShieldPower, reloadableWeaponIndex =-1, -1 --assume unit has no shield and no reloadable/slow-loading weapons local fastWeaponIndex = -1 --temporary variables local fastestReloadTime, fastReloadRange = 999,-1 for currentWeaponIndex, weapons in ipairs(unitDef.weapons) do --reference: gui_contextmenu.lua by CarRepairer local weaponsID = weapons.weaponDef local weaponsDef = WeaponDefs[weaponsID] if weaponsDef.name and not (weaponsDef.name:find('fake') or weaponsDef.name:find('noweapon')) then --reference: gui_contextmenu.lua by CarRepairer if weaponsDef.isShield then unitShieldPower = weaponsDef.shieldPower --remember the shield power of this unit else --if not shield then this is conventional weapon local reloadTime = weaponsDef.reload if reloadTime < fastestReloadTime then --find the weapon with the smallest reload time fastestReloadTime = reloadTime fastReloadRange = weaponsDef.range fastWeaponIndex = currentWeaponIndex --remember the index of the fastest weapon. end end end end if fastestReloadTime > reloadableWeaponCriteria then --if the fastest reload cycle is greater than widget's update cycle, then: reloadableWeaponIndex = fastWeaponIndex --remember the index of that fastest loading weapon if (turnOnEcho == 1) then --debugging Spring.Echo("reloadableWeaponIndex(CheckWeaponsAndShield):") Spring.Echo(reloadableWeaponIndex) Spring.Echo("fastestReloadTime(CheckWeaponsAndShield):") Spring.Echo(fastestReloadTime) end end return unitShieldPower, reloadableWeaponIndex,fastestReloadTime,fastReloadRange end function GateKeeperOrCommandFilter (cQueue,persistentData, unitInMotionSingleUnit) local allowExecution = false local reloadAvoidance = false -- indicate to way way downstream processes whether avoidance is based on weapon reload/shieldstate if cQueue~=nil then --prevent ?. Forgot... local isReloading = CheckIfUnitIsReloading(unitInMotionSingleUnit) --check if unit is reloading/shieldCritical local unitID = unitInMotionSingleUnit["unitID"] local state=spGetUnitStates(unitID) local holdPosition= (state.movestate == 0) local unitType = unitInMotionSingleUnit["unitType"] local unitInView = unitInMotionSingleUnit["isVisible"] local retreating = false if options.retreatAvoidance.value and WG.retreatingUnits then retreating = (WG.retreatingUnits[unitID]~=nil or spGetUnitRulesParam(unitID,"isRetreating")==1) end --if ((unitInView ~= "yes") or isReloading or (unitType == 1 and options.cloakyAlwaysFlee.value)) then --if unit is out of user's vision OR is reloading OR is cloaky, and: if (cQueue[1] == nil or #cQueue == 1) then --if unit is currently idle OR with-singular-mono-command (eg: automated move order or auto-attack), then: --if (not holdPosition) then --if unit is not "hold position", then: local idleOrIsDodging = (cQueue[1] == nil) or (#cQueue == 1 and cQueue[1].id == CMD_MOVE and (not cQueue[2] or cQueue[2].id~=false)) --is idle completely, or is given widget's CMD_MOVE and not spontaneous engagement signature (note: CMD_MOVE or any other command will not end with CMD_STOP when issued by widget) local dummyCmd if idleOrIsDodging then cQueue={{id = cMD_DummyG, params = {-1 ,-1,-1}, options = {}}, {id = CMD_STOP, params = {-1 ,-1,-1}, options = {}}, nil} --select cMD_DummyG if unit is to flee without need to return to old position, elseif cQueue[1].id < 0 then cQueue[2] = {id = CMD_STOP, params = {-1 ,-1,-1}, options = {}} --automated build (mono command issued by CentralBuildAI widget). We append CMD_STOP so it look like normal build command. else cQueue={{id = cMD_Dummy_atkG, params = {-1 ,-1,-1}, options = {}}, {id = CMD_STOP, params = {-1 ,-1,-1}, options = {}}, nil} --select cMD_Dummy_atkG if unit is auto-attack & reloading (as in: isReloading + (no command or mono command)) and doesn't mind being bound to old position end --flag unit with a FAKE COMMAND. Will be used to initiate avoidance on idle unit & non-viewed unit. Note: this is not real command, its here just to trigger avoidance. --Note2: negative target only deactivate attraction function, but avoidance function is still active & output new coordinate if enemy is around --end end --end if cQueue[1]~=nil then --prevent idle unit from executing the system (prevent crash), but idle unit with FAKE COMMAND (cMD_DummyG) is allowed. local isStealthOrConsUnit = (unitType == 1) local isNotViewed = (unitInView ~= "yes") local isCommonConstructorCmd = (cQueue[1].id == CMD_REPAIR or cQueue[1].id < 0 or cQueue[1].id == CMD_RESURRECT) local isReclaimCmd = (cQueue[1].id == CMD_RECLAIM) local isMoveCommand = (cQueue[1].id == CMD_MOVE) local isNormCommand = (isCommonConstructorCmd or isMoveCommand) -- ALLOW unit with command: repair (40), build (<0), reclaim (90), ressurect(125), move(10), --local isStealthOrConsUnitTypeOrIsNotViewed = isStealthOrConsUnit or (unitInView ~= "yes" and unitType~= 3)--ALLOW only unit of unitType=1 OR (all unitTypes that is outside player's vision except gunship) local isStealthOrConsUnitTypeOrIsNotViewed = isStealthOrConsUnit or isNotViewed--ALLOW unit of unitType=1 (cloaky, constructor) OR all unitTypes that is outside player's vision local _1stAttackSignature = (cQueue[1].id == CMD_ATTACK) local _1stGuardSignature = (cQueue[1].id == CMD_GUARD) local _2ndAttackSignature = false --attack command signature local _2ndGuardSignature = false --guard command signature if #cQueue >=2 then --check if the command-queue is masked by widget's previous command, but the actual originality check will be performed by TargetBoxReached() later. _2ndAttackSignature = (cQueue[1].id == CMD_MOVE and cQueue[2].id == CMD_ATTACK) _2ndGuardSignature = (cQueue[1].id == CMD_MOVE and cQueue[2].id == CMD_GUARD) end local isAbundanceResource = (spGetTeamResources(persistentData["myTeamID"], "metal") > 10) local isReloadingAttack = (isReloading and (((_1stAttackSignature or _2ndAttackSignature) and options.enableReloadAvoidance.value) or (cQueue[1].id == cMD_DummyG or cQueue[1].id == cMD_Dummy_atkG))) --any unit with attack command or was idle that is Reloading local isGuardState = (_1stGuardSignature or _2ndGuardSignature) local isAttackingState = (_1stAttackSignature or _2ndAttackSignature) local isForceCloaked = spGetUnitIsCloaked(unitID) and (unitType==2 or unitType==3) --any unit with type 3 (gunship) or type 2 (ground units except cloaky) that is cloaked. local isRealIdle = cQueue[1].id == cMD_DummyG --FAKE (IDLE) COMMAND local isStealthOrConsUnitAlwaysFlee = isStealthOrConsUnit and options.cloakyAlwaysFlee.value if ((isNormCommand or (isReclaimCmd and isAbundanceResource)) and isStealthOrConsUnitTypeOrIsNotViewed and not holdPosition) or --execute on: unit with generic mobility command (or reclaiming during abundance resource): for UnitType==1 unit (cloaky, constructor) OR for any unit outside player view... & which is not holding position (isRealIdle and (isNotViewed or isStealthOrConsUnitAlwaysFlee) and not holdPosition) or --execute on: any unit that is really idle and out of view... & is not hold position (isReloadingAttack and not holdPosition) or --execute on: any unit which is reloading... & is not holding position -- (isAttackingState and isStealthOrConsUnitAlwaysFlee and not holdPosition) or --execute on: always-fleeing cloaky unit that about to attack... & is not holding position (isGuardState and not holdPosition) or --execute on: any unit which is guarding another unit... & is not hold position (isForceCloaked and isMoveCommand and not holdPosition) or --execute on: any normal unit being cloaked and is moving... & is not hold position. (retreating and not holdPosition) --execute on: any retreating unit then local isReloadAvoidance = (isReloadingAttack and not holdPosition) if isReloadAvoidance or #cQueue>=2 then --check cQueue for lenght to prevent STOP command from short circuiting the system (code downstream expect cQueue of length>=2) if isReloadAvoidance or cQueue[2].id~=false then --prevent a spontaneous enemy engagement from short circuiting the system allowExecution = true --allow execution reloadAvoidance = isReloadAvoidance end --if cQueue[2].id~=false if (turnOnEcho == 1) then Spring.Echo(cQueue[2].id) end --for debugging end --if #cQueue>=2 end --if ((cQueue[1].id==40 or cQueue[1].id<0 or cQueue[1].id==90 or cQueue[1].id==10 or cQueue[1].id==125) and (unitInMotion[i][2]==1 or unitInMotion[i].isVisible == nil) end --if cQueue[1]~=nil end --if cQueue~=nil local output = { cQueueTemp = cQueue, allowExecution = allowExecution, reloadAvoidance = reloadAvoidance, } return output --disallow/allow execution end --check if widget's command or user's command function IdentifyTargetOnCommandQueue(cQueueOri,persistentData,gateKeeperOutput,unitInMotionSingleUnit) --//used by DoCalculation() local unitID = unitInMotionSingleUnit["unitID"] local commandIndexTable = persistentData["commandIndexTable"] local newCommand=true -- immediately assume user's command local output -------------------------------------------------- if commandIndexTable[unitID]==nil then --memory was empty, so fill it with zeros or non-significant number commandIndexTable[unitID]={widgetX=-2, widgetZ=-2 , patienceIndexA=0} else local a = -1 local c = -1 local b = math.modf(commandIndexTable[unitID]["widgetX"]) local d = math.modf(commandIndexTable[unitID]["widgetZ"]) if cQueueOri[1] then a = math.modf(dNil(cQueueOri[1].params[1])) --using math.modf to remove trailing decimal (only integer for matching). In case high resolution cause a fail matching with server's numbers... and use dNil incase wreckage suddenly disappear. c = math.modf(dNil(cQueueOri[1].params[3])) --dNil: if it is a reclaim or repair order (no z coordinate) then replace it with -1 (has similar effect to the "nil") end newCommand= (a~= b and c~=d)--compare current command with in memory if (turnOnEcho == 1) then --debugging Spring.Echo("unitID(IdentifyTargetOnCommandQueue)" .. unitID) Spring.Echo("commandIndexTable[unitID][widgetX](IdentifyTargetOnCommandQueue):" .. commandIndexTable[unitID]["widgetX"]) Spring.Echo("commandIndexTable[unitID][widgetZ](IdentifyTargetOnCommandQueue):" .. commandIndexTable[unitID]["widgetZ"]) Spring.Echo("newCommand(IdentifyTargetOnCommandQueue):") Spring.Echo(newCommand) Spring.Echo("cQueueOri[1].params[1](IdentifyTargetOnCommandQueue):" .. cQueueOri[1].params[1]) Spring.Echo("cQueueOri[1].params[2](IdentifyTargetOnCommandQueue):" .. cQueueOri[1].params[2]) Spring.Echo("cQueueOri[1].params[3](IdentifyTargetOnCommandQueue):" .. cQueueOri[1].params[3]) if cQueueOri[2]~=nil then Spring.Echo("cQueue[2].params[1](IdentifyTargetOnCommandQueue):") Spring.Echo(cQueueOri[2].params[1]) Spring.Echo("cQueue[2].params[3](IdentifyTargetOnCommandQueue):") Spring.Echo(cQueueOri[2].params[3]) end end end if newCommand then --if user's new command output = ExtractTarget (1,gateKeeperOutput["cQueueTemp"],unitInMotionSingleUnit) commandIndexTable[unitID]["patienceIndexA"]=0 --//reset impatience counter else --if widget's previous command output = ExtractTarget (2,gateKeeperOutput["cQueueTemp"],unitInMotionSingleUnit) end output["newCommand"] = newCommand persistentData["commandIndexTable"] = commandIndexTable --note: table is referenced by memory, so it will update even without return value return output --return target coordinate end --ignore command set on this box function TargetBoxReached (unitID, idTargetOutput) ----Global Constant---- local halfTargetBoxSize = halfTargetBoxSize_g ----------------------- local boxSizeTrigger = idTargetOutput["boxSizeTrigger"] local targetCoordinate = idTargetOutput["targetCoordinate"] local currentX,_,currentZ = spGetUnitPosition(unitID) local targetX = dNil(targetCoordinate[1]) -- use dNil if target asynchronously/spontaneously disappear: in that case it will replace "nil" with -1 local targetZ =targetCoordinate[3] if targetX==-1 then return false end --if target is invalid (-1) then assume target not-yet-reached, return false (default state), and continue avoidance local xDistanceToTarget = math.abs(currentX -targetX) local zDistanceToTarget = math.abs(currentZ -targetZ) if (turnOnEcho == 1) then Spring.Echo("unitID(TargetBoxReached)" .. unitID) Spring.Echo("currentX(TargetBoxReached)" .. currentX) Spring.Echo("currentZ(TargetBoxReached)" .. currentZ) Spring.Echo("cx(TargetBoxReached)" .. targetX) Spring.Echo("cz(TargetBoxReached)" .. targetZ) Spring.Echo("(xDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger] and zDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger])(TargetBoxReached):") Spring.Echo((xDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger] and zDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger])) end local withinTargetBox = (xDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger] and zDistanceToTarget<=halfTargetBoxSize[boxSizeTrigger]) return withinTargetBox --command outside this box return false end -- get LOS function GetUnitLOSRadius(case,unitInMotionSingleUnit) ----Global Constant---- local extraLOSRadiusCONSTANT = extraLOSRadiusCONSTANTg ----------------------- local fastestWeapon = unitInMotionSingleUnit["weaponInfo"] local unitID =unitInMotionSingleUnit["unitID"] local unitDefID= spGetUnitDefID(unitID) local unitDef= UnitDefs[unitDefID] local losRadius =550 --arbitrary (scout LOS) if unitDef~=nil then --if unitDef is not empty then use the following LOS losRadius= unitDef.losRadius*LOS_MULT --in normal case use real LOS. Note: for some reason it was times 32 losRadius= losRadius + extraLOSRadiusCONSTANT --add extra detection range for beyond LOS (radar) if case=="attack" then --if avoidance is for attack enemy: use special LOS local unitFastestReloadableWeapon = fastestWeapon["reloadableWeaponIndex"] --retrieve the quickest reloadable weapon index if unitFastestReloadableWeapon ~= -1 then local weaponRange = fastestWeapon["range"] --retrieve weapon range losRadius = math.max(weaponRange*0.75, losRadius) --select avoidance's detection-range to 75% of weapon range or maintain to losRadius, select which is the biggest (Note: big LOSradius mean big detection but also big "distanceCONSTANTunit_G" if "useLOS_distanceCONSTANTunit_G==true", thus bigger avoidance circle) end --[[ local unitShieldRange,fastWeaponRange =-1, -1 --assume unit has no shield and no weapon local fastestReloadTime = 999 --temporary variables for _, weapons in ipairs(unitDef["weapons"]) do --reference: gui_contextmenu.lua by CarRepairer local weaponsID = weapons["weaponDef"] local weaponsDef = WeaponDefs[weaponsID] if weaponsDef["name"] and not (weaponsDef["name"]:find('fake') or weaponsDef["name"]:find('noweapon')) then --reference: gui_contextmenu.lua by CarRepairer if weaponsDef["isShield"] then unitShieldRange = weaponsDef["shieldRadius"] --remember the shield radius of this unit else --if not shield then this is conventional weapon local reloadTime = weaponsDef["reload"] if reloadTime < fastestReloadTime then --find the weapon with the smallest reload time fastestReloadTime = reloadTime fastWeaponRange = weaponsDef["range"] --remember the range of the fastest weapon. end end end end --]] end if unitDef.isBuilder then losRadius = losRadius + extraLOSRadiusCONSTANT --add additional/more detection range for constructors for quicker reaction vs enemy radar dot end end return losRadius end --return a table of surrounding enemy function GetAllUnitsInRectangle(unitID, losRadius, attacker,excludedEnemyID) local x,y,z = spGetUnitPosition(unitID) local unitDefID = spGetUnitDefID(unitID) local unitDef = UnitDefs[unitDefID] local iAmConstructor = unitDef.isBuilder local iAmNotCloaked = not spGetUnitIsCloaked(unitID) --unitID is "this" unit (our unit) local unitsInRectangle = spGetUnitsInRectangle(x-losRadius, z-losRadius, x+losRadius, z+losRadius) local relevantUnit={} local arrayIndex=0 --add attackerID into enemy list relevantUnit, arrayIndex = AddAttackerIDToEnemyList (unitID, losRadius, relevantUnit, arrayIndex, attacker) -- for _, rectangleUnitID in ipairs(unitsInRectangle) do local isAlly= spIsUnitAllied(rectangleUnitID) if (rectangleUnitID ~= unitID) and not isAlly and rectangleUnitID~=excludedEnemyID then --filter out ally units and self and exclusive-exclusion local rectangleUnitTeamID = spGetUnitTeam(rectangleUnitID) if (rectangleUnitTeamID ~= gaiaTeamID) then --filter out gaia (non aligned unit) local recUnitDefID = spGetUnitDefID(rectangleUnitID) local registerEnemy = false if recUnitDefID~=nil and (iAmConstructor and iAmNotCloaked) then --if enemy is in LOS & I am a visible constructor: then local recUnitDef = UnitDefs[recUnitDefID] --retrieve enemy definition local enemyParalyzed,_,_ = spGetUnitIsStunned (rectangleUnitID) local disarmed = spGetUnitRulesParam(rectangleUnitID,"disarmed") if recUnitDef["weapons"][1]~=nil and not enemyParalyzed and (not disarmed or disarmed ~= 1) then -- check enemy for weapons and paralyze effect registerEnemy = true --register the enemy only if it armed & wasn't paralyzed end else --if enemy is detected (in LOS or RADAR), and iAm a generic units OR any cloaked constructor then: if iAmNotCloaked then --if I am not cloaked local enemyParalyzed,_,_ = Spring.GetUnitIsStunned (rectangleUnitID) if not enemyParalyzed then -- check for paralyze effect registerEnemy = true --register enemy if it's not paralyzed end else --if I am cloaked (constructor or cloakies), then: registerEnemy = true --register all enemy (avoid all unit) end end if registerEnemy then arrayIndex=arrayIndex+1 relevantUnit[arrayIndex]=rectangleUnitID --register enemy end end end end relevantUnit["count"] = arrayIndex return relevantUnit end --allow a unit to recognize fleeing enemy; so it doesn't need to avoid them function CatalogueMovingObject(surroundingUnits, unitID,losRadius) local unitsSeparation={} if (surroundingUnits["count"] and surroundingUnits["count"]>0) then --don't catalogue anything if no enemy exist local unitDepth = 99 local sonarDetected = false local halfLosRadius = losRadius/2 --if unitType == 4 then --//if unit is amphibious, then: _,unitDepth,_ = spGetUnitPosition(unitID) --//get unit's y-axis. Less than 0 mean submerged. --end local unitXvel,_,unitZvel = spGetUnitVelocity(unitID) local unitSpeed = math.sqrt(unitXvel*unitXvel+unitZvel*unitZvel) for i=1,surroundingUnits["count"],1 do --//iterate over all enemy list. local unitRectangleID=surroundingUnits[i] if (unitRectangleID ~= nil) then local recXvel,_,recZvel = spGetUnitVelocity(unitRectangleID) recXvel = recXvel or 0 recZvel = recZvel or 0 local recSpeed = math.sqrt(recXvel*recXvel+recZvel*recZvel) local relativeAngle = GetUnitRelativeAngle (unitID, unitRectangleID) local unitDirection,_,_ = GetUnitDirection(unitID) local unitSeparation = spGetUnitSeparation (unitID, unitRectangleID, true) if math.abs(unitDirection- relativeAngle)< (collisionAngleG) or (recSpeed>3*unitSpeed) then --unit inside the collision angle? or is super fast? remember unit currrent saperation for comparison again later unitsSeparation[unitRectangleID]=unitSeparation else --unit outside the collision angle? set to an arbitrary 9999 which mean "do not need comparision, always avoid" unitsSeparation[unitRectangleID]=9999 end if unitDepth <0 then --//if unit is submerged, then: --local enemySonarRadius = (spGetUnitSensorRadius(unitRectangleID,"sonar") or 0) local enemyDefID = spGetUnitDefID(unitRectangleID) local unitDefsSonarContent = 9999 --//set to very large so that any un-identified contact is assumed as having sonar (as threat). if UnitDefs[enemyDefID]~=nil then unitDefsSonarContent = UnitDefs[enemyDefID].sonarRadius end local enemySonarRadius = (unitDefsSonarContent or 0) if enemySonarRadius > halfLosRadius then --//check enemy for sonar sonarDetected = true end end end end if (not sonarDetected) and (unitDepth < 0) then --//if enemy doesn't have sonar but Iam still submerged, then: losRadius = halfLosRadius --// halven the unit's 'avoidance' range. Don't need to avoid enemy if enemy are blind. end end if (turnOnEcho == 1) then Spring.Echo("unitSeparation(CatalogueMovingObject):") Spring.Echo(unitsSeparation) end return unitsSeparation, losRadius end function GetImpatience(idTargetOutput,unitID, persistentData) local newCommand = idTargetOutput["newCommand"] local commandIndexTable = persistentData["commandIndexTable"] local impatienceTrigger=1 --zero will de-activate auto reverse if commandIndexTable[unitID]["patienceIndexA"]>=6 then impatienceTrigger=0 end --//if impatience index level 6 (after 6 time avoidance) then trigger impatience. Impatience will deactivate/change some values downstream if not newCommand and activateImpatienceG==1 then commandIndexTable[unitID]["patienceIndexA"]=commandIndexTable[unitID]["patienceIndexA"]+1 --increase impatience index if impatience system is activate end if (turnOnEcho == 1) then Spring.Echo("commandIndexTable[unitID][patienceIndexA] (GetImpatienceLevel) " .. commandIndexTable[unitID]["patienceIndexA"]) end persistentData["commandIndexTable"] = commandIndexTable --Note: this will update since its referenced by memory return impatienceTrigger end function UseNearbyAllyAsTarget(unitID, persistentData) local x,y,z = -1,-1,-1 if WG.OPTICS_cluster then local allyClusterInfo = persistentData["allyClusterInfo"] local myTeamID = persistentData["myTeamID"] if (allyClusterInfo["age"]>= 3) then --//only update after 4 cycle: allyClusterInfo["age"]= 0 allyClusterInfo["coords"] = {} local allUnits = spGetAllUnits() local unorderedUnitList = {} for i=1, #allUnits, 1 do --//convert unit list into a compatible format for the Clustering function below local unitID_list = allUnits[i] if spIsUnitAllied(unitID_list, unitID) then local x,y,z = spGetUnitPosition(unitID_list) local unitDefID_list = spGetUnitDefID(unitID_list) local unitDef = UnitDefs[unitDefID_list] local unitSpeed =unitDef["speed"] if (unitSpeed>0) then --//if moving units if (unitDef.isBuilder) and not unitDef.customParams.commtype then --if constructor --intentionally empty. Not include builder. elseif unitDef.customParams.commtype then --if COMMANDER, unorderedUnitList[unitID_list] = {x,y,z} --//store elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) then --if all ground unit, amphibious, and ships (except commander) unorderedUnitList[unitID_list] = {x,y,z} --//store elseif (unitDef.hoverAttack== true) then --if gunships --intentionally empty. Not include gunships. end else --if buildings unorderedUnitList[unitID_list] = {x,y,z} --//store end end end local cluster, _ = WG.OPTICS_cluster(unorderedUnitList, 600,3, myTeamID,300) --//find clusters with atleast 3 unit per cluster and with at least within 300-elmo from each other for index=1 , #cluster do local sumX, sumY,sumZ, unitCount,meanX, meanY, meanZ = 0,0 ,0 ,0 ,0,0,0 for unitIndex=1, #cluster[index] do local unitID_list = cluster[index][unitIndex] local x,y,z= unorderedUnitList[unitID_list][1],unorderedUnitList[unitID_list][2],unorderedUnitList[unitID_list][3] --// get stored unit position sumX= sumX+x sumY = sumY+y sumZ = sumZ+z unitCount=unitCount+1 end meanX = sumX/unitCount --//calculate center of cluster meanY = sumY/unitCount meanZ = sumZ/unitCount allyClusterInfo["coords"][#allyClusterInfo["coords"]+1] = {meanX, meanY, meanZ} --//record cluster position end end --//end cluster detection local nearestCluster = -1 local nearestDistance = 99999 local coordinateList = allyClusterInfo["coords"] local px,_,pz = spGetUnitPosition(unitID) for i=1, #coordinateList do local distance = Distance(coordinateList[i][1], coordinateList[i][3] , px, pz) if distance < nearestDistance then nearestDistance = distance nearestCluster = i end end if nearestCluster > 0 then x,y,z = coordinateList[nearestCluster][1],coordinateList[nearestCluster][2],coordinateList[nearestCluster][3] end persistentData["allyClusterInfo"] = allyClusterInfo --update content end if x == -1 then local nearbyAllyUnitID = Spring.GetUnitNearestAlly (unitID, 600) if nearbyAllyUnitID ~= nearbyAllyUnitID then x,y,z = spGetUnitPosition(nearbyAllyUnitID) end end return {x,y,z} end function AvoidanceCalculator(losRadius,surroundingUnits,unitsSeparation,impatienceTrigger,persistentData,idTargetOutput,unitInMotionSingleUnit) local newCommand = idTargetOutput["newCommand"] local skippingTimer = persistentData["skippingTimer"] local unitID = unitInMotionSingleUnit["unitID"] local unitSpeed = unitInMotionSingleUnit["unitSpeed"] local graphCONSTANTtrigger = idTargetOutput["graphCONSTANTtrigger"] local fixedPointCONSTANTtrigger = idTargetOutput["fixedPointCONSTANTtrigger"] local targetCoordinate = idTargetOutput["targetCoordinate"] local decloakScaling = unitInMotionSingleUnit["decloakScaling"] if (unitID~=nil) and (targetCoordinate ~= nil) then --prevent idle/non-existent/ unit with invalid command from using collision avoidance local aCONSTANT = aCONSTANTg --attractor constant (amplitude multiplier) local obsCONSTANT =obsCONSTANTg --repulsor constant (amplitude multiplier) local unitDirection, _, wasMoving = GetUnitDirection(unitID) --get unit direction local targetAngle = 0 local fTarget = 0 local fTargetSlope = 0 ---- aCONSTANT = aCONSTANT[graphCONSTANTtrigger[1]] --//select which 'aCONSTANT' value obsCONSTANT = obsCONSTANT[graphCONSTANTtrigger[2]]*decloakScaling --//select which 'obsCONSTANT' value to use & increase obsCONSTANT value when unit has larger decloakDistance than reference unit (Scythe). fTarget = aCONSTANT --//maximum value is aCONSTANT fTargetSlope = 1 --//slope is negative or positive if targetCoordinate[1]~=-1 then --if target coordinate contain -1 then disable target for pure avoidance targetAngle = GetTargetAngleWithRespectToUnit(unitID, targetCoordinate) --get target angle fTarget = GetFtarget (aCONSTANT, targetAngle, unitDirection) fTargetSlope = GetFtargetSlope (aCONSTANT, targetAngle, unitDirection, fTarget) --local targetSubtendedAngle = GetTargetSubtendedAngle(unitID, targetCoordinate) --get target 'size' as viewed by the unit end local sumAllUnitOutput = { wTotal = nil, dSum = nil, fObstacleSum = nil, dFobstacle = nil, nearestFrontObstacleRange = nil, normalizingFactor = nil, } --count every enemy unit and sum its contribution to the obstacle/repulsor variable sumAllUnitOutput=SumAllUnitAroundUnitID (obsCONSTANT,unitDirection,losRadius,surroundingUnits,unitsSeparation,impatienceTrigger,graphCONSTANTtrigger,unitInMotionSingleUnit,skippingTimer) --calculate appropriate behaviour based on the constant and above summation value local wTarget, wObstacle = CheckWhichFixedPointIsStable (fTargetSlope, fTarget, fixedPointCONSTANTtrigger,sumAllUnitOutput) --convert an angular command into a coordinate command local newX, newZ= ToCoordinate(wTarget, wObstacle, fTarget, unitDirection, losRadius, impatienceTrigger, skippingTimer, wasMoving, newCommand,sumAllUnitOutput, unitInMotionSingleUnit) if (turnOnEcho == 1) then Spring.Echo("unitID(AvoidanceCalculator)" .. unitID) Spring.Echo("targetAngle(AvoidanceCalculator) " .. targetAngle) Spring.Echo("unitDirection(AvoidanceCalculator) " .. unitDirection) Spring.Echo("fTarget(AvoidanceCalculator) " .. fTarget) Spring.Echo("fTargetSlope(AvoidanceCalculator) " .. fTargetSlope) --Spring.Echo("targetSubtendedAngle(AvoidanceCalculator) " .. targetSubtendedAngle) Spring.Echo("wTotal(AvoidanceCalculator) " .. wTotal) Spring.Echo("dSum(AvoidanceCalculator) " .. dSum) Spring.Echo("fObstacleSum(AvoidanceCalculator) " .. fObstacleSum) Spring.Echo("dFobstacle(AvoidanceCalculator) " .. dFobstacle) Spring.Echo("nearestFrontObstacleRange(AvoidanceCalculator) " .. nearestFrontObstacleRange) Spring.Echo("wTarget(AvoidanceCalculator) " .. wTarget) Spring.Echo("wObstacle(AvoidanceCalculator) " .. wObstacle) Spring.Echo("newX(AvoidanceCalculator) " .. newX) Spring.Echo("newZ(AvoidanceCalculator) " .. newZ) end return newX, newZ --return move coordinate end end -- maintain the visibility of original command -- reference: "unit_tactical_ai.lua" -ZeroK gadget by Google Frog function InsertCommandQueue(unitID,cQueue,cQueueGKPed,newCommand,persistentData) ------- localize global constant: local consRetreatTimeout = consRetreatTimeoutG local commandTimeout = commandTimeoutG ------- end global constant local now = persistentData["now"] local commandTTL = persistentData["commandTTL"] local commandIndexTable = persistentData["commandIndexTable"] ------- --Method 1: doesn't work online --if not newCommand then spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[1].tag}, {} ) end --delete old command -- spGiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_MOVE, CMD_OPT_INTERNAL, newX, newY, newZ}, {"alt"} ) --insert new command ---- --Method 2: doesn't work online -- if not newCommand then spGiveOrderToUnit(unitID, CMD_MOVE, {cQueue[1].params[1],cQueue[1].params[2],cQueue[1].params[3]}, {"ctrl","shift"} ) end --delete old command -- spGiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_MOVE, CMD_OPT_INTERNAL, newX, newY, newZ}, {"alt"} ) --insert new command ---- --Method 3.5: cause big movement noise -- newX = Round(newX) -- newY = Round(newY) -- newZ = Round(newZ) ---- --Method 3: work online, but under rare circumstances doesn't work -- spGiveOrderToUnit(unitID, CMD.STOP, {}, {}) -- spGiveOrderToUnit(unitID, CMD_MOVE, {newX, newY, newZ}, {} ) -- local arrayIndex=1 -- if not newCommand then arrayIndex=2 end --skip old widget command -- if #cQueue>=2 then --try to identify unique signature of area reclaim/repair -- if (cQueue[1].id==40 or cQueue[1].id==90 or cQueue[1].id==125) then -- if cQueue[2].id==90 or cQueue[2].id==125 then -- if (not Spring.ValidFeatureID(cQueue[2].params[1]-wreckageID_offset) or (not Spring.ValidFeatureID(cQueue[2].params[1]))) and not Spring.ValidUnitID(cQueue[2].params[1]) then --if it is an area command -- spGiveOrderToUnit(unitID, CMD_MOVE, cQueue[2].params, {} ) --divert unit to the center of reclaim/repair command -- arrayIndex=arrayIndex+1 --skip the target:wreck/units. Allow command reset -- end -- elseif cQueue[2].id==40 then -- if (not Spring.ValidFeatureID(cQueue[2].params[1]-wreckageID_offset) or (not Spring.ValidFeatureID(cQueue[2].params[1]))) and not Spring.ValidUnitID(cQueue[2].params[1]) then --if it is an area command -- arrayIndex=arrayIndex+1 --skip the target:units. Allow continuous command reset -- end -- end -- end -- end -- for b = arrayIndex, #cQueue,1 do --re-do user's optional command -- local options={"shift",nil,nil,nil} -- local optionsIndex=2 -- if cQueue[b].options["alt"] then -- options[optionsIndex]="alt" -- end -- if cQueue[b].options["ctrl"] then -- optionsIndex=optionsIndex+1 -- options[optionsIndex]="ctrl" -- end -- if cQueue[b].options["right"] then -- optionsIndex=optionsIndex+1 -- options[optionsIndex]="right" -- end -- spGiveOrderToUnit(unitID, cQueue[b].id, cQueue[b].params, options) --replace the rest of the command -- end --Method 4: with network delay detection won't do any problem local orderArray={nil,nil,nil,nil,nil,nil} local queueIndex=1 local avoidanceCommand = true if not newCommand then --if widget's command then delete it if not cQueue or not cQueue[1] then --happen when unit has NIL command (this), and somehow is same as widget's command (see: IdentifyTargetOnCommandQueue), and somehow unit currently has mono-command (see: CheckUserOverride) if turnOnEcho==2 then Spring.Echo("UnitIsDead (InsertCommandQueue):") Spring.Echo(Spring.GetUnitIsDead(unitID)) Spring.Echo("ValidUnitID (InsertCommandQueue):") Spring.Echo(Spring.ValidUnitID(unitID)) Spring.Echo("WidgetX (InsertCommandQueue):") Spring.Echo(commandIndexTable[unitID]["widgetX"]) Spring.Echo("WidgetZ (InsertCommandQueue):") Spring.Echo(commandIndexTable[unitID]["widgetZ"]) end else orderArray[1] = {CMD_REMOVE, {cQueue[1].tag}, {}} --spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[1].tag}, {} ) --delete previous widget command local lastIndx = commandTTL[unitID][1] --commandTTL[unitID]'s table lenght commandTTL[unitID][lastIndx] = nil --//delete the last watchdog entry (the "not newCommand" means that previous widget's command haven't changed yet (nothing has interrupted this unit, same is with commandTTL), and so if command is to delete then it is good opportunity to also delete its timeout info at *commandTTL* too). Deleting this entry mean that this particular command will no longer be checked for timeout. commandTTL[unitID][1] = lastIndx -1 --refresh table lenght -- Technical note: emptying commandTTL[unitID][#commandTTL[unitID]] is not technically required (not emptying it only make commandTTL countdown longer, but a mistake in emptying a commandTTL could make unit more prone to stuck when fleeing to impassable coordinate. queueIndex=2 --skip index 1 of stored command. Skip widget's command end end if (#cQueue>=queueIndex+1) then --if is queue={reclaim, area reclaim,stop}, or: queue={move,reclaim, area reclaim,stop}, or: queue={area reclaim, stop}, or:queue={move, area reclaim, stop}. if (cQueue[queueIndex].id==CMD_REPAIR or cQueue[queueIndex].id==CMD_RECLAIM or cQueue[queueIndex].id==CMD_RESURRECT) then --if first (1) queue is reclaim/ressurect/repair if cQueue[queueIndex+1].id==CMD_RECLAIM or cQueue[queueIndex+1].id==CMD_RESURRECT then --if second (2) queue is also reclaim/ressurect --if (not Spring.ValidFeatureID(cQueue[queueIndex+1].params[1]-Game.maxUnits) or (not Spring.ValidFeatureID(cQueue[queueIndex+1].params[1]))) and not Spring.ValidUnitID(cQueue[queueIndex+1].params[1]) then --if it was an area command if (cQueue[queueIndex+1].params[4]~=nil) then --second (2) queue is area reclaim. area command should has no "nil" on params 1,2,3, & 4 orderArray[#orderArray+1] = {CMD_REMOVE, {cQueue[queueIndex].tag}, {}} -- spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[queueIndex].tag}, {} ) --delete latest reclaiming/ressurecting command (skip the target:wreck/units). Allow command reset local coordinate = (FindSafeHavenForCons(unitID, now)) or (cQueue[queueIndex+1]) orderArray[#orderArray+1] = {CMD_INSERT, {0, CMD_MOVE, CMD_OPT_INTERNAL, coordinate.params[1], coordinate.params[2], coordinate.params[3]}, {"alt"}} --spGiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_MOVE, CMD_OPT_INTERNAL, coordinate.params[1], coordinate.params[2], coordinate.params[3]}, {"alt"} ) --divert unit to the center of reclaim/repair command OR to any heavy concentration of ally (haven) local lastIndx = commandTTL[unitID][1] --commandTTL[unitID]'s table lenght commandTTL[unitID][lastIndx +1] = {countDown = consRetreatTimeout, widgetCommand= {coordinate.params[1], coordinate.params[3]}} --//remember this command on watchdog's commandTTL table. It has 15x*RefreshUnitUpdateRate* to expire commandTTL[unitID][1] = lastIndx +1--refresh table lenght avoidanceCommand = false end elseif cQueue[queueIndex+1].id==CMD_REPAIR then --if second (2) queue is also repair --if (not Spring.ValidFeatureID(cQueue[queueIndex+1].params[1]-Game.maxUnits) or (not Spring.ValidFeatureID(cQueue[queueIndex+1].params[1]))) and not Spring.ValidUnitID(cQueue[queueIndex+1].params[1]) then --if it was an area command if (cQueue[queueIndex+1].params[4]~=nil) then --area command should has no "nil" on params 1,2,3, & 4 orderArray[#orderArray+1] = {CMD_REMOVE, {cQueue[queueIndex].tag}, {}} --spGiveOrderToUnit(unitID, CMD_REMOVE, {cQueue[queueIndex].tag}, {} ) --delete current repair command, (skip the target:units). Reset the repair command end elseif (cQueue[queueIndex].params[4]~=nil) then --if first (1) queue is area reclaim (an area reclaim without any wreckage to reclaim). area command should has no "nil" on params 1,2,3, & 4 local coordinate = (FindSafeHavenForCons(unitID, now)) or (cQueue[queueIndex]) orderArray[#orderArray+1] = {CMD_INSERT, {0, CMD_MOVE, CMD_OPT_INTERNAL, coordinate.params[1], coordinate.params[2], coordinate.params[3]}, {"alt"}} --spGiveOrderToUnit(unitID, CMD_INSERT, {0, CMD_MOVE, CMD_OPT_INTERNAL, coordinate.params[1], coordinate.params[2], coordinate.params[3]}, {"alt"} ) --divert unit to the center of reclaim/repair command local lastIndx = commandTTL[unitID][1] --commandTTL[unitID]'s table lenght commandTTL[unitID][lastIndx+1] = {countDown = commandTimeout, widgetCommand= {coordinate.params[1], coordinate.params[3]}} --//remember this command on watchdog's commandTTL table. It has 2x*RefreshUnitUpdateRate* to expire commandTTL[unitID][1] = lastIndx +1--refresh table lenght avoidanceCommand = false end end end if (turnOnEcho == 1) then Spring.Echo("unitID(InsertCommandQueue)" .. unitID) Spring.Echo("newCommand(InsertCommandQueue):") Spring.Echo(newCommand) Spring.Echo("cQueue[1].params[1](InsertCommandQueue):" .. cQueue[1].params[1]) Spring.Echo("cQueue[1].params[3](InsertCommandQueue):" .. cQueue[1].params[3]) if cQueue[2]~=nil then Spring.Echo("cQueue[2].params[1](InsertCommandQueue):") Spring.Echo(cQueue[2].params[1]) Spring.Echo("cQueue[2].params[3](InsertCommandQueue):") Spring.Echo(cQueue[2].params[3]) end end persistentData["commandTTL"] = commandTTL ----return updated memory tables used to check for command's expiration age. return avoidanceCommand, orderArray --return whether new command is to be issued end ---------------------------------Level2 ---------------------------------Level3 (low-level function) --check if unit is vulnerable/reloading function CheckIfUnitIsReloading(unitInMotionSingleUnitTable) ---Global Constant--- local criticalShieldLevel =criticalShieldLevelG local minimumRemainingReloadTime =minimumRemainingReloadTimeG local secondPerGameFrame =secondPerGameFrameG ------ --local unitType = unitInMotionSingleUnitTable["unitType"] --retrieve stored unittype local shieldIsCritical =false local weaponIsEmpty = false local fastestWeapon = unitInMotionSingleUnitTable["weaponInfo"] --if unitType ==2 or unitType == 1 then local unitID = unitInMotionSingleUnitTable["unitID"] --retrieve stored unitID local unitShieldPower = fastestWeapon["unitShieldPower"] --retrieve registered full shield power if unitShieldPower ~= -1 then local _, currentPower = spGetUnitShieldState(unitID) if currentPower~=nil then if currentPower/unitShieldPower <criticalShieldLevel then shieldIsCritical = true end end end local unitFastestReloadableWeapon = fastestWeapon["reloadableWeaponIndex"] --retrieve the quickest reloadable weapon index local fastestReloadTime = fastestWeapon["reloadTime"] --in second if unitFastestReloadableWeapon ~= -1 then -- local unitSpeed = unitInMotionSingleUnitTable["unitSpeed"] -- local distancePerSecond = unitSpeed -- local fastUnit_shortRange = unitSpeed > fastestWeapon["range"] --check if unit can exit range easily if *this widget* evasion is activated -- local unitValidForReloadEvasion = true -- if fastUnit_shortRange then -- unitValidForReloadEvasion = fastestReloadTime > 2.5 --check if unit will have enough time to return from *this widget* evasion -- end -- if unitValidForReloadEvasion then local weaponReloadFrame = spGetUnitWeaponState(unitID, unitFastestReloadableWeapon, "reloadFrame") --Somehow the weapon table actually start at "0", so minus 1 from actual value local currentFrame, _ = spGetGameFrame() local remainingTime = (weaponReloadFrame - currentFrame)*secondPerGameFrame --convert to second -- weaponIsEmpty = (remainingTime > math.max(minimumRemainingReloadTime,fastestReloadTime*0.25)) weaponIsEmpty = (remainingTime > minimumRemainingReloadTime) if (turnOnEcho == 1) then --debugging Spring.Echo(unitFastestReloadableWeapon) Spring.Echo(fastestWeapon["range"]) end -- end end --end return (weaponIsEmpty or shieldIsCritical) end -- debugging method, used to quickly remove nil function dNil(x) if x==nil then x=-1 end return x end function ExtractTarget (queueIndex, cQueue,unitInMotionSingleUnit) --//used by IdentifyTargetOnCommandQueue() local unitID = unitInMotionSingleUnit["unitID"] local targetCoordinate = {nil,nil,nil} local fixedPointCONSTANTtrigger = unitInMotionSingleUnit["fixedPointType"] local unitVisible = (unitInMotionSingleUnit["isVisible"]== "yes") local weaponRange = unitInMotionSingleUnit["weaponInfo"]["range"] local weaponType = unitInMotionSingleUnit["weaponType"] local boxSizeTrigger=0 --an arbitrary constant/variable, which trigger some other action/choice way way downstream. The purpose is to control when avoidance must be cut-off using custom value (ie: 1,2,3,4) for specific cases. local graphCONSTANTtrigger = {} local case="" local targetID=nil ------------------------------------------------ if (cQueue[queueIndex].id==CMD_MOVE or cQueue[queueIndex].id<0) then --move or building stuff local targetPosX, targetPosY, targetPosZ = -1, -1, -1 -- (-1) is default value because -1 represent "no target" if cQueue[queueIndex].params[1]~= nil and cQueue[queueIndex].params[2]~=nil and cQueue[queueIndex].params[3]~=nil then --confirm that the coordinate exist targetPosX, targetPosY, targetPosZ = cQueue[queueIndex].params[1], cQueue[queueIndex].params[2],cQueue[queueIndex].params[3] -- elseif cQueue[queueIndex].params[1]~= nil then --check whether its refering to a nanoframe -- local nanoframeID = cQueue[queueIndex].params[1] -- targetPosX, targetPosY, targetPosZ = spGetUnitPosition(nanoframeID) -- if (turnOnEcho == 2)then Spring.Echo("ExtractTarget, MoveCommand: is using nanoframeID") end else if (turnOnEcho == 2)then local defID = spGetUnitDefID(unitID) local ud = UnitDefs[defID or -1] if ud then Spring.Echo("Dynamic Avoidance move/build target is nil: fallback to no target " .. ud.humanName)--certain command has negative id but nil parameters. This is unknown command. ie: -32 else Spring.Echo("Dynamic Avoidance move/build target is nil: fallback to no target") end end end boxSizeTrigger=1 --//avoidance deactivation 'halfboxsize' for MOVE command graphCONSTANTtrigger[1] = 1 --use standard angle scale (take ~10 cycle to do 180 flip, but more predictable) graphCONSTANTtrigger[2] = 1 if #cQueue >= queueIndex+1 then --this make unit retreating (that don't have safe haven coordinate) after reclaiming/ressurecting to have no target (and thus will retreat toward random position). if cQueue[queueIndex+1].id==CMD_RECLAIM or cQueue[queueIndex+1].id==CMD_RESURRECT then --//reclaim command has 2 stage: 1 is move back to base, 2 is going reclaim. If detected reclaim or ressurect at 2nd queue then identify as area reclaim if (cQueue[queueIndex].params[1]==cQueue[queueIndex+1].params[1] and cQueue[queueIndex].params[2]==cQueue[queueIndex+1].params[2] --if retreat position equal to area reclaim/resurrect center (only happen if no safe haven coordinate detected) and cQueue[queueIndex].params[3]==cQueue[queueIndex+1].params[3]) or (cQueue[queueIndex].params[1]==cQueue[queueIndex+1].params[2] and cQueue[queueIndex].params[2]==cQueue[queueIndex+1].params[3] --this 2nd condition happen when there is wreck to reclaim and the first params is the featureID. and cQueue[queueIndex].params[3]==cQueue[queueIndex+1].params[4]) then --area reclaim will have no "nil", and will equal to retreat coordinate when retreating to center of area reclaim. targetPosX, targetPosY, targetPosZ = -1, -1, -1 --//if area reclaim under the above condition, then avoid forever in presence of enemy, ELSE if no enemy (no avoidance): it reach retreat point and resume reclaiming boxSizeTrigger=1 --//avoidance deactivation 'halfboxsize' for MOVE command end end end targetCoordinate={targetPosX, targetPosY, targetPosZ } --send away the target for move command case = 'movebuild' elseif cQueue[queueIndex].id==CMD_RECLAIM or cQueue[queueIndex].id==CMD_RESURRECT then --reclaim or ressurect -- local a = Spring.GetUnitCmdDescs(unitID, Spring.FindUnitCmdDesc(unitID, 90), Spring.FindUnitCmdDesc(unitID, 90)) -- Spring.Echo(a[queueIndex]["name"]) local wreckPosX, wreckPosY, wreckPosZ = -1, -1, -1 -- -1 is default value because -1 represent "no target" local areaMode = false local foundMatch = false --Method 1: set target to individual wreckage, else (if failed) revert to center of current area-command or to no target. -- [[ local posX, posY, posZ = GetUnitOrFeaturePosition(cQueue[queueIndex].params[1]) if posX then foundMatch=true wreckPosX, wreckPosY, wreckPosZ = posX, posY, posZ targetID = cQueue[queueIndex].params[1] end if foundMatch then --next: check if this is actually an area reclaim/ressurect if cQueue[queueIndex].params[4] ~= nil then --area reclaim should has no "nil" on params 1,2,3, & 4 and in this case params 1 contain featureID/unitID because its the 2nd part of the area-reclaim command that reclaim wreck/target areaMode = true wreckPosX, wreckPosY,wreckPosZ = cQueue[queueIndex].params[2], cQueue[queueIndex].params[3],cQueue[queueIndex].params[4] end elseif cQueue[queueIndex].params[4] ~= nil then --1st part of the area-reclaim command (an empty area-command) areaMode = true wreckPosX, wreckPosY,wreckPosZ = cQueue[queueIndex].params[1], cQueue[queueIndex].params[2],cQueue[queueIndex].params[3] else --have no unit match but have no area coordinate either, but is RECLAIM command, something must be wrong: if (turnOnEcho == 2)then Spring.Echo("Dynamic Avoidance reclaim targetting failure: fallback to no target") end end --]] --Method 2: set target to center of area command (also check for area command in next queue), else set target to wreckage or to no target. *This method assume retreat to base is a norm* --[[ if (cQueue[queueIndex].params[4] ~= nil) then --area reclaim should has no "nil" on params 1,2,3, & 4 while single reclaim has unit/featureID in params 1 only wreckPosX, wreckPosY,wreckPosZ = cQueue[queueIndex].params[1], cQueue[queueIndex].params[2],cQueue[queueIndex].params[3] areaMode = true foundMatch = true elseif (cQueue[queueIndex+1].params[4] ~= nil and (cQueue[queueIndex+1].id==CMD_RECLAIM or cQueue[queueIndex+1].id==CMD_RESURRECT)) then --if next queue is an area-reclaim wreckPosX, wreckPosY,wreckPosZ = cQueue[queueIndex+1].params[1], cQueue[queueIndex+1].params[2],cQueue[queueIndex+1].params[3] areaMode = true foundMatch = true end if not areaMode then local posX, posY, posZ = GetUnitOrFeaturePosition(cQueue[queueIndex].params[1]) if posX then foundMatch = true wreckPosX, wreckPosY, wreckPosZ = posX, posY, posZ end end if not foundMatch then --if no area-command, no wreckage, no trees, no rock, and no unitID then return error if (turnOnEcho == 2)then Spring.Echo("Dynamic Avoidance reclaim targetting failure: fallback to no target") end end --]] targetCoordinate={wreckPosX, wreckPosY,wreckPosZ} --use wreck/center-of-area-command as target --graphCONSTANTtrigger[1] = 2 --use bigger angle scale for initial avoidance: after that is a MOVE command to the center or area-command which uses standard angle scale (take ~4 cycle to do 180 flip, but more chaotic) --graphCONSTANTtrigger[2] = 2 graphCONSTANTtrigger[1] = 1 --use standard angle scale (take ~10 cycle to do 180 flip, but more predictable) graphCONSTANTtrigger[2] = 1 boxSizeTrigger=2 --use deactivation 'halfboxsize' for RECLAIM/RESURRECT command if not areaMode then --signature for discrete RECLAIM/RESURRECT command. boxSizeTrigger = 1 --change to deactivation 'halfboxsize' similar to MOVE command if user queued a discrete reclaim/ressurect command --graphCONSTANTtrigger[1] = 1 --override: use standard angle scale (take ~10 cycle to do 180 flip, but more predictable) --graphCONSTANTtrigger[2] = 1 end case = 'reclaimressurect' elseif cQueue[queueIndex].id==CMD_REPAIR then --repair command local unitPosX, unitPosY, unitPosZ = -1, -1, -1 -- (-1) is default value because -1 represent "no target" local targetUnitID=cQueue[queueIndex].params[1] if spValidUnitID(targetUnitID) then --if has unit ID unitPosX, unitPosY, unitPosZ = spGetUnitPosition(targetUnitID) targetID = targetUnitID elseif cQueue[queueIndex].params[1]~= nil and cQueue[queueIndex].params[2]~=nil and cQueue[queueIndex].params[3]~=nil then --if no unit then use coordinate unitPosX, unitPosY,unitPosZ = cQueue[queueIndex].params[1], cQueue[queueIndex].params[2],cQueue[queueIndex].params[3] else if (turnOnEcho == 2)then Spring.Echo("Dynamic Avoidance repair targetting failure: fallback to no target") end end targetCoordinate={unitPosX, unitPosY,unitPosZ} --use ally unit as target boxSizeTrigger=3 --change to deactivation 'halfboxsize' similar to REPAIR command graphCONSTANTtrigger[1] = 1 graphCONSTANTtrigger[2] = 1 case = 'repair' elseif (cQueue[1].id == cMD_DummyG) or (cQueue[1].id == cMD_Dummy_atkG) then targetCoordinate = {-1, -1,-1} --no target (only avoidance) boxSizeTrigger = nil --//value not needed; because 'halfboxsize' for a "-1" target always return "not reached" (infinite avoidance), calculation is skipped (no nil error) graphCONSTANTtrigger[1] = 1 --//this value doesn't matter because 'cMD_DummyG' don't use attractor (-1 disabled the attractor calculation, and 'fixedPointCONSTANTtrigger' behaviour ignore attractor). Needed because "fTarget" is tied to this variable in "AvoidanceCalculator()". graphCONSTANTtrigger[2] = 1 fixedPointCONSTANTtrigger = 3 --//use behaviour that promote avoidance/ignore attractor case = 'cmddummys' elseif cQueue[queueIndex].id == CMD_GUARD then local unitPosX, unitPosY, unitPosZ = -1, -1, -1 -- (-1) is default value because -1 represent "no target" local targetUnitID = cQueue[queueIndex].params[1] if spValidUnitID(targetUnitID) then --if valid unit ID, not fake (if fake then will use "no target" for pure avoidance) local unitDirection = 0 unitDirection, unitPosY,_ = GetUnitDirection(targetUnitID) --get target's direction in radian unitPosX, unitPosZ = ConvertToXZ(targetUnitID, unitDirection, 200) --project a target at 200m in front of guarded unit targetID = targetUnitID else if (turnOnEcho == 2)then Spring.Echo("Dynamic Avoidance guard targetting failure: fallback to no target") end end targetCoordinate={unitPosX, unitPosY,unitPosZ} --use ally unit as target boxSizeTrigger = 4 --//deactivation 'halfboxsize' for GUARD command graphCONSTANTtrigger[1] = 2 --//use more aggressive attraction because it GUARD units. It need big result. graphCONSTANTtrigger[2] = 1 --//(if 1) use less aggressive avoidance because need to stay close to units. It need not stray. case = 'guard' elseif cQueue[queueIndex].id == CMD_ATTACK then local targetPosX, targetPosY, targetPosZ = -1, -1, -1 -- (-1) is default value because -1 represent "no target" boxSizeTrigger = nil --//value not needed when target is "-1" which always return "not reached" (a case where boxSizeTrigger is not used) graphCONSTANTtrigger[1] = 1 --//this value doesn't matter because 'CMD_ATTACK' don't use attractor (-1 already disabled the attractor calculation, and 'fixedPointCONSTANTtrigger' ignore attractor). Needed because "fTarget" is tied to this variable in "AvoidanceCalculator()". graphCONSTANTtrigger[2] = 2 --//use more aggressive avoidance because it often run just once or twice. It need big result. fixedPointCONSTANTtrigger = 3 --//use behaviour that promote avoidance/ignore attractor (incase -1 is not enough) if unitVisible and weaponType~=2 then --not arty local enemyID = cQueue[queueIndex].params[1] local x,y,z = spGetUnitPosition(enemyID) if x then targetPosX, targetPosY, targetPosZ = x,y,z --set target to enemy targetID = enemyID -- if weaponType==0 then --melee unit set bigger targetReached box. -- boxSizeTrigger = 1 --if user initiate an attack while avoidance is necessary (eg: while reloading), then set deactivation 'halfboxsize' for MOVE command (ie: 400m range) -- elseif weaponType==1 then boxSizeTrigger = 2 --set deactivation 'halfboxsize' for RECLAIM/RESURRECT command (ie: 0m range/ always flee) -- end fixedPointCONSTANTtrigger = 1 --//use general behaviour that balance between target & avoidance end end targetCoordinate={targetPosX, targetPosY, targetPosZ} --set target to enemy unit or none case = 'attack' else --if queue has no match/ is empty: then use no-target. eg: A case where undefined command is allowed into the system, or when engine delete the next queues of a valid command and widget expect it to still be there. targetCoordinate={-1, -1, -1} --if for some reason command queue[2] is already empty then use these backup value as target: boxSizeTrigger = nil --//value not needed when target is "-1" which always return "not reached" (a case where boxSizeTrigger is not used) graphCONSTANTtrigger[1] = 1 --//needed because "fTarget" is tied to this variable in "AvoidanceCalculator()". This value doesn't matter because -1 already skip attractor calculation & 'fixedPointCONSTANTtrigger' already ignore attractor values. graphCONSTANTtrigger[2] = 1 fixedPointCONSTANTtrigger = 3 case = 'none' end local output = { targetCoordinate = targetCoordinate, boxSizeTrigger = boxSizeTrigger, graphCONSTANTtrigger = graphCONSTANTtrigger, fixedPointCONSTANTtrigger = fixedPointCONSTANTtrigger, case = case, targetID = targetID, } return output end function AddAttackerIDToEnemyList (unitID, losRadius, relevantUnit, arrayIndex, attacker) if attacker[unitID].countDown > 0 then local separation = spGetUnitSeparation (unitID,attacker[unitID].id, true) if separation ~=nil then --if attackerID is still a valid id (ie: enemy did not disappear) then: if separation> losRadius then --only include attacker that is outside LosRadius because anything inside LosRadius is automatically included later anyway arrayIndex=arrayIndex+1 relevantUnit[arrayIndex]= attacker[unitID].id --//add attacker as a threat end end end return relevantUnit, arrayIndex end function GetUnitRelativeAngle (unitIDmain,unitID2,unitIDmainX,unitIDmainZ,unitID2X,unitID2Z) local x,z = unitIDmainX,unitIDmainZ local rX, rZ=unitID2X,unitID2Z --use inputted position if not x then --empty? x,_,z = spGetUnitPosition(unitIDmain) --use standard position end if not rX then rX, _, rZ= spGetUnitPosition(unitID2) end local cX, _, cZ = rX-x, _, rZ-z local cXcZ = math.sqrt(cX*cX + cZ*cZ) --hypothenus for xz direction local relativeAngle = math.atan2 (cX/cXcZ, cZ/cXcZ) --math.atan2 accept trigonometric ratio (ie: ratio that has same value as: cos(angle) & sin(angle). Cos is ratio between x and hypothenus, and Sin is ratio between z and hypothenus) return relativeAngle end function GetTargetAngleWithRespectToUnit(unitID, targetCoordinate) local x,_,z = spGetUnitPosition(unitID) local tx, tz = targetCoordinate[1], targetCoordinate[3] local dX, dZ = tx- x, tz-z local dXdZ = math.sqrt(dX*dX + dZ*dZ) --hypothenus for xz direction local targetAngle = math.atan2(dX/dXdZ, dZ/dXdZ) --math.atan2 accept trigonometric ratio (ie: ratio that has same value as: cos(angle) & sin(angle)) return targetAngle end --attractor's sinusoidal wave function (target's sine wave function) function GetFtarget (aCONSTANT, targetAngle, unitDirection) local fTarget = -1*aCONSTANT*math.sin(unitDirection - targetAngle) return fTarget end --attractor's graph slope at unit's direction function GetFtargetSlope (aCONSTANT, targetAngle, unitDirection, fTarget) local unitDirectionPlus1 = unitDirection+0.05 local fTargetPlus1 = -1*aCONSTANT*math.sin(unitDirectionPlus1 - targetAngle) local fTargetSlope=(fTargetPlus1-fTarget) / (unitDirectionPlus1 -unitDirection) return fTargetSlope end --target angular size function GetTargetSubtendedAngle(unitID, targetCoordinate) local tx,tz = targetCoordinate[1],targetCoordinate[3] local x,_,z = spGetUnitPosition(unitID) local unitDefID= spGetUnitDefID(unitID) local unitDef= UnitDefs[unitDefID] local unitSize =32--arbitrary value, size of a com if(unitDef~=nil) then unitSize = unitDef.xsize*8 end --8 is the actual Distance per square, times the unit's square local targetDistance= Distance(tx,tz,x,z) local targetSubtendedAngle = math.atan(unitSize*2/targetDistance) --target is same size as unit's. Usually target do not has size at all, because they are simply move command on ground return targetSubtendedAngle end --sum the contribution from all enemy unit function SumAllUnitAroundUnitID (obsCONSTANT,unitDirection,losRadius,surroundingUnits,unitsSeparation,impatienceTrigger,graphCONSTANTtrigger,unitInMotionSingleUnit,skippingTimer) local thisUnitID = unitInMotionSingleUnit["unitID"] local safetyMarginCONSTANT = safetyMarginCONSTANTunitG -- make the slopes in the extremeties of obstacle graph more sloppy (refer to "non-Linear Dynamic system approach to modelling behavior" -SiomeGoldenstein, Edward Large, DimitrisMetaxas) local smCONSTANT = smCONSTANTunitG --? local distanceCONSTANT = distanceCONSTANTunitG local useLOS_distanceCONSTANT = useLOS_distanceCONSTANTunit_G local normalizeObsGraph = normalizeObsGraphG local cmd_then_DoCalculation_delay = cmd_then_DoCalculation_delayG ---- local wTotal=0 local fObstacleSum=0 local dFobstacle=0 local dSum=0 local nearestFrontObstacleRange =999 local normalizingFactor = 1 if (turnOnEcho == 1) then Spring.Echo("unitID(SumAllUnitAroundUnitID)" .. thisUnitID) end if (surroundingUnits["count"] and surroundingUnits["count"]>0) then --don't execute if no enemy unit exist local graphSample={} if normalizeObsGraph then --an option (default OFF) allow the obstacle graph to be normalized for experimenting purposes for i=1, 180+1, 1 do graphSample[i]=0 --initialize content 360 points end end local thisXvel,_,thisZvel = spGetUnitVelocity(thisUnitID) local thisX,_,thisZ = spGetUnitPosition(thisUnitID) local delay_1 = skippingTimer.averageDelay/2 local delay_2 = cmd_then_DoCalculation_delay local thisXvel_delay2,thisZvel_delay2 = GetDistancePerDelay(thisXvel,thisZvel, delay_2) local thisXvel_delay1,thisZvel_delay1 = GetDistancePerDelay(thisXvel,thisZvel,delay_1) --convert per-frame velocity into per-second velocity, then into elmo-per-averageNetworkDelay for i=1,surroundingUnits["count"], 1 do local unitRectangleID=surroundingUnits[i] if (unitRectangleID ~= nil)then --excluded any nil entry local recX_delay1,recZ_delay1,unitSeparation_1,_,_,unitSeparation_2 = GetTargetPositionAfterDelay(unitRectangleID, delay_1,delay_2,thisXvel_delay1,thisZvel_delay1,thisXvel_delay2,thisZvel_delay2,thisX,thisZ) if unitsSeparation[unitRectangleID]==nil then unitsSeparation[unitRectangleID]=9999 end --if enemy spontaneously appear then set the memorized separation distance to 9999; maybe previous polling missed it and to prevent nil if (turnOnEcho == 1) then Spring.Echo("unitSeparation <unitsSeparation[unitRectangleID](SumAllUnitAroundUnitID)") Spring.Echo(unitSeparation <unitsSeparation[unitRectangleID]) end if unitSeparation_2 - unitsSeparation[unitRectangleID] < 30 then --see if the enemy in collision front is maintaining distance/fleeing or is closing in local relativeAngle = GetUnitRelativeAngle (thisUnitID, unitRectangleID,thisX,thisZ,recX_delay1,recZ_delay1) -- obstacle's angular position with respect to our coordinate local subtendedAngle = GetUnitSubtendedAngle (thisUnitID, unitRectangleID, losRadius,unitSeparation_1) -- obstacle & our unit's angular size distanceCONSTANT=distanceCONSTANTunitG --reset distance constant if useLOS_distanceCONSTANT then distanceCONSTANT= losRadius --use unit's LOS instead of constant so that longer range unit has bigger avoidance radius. end --get obstacle/ enemy/repulsor wave function if impatienceTrigger==0 then --impatienceTrigger reach zero means that unit is impatient distanceCONSTANT=distanceCONSTANT/2 end local ri, wi, di,diff1 = GetRiWiDi (unitDirection, relativeAngle, subtendedAngle, unitSeparation_1, safetyMarginCONSTANT, smCONSTANT, distanceCONSTANT,obsCONSTANT) local fObstacle = ri*wi*di --get second obstacle/enemy/repulsor wave function to calculate slope local ri2, wi2, di2, diff2= GetRiWiDi (unitDirection, relativeAngle, subtendedAngle, unitSeparation_1, safetyMarginCONSTANT, smCONSTANT, distanceCONSTANT, obsCONSTANT, true) local fObstacle2 = ri2*wi2*di2 --create a snapshot of the entire graph. Resolution: 360 datapoint local dI = math.exp(-1*unitSeparation_1/distanceCONSTANT) --distance multiplier local hI = windowingFuncMultG/ (math.cos(2*subtendedAngle) - math.cos(2*subtendedAngle+ safetyMarginCONSTANT)) if normalizeObsGraph then for i=-90, 90, 1 do --sample the entire 360 degree graph local differenceInAngle = (unitDirection-relativeAngle)+i*math.pi/180 local rI = (differenceInAngle/ subtendedAngle)*math.exp(1- math.abs(differenceInAngle/subtendedAngle)) local wI = obsCONSTANT* (math.tanh(hI- (math.cos(differenceInAngle) -math.cos(2*subtendedAngle +smCONSTANT)))+1) --graph with limiting window graphSample[i+90+1]=graphSample[i+90+1]+ (rI*wI*dI) --[[ <<--can uncomment this and comment the 2 "normalizeObsGraph" switch above for debug info Spring.Echo((rI*wI*dI) .. " (rI*wI*dI) (SumAllUnitAroundUnitID)") if i==0 then Spring.Echo("CENTER") end --]] end end --get repulsor wavefunction's slope local fObstacleSlope = GetFObstacleSlope(fObstacle2, fObstacle, diff2, diff1) --sum all repulsor's wavefunction from every enemy/obstacle within this loop wTotal, dSum, fObstacleSum,dFobstacle, nearestFrontObstacleRange= DoAllSummation (wi, fObstacle, fObstacleSlope, di,wTotal, unitDirection, unitSeparation_1, relativeAngle, dSum, fObstacleSum,dFobstacle, nearestFrontObstacleRange) end end end if normalizeObsGraph then local biggestValue=0 for i=1, 180+1, 1 do --find maximum value from graph if biggestValue<graphSample[i] then biggestValue = graphSample[i] end end if biggestValue > obsCONSTANT then normalizingFactor = obsCONSTANT/biggestValue --normalize graph value to a determined maximum else normalizingFactor = 1 --don't change the graph if the graph never exceed maximum value end end end local output = { wTotal = wTotal, dSum = dSum, fObstacleSum = fObstacleSum, dFobstacle = dFobstacle, nearestFrontObstacleRange = nearestFrontObstacleRange, normalizingFactor = normalizingFactor, } return output --return obstacle's calculation result end --determine appropriate behaviour function CheckWhichFixedPointIsStable (fTargetSlope, fTarget, fixedPointCONSTANTtrigger,sumAllUnitOutput) local dFobstacle = sumAllUnitOutput["dFobstacle"] local dSum = sumAllUnitOutput["dSum"] local wTotal = sumAllUnitOutput["wTotal"] local fObstacleSum = sumAllUnitOutput["fObstacleSum"] --local alphaCONSTANT1, alphaCONSTANT2, gammaCONSTANT1and2, gammaCONSTANT2and1 = ConstantInitialize(fTargetSlope, dFobstacle, dSum, fTarget, fObstacleSum, wTotal, fixedPointCONSTANTtrigger) local cCONSTANT1 = cCONSTANT1g local cCONSTANT2 = cCONSTANT2g local gammaCONSTANT1and2 local gammaCONSTANT2and1 = gammaCONSTANT2and1g local alphaCONSTANT1 = alphaCONSTANT1g local alphaCONSTANT2 --always between 1 and 0 -------- cCONSTANT1 = cCONSTANT1[fixedPointCONSTANTtrigger] cCONSTANT2 = cCONSTANT2[fixedPointCONSTANTtrigger] gammaCONSTANT2and1 = gammaCONSTANT2and1[fixedPointCONSTANTtrigger] alphaCONSTANT1 = alphaCONSTANT1[fixedPointCONSTANTtrigger] --calculate "gammaCONSTANT1and2, alphaCONSTANT2, and alphaCONSTANT1" local pTarget= Sgn(fTargetSlope)*math.exp(cCONSTANT1*math.abs(fTarget)) local pObstacle = Sgn(dFobstacle)*math.exp(cCONSTANT1*math.abs(fObstacleSum))*wTotal gammaCONSTANT1and2 = math.exp(-1*cCONSTANT2*pTarget*pObstacle)/math.exp(cCONSTANT2) alphaCONSTANT2 = math.tanh(dSum) alphaCONSTANT1 = alphaCONSTANT1*(1-alphaCONSTANT2) -- local wTarget=0 local wObstacle=1 if (turnOnEcho == 1) then Spring.Echo("fixedPointCONSTANTtrigger(CheckWhichFixedPointIsStable)" .. fixedPointCONSTANTtrigger) Spring.Echo("alphaCONSTANT1(CheckWhichFixedPointIsStable)" .. alphaCONSTANT1) Spring.Echo ("alphaCONSTANT2(CheckWhichFixedPointIsStable)" ..alphaCONSTANT2) Spring.Echo ("gammaCONSTANT1and2(CheckWhichFixedPointIsStable)" ..gammaCONSTANT1and2) Spring.Echo ("gammaCONSTANT2and1(CheckWhichFixedPointIsStable)" ..gammaCONSTANT2and1) end if (alphaCONSTANT1 < 0) and (alphaCONSTANT2 <0) then --state 0 is unstable, unit don't move wTarget = 0 wObstacle =0 if (turnOnEcho == 1) then Spring.Echo("state 0") Spring.Echo ("(alphaCONSTANT1 < 0) and (alphaCONSTANT2 <0)") end end if (gammaCONSTANT1and2 > alphaCONSTANT1) and (alphaCONSTANT2 >0) then --state 1: unit flee from obstacle and forget target wTarget =0 wObstacle =-1 if (turnOnEcho == 1) then Spring.Echo("state 1") Spring.Echo ("(gammaCONSTANT1and2 > alphaCONSTANT1) and (alphaCONSTANT2 >0)") end end if(gammaCONSTANT2and1 > alphaCONSTANT2) and (alphaCONSTANT1 >0) then --state 2: unit forget obstacle and go for the target wTarget= -1 wObstacle =0 if (turnOnEcho == 1) then Spring.Echo("state 2") Spring.Echo ("(gammaCONSTANT2and1 > alphaCONSTANT2) and (alphaCONSTANT1 >0)") end end if (alphaCONSTANT1>0) and (alphaCONSTANT2>0) then --state 3: mixed contribution from target and obstacle if (alphaCONSTANT1> gammaCONSTANT1and2) and (alphaCONSTANT2>gammaCONSTANT2and1) then if (gammaCONSTANT1and2*gammaCONSTANT2and1 < 0.0) then --function from latest article. Set repulsor/attractor balance wTarget= math.sqrt((alphaCONSTANT2*(alphaCONSTANT1-gammaCONSTANT1and2))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1)) wObstacle= math.sqrt((alphaCONSTANT1*(alphaCONSTANT2-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1)) -- wTarget= math.sqrt((alphaCONSTANT2*(alphaCONSTANT1-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1)) -- wObstacle= math.sqrt((alphaCONSTANT1*(alphaCONSTANT2-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1)) if (turnOnEcho == 1) then Spring.Echo("state 3") Spring.Echo ("(gammaCONSTANT1and2*gammaCONSTANT2and1 < 0.0)") end end if (gammaCONSTANT1and2>0) and (gammaCONSTANT2and1>0) then --function from latest article. Set repulsor/attractor balance wTarget= math.sqrt((alphaCONSTANT2*(alphaCONSTANT1-gammaCONSTANT1and2))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1)) wObstacle= math.sqrt((alphaCONSTANT1*(alphaCONSTANT2-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1)) -- wTarget= math.sqrt((alphaCONSTANT2*(alphaCONSTANT1-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1)) -- wObstacle= math.sqrt((alphaCONSTANT1*(alphaCONSTANT2-gammaCONSTANT2and1))/(alphaCONSTANT1*alphaCONSTANT2-gammaCONSTANT1and2*gammaCONSTANT2and1)) wTarget= wTarget*-1 if (turnOnEcho == 1) then Spring.Echo("state 4") Spring.Echo ("(gammaCONSTANT1and2>0) and (gammaCONSTANT2and1>0)") end end end else if (turnOnEcho == 1) then Spring.Echo ("State not listed") end end if (turnOnEcho == 1) then Spring.Echo ("wTarget (CheckWhichFixedPointIsStable)" ..wTarget) Spring.Echo ("wObstacle(CheckWhichFixedPointIsStable)" ..wObstacle) end return wTarget, wObstacle --return attractor's and repulsor's multiplier end --convert angular command into coordinate, plus other function function ToCoordinate(wTarget, wObstacle, fTarget, unitDirection, losRadius, impatienceTrigger, skippingTimer, wasMoving, newCommand,sumAllUnitOutput, unitInMotionSingleUnit) local safetyDistanceCONSTANT=safetyDistanceCONSTANT_fG local timeToContactCONSTANT=timeToContactCONSTANTg local activateAutoReverse=activateAutoReverseG --------- local thisUnitID = unitInMotionSingleUnit["unitID"] local unitSpeed = unitInMotionSingleUnit["unitSpeed"] local nearestFrontObstacleRange = sumAllUnitOutput["nearestFrontObstacleRange"] local fObstacleSum = sumAllUnitOutput["fObstacleSum"] local normalizingFactor = sumAllUnitOutput["normalizingFactor"] if (nearestFrontObstacleRange> losRadius) then nearestFrontObstacleRange = 999 end --if no obstacle infront of unit then set nearest obstacle as far as LOS to prevent infinite velocity. local newUnitAngleDerived= GetNewAngle(unitDirection, wTarget, fTarget, wObstacle, fObstacleSum, normalizingFactor) --derive a new angle from calculation for move solution local velocity=unitSpeed*(math.max(timeToContactCONSTANT, skippingTimer.averageDelay + timeToContactCONSTANT)) --scale-down/scale-up command lenght based on system delay (because short command will make unit move in jittery way & avoidance stop prematurely). *NOTE: select either preset velocity (timeToContactCONSTANT==cmd_then_DoCalculation_delayG) or the one taking account delay measurement (skippingTimer.networkDelay + cmd_then_DoCalculation_delay), which one is highest, times unitSpeed as defined by UnitDefs. local networkDelayDrift = 0 if wasMoving then --unit drift contributed by network lag/2 (divide-by-2 because averageDelay is a roundtrip delay and we just want the delay of stuff measured on screen), only calculated when unit is known to be moving (eg: is using lastPosition to determine direction), but network lag value is not accurate enough to yield an accurate drift prediction. networkDelayDrift = unitSpeed*(skippingTimer.averageDelay/2) -- else --if initially stationary then add this backward motion (as 'hax' against unit move toward enemy because of avoidance due to firing/reloading weapon) -- networkDelayDrift = -1*unitSpeed/2 end local maximumVelocity = (nearestFrontObstacleRange- safetyDistanceCONSTANT)/timeToContactCONSTANT --calculate the velocity that will cause a collision within the next "timeToContactCONSTANT" second. activateAutoReverse=activateAutoReverse*impatienceTrigger --activate/deactivate 'autoReverse' if impatience system is used local doReverseNow = false if (maximumVelocity <= velocity) and (activateAutoReverse==1) and (not newCommand) then --velocity = -unitSpeed --set to reverse if impact is imminent & when autoReverse is active & when isn't a newCommand. NewCommand is TRUE if its on initial avoidance. We don't want auto-reverse on initial avoidance (we rely on normal avoidance first, then auto-reverse if it about to collide with enemy). doReverseNow = true end if (turnOnEcho == 1) then Spring.Echo("maximumVelocity(ToCoordinate)" .. maximumVelocity) Spring.Echo("activateAutoReverse(ToCoordinate)" .. activateAutoReverse) Spring.Echo("unitDirection(ToCoordinate)" .. unitDirection) end local newX, newZ= ConvertToXZ(thisUnitID, newUnitAngleDerived,velocity, unitDirection, networkDelayDrift,doReverseNow) --convert angle into coordinate form return newX, newZ end function Round(num) --Reference: http://lua-users.org/wiki/SimpleRound under = math.floor(num) upper = math.floor(num) + 1 underV = -(under - num) upperV = upper - num if (upperV > underV) then return under else return upper end end local safeHavenLastUpdate = 0 local safeHavenCoordinates = {} function FindSafeHavenForCons(unitID, now) local myTeamID = myTeamID_gbl ---- if options.enableReturnToBase.value==false or WG.OPTICS_cluster == nil then --//if epicmenu option 'Return To Base' is false then return nil return nil end --Spring.Echo((now - safeHavenLastUpdate)) if (now - safeHavenLastUpdate) > 4 then --//only update NO MORE than once every 4 second: safeHavenCoordinates = {} --//reset old content local allMyUnits = spGetTeamUnits(myTeamID) local unorderedUnitList = {} for i=1, #allMyUnits, 1 do --//convert unit list into a compatible format for the Clustering function below local unitID_list = allMyUnits[i] local x,y,z = spGetUnitPosition(unitID_list) local unitDefID_list = spGetUnitDefID(unitID_list) local unitDef = UnitDefs[unitDefID_list] local unitSpeed =unitDef["speed"] if (unitSpeed>0) then --//if moving units if (unitDef.isBuilder or unitDef["canCloak"]) and not unitDef.customParams.commtype then --if cloakies and constructor, and not com (ZK) --intentionally empty. Not include cloakies and builder. elseif unitDef.customParams.commtype then --if COMMANDER, unorderedUnitList[unitID_list] = {x,y,z} --//store elseif not (unitDef["canFly"] or unitDef["isAirUnit"]) then --if all ground unit, amphibious, and ships (except commander) --unorderedUnitList[unitID_list] = {x,y,z} --//store elseif (unitDef.hoverAttack== true) then --if gunships --intentionally empty. Not include gunships. end else --if buildings unorderedUnitList[unitID_list] = {x,y,z} --//store end end local cluster, _ = WG.OPTICS_cluster(unorderedUnitList, 600,3, myTeamID,300) --//find clusters with atleast 3 unit per cluster and with at least within 300-meter from each other for index=1 , #cluster do local sumX, sumY,sumZ, unitCount,meanX, meanY, meanZ = 0,0 ,0 ,0 ,0,0,0 for unitIndex=1, #cluster[index] do local unitID_list = cluster[index][unitIndex] local x,y,z= unorderedUnitList[unitID_list][1],unorderedUnitList[unitID_list][2],unorderedUnitList[unitID_list][3] --// get stored unit position sumX= sumX+x sumY = sumY+y sumZ = sumZ+z unitCount=unitCount+1 end meanX = sumX/unitCount --//calculate center of cluster meanY = sumY/unitCount meanZ = sumZ/unitCount safeHavenCoordinates[(#safeHavenCoordinates or 0)+1] = {meanX, meanY, meanZ} --//record cluster position end safeHavenLastUpdate = now end --//end cluster detection local currentSafeHaven = {params={}} --// initialize table using 'params' to be consistent with 'cQueue' content local nearestSafeHaven = {params={}} --// initialize table using 'params' to be consistent with 'cQueue' content local nearestSafeHavenDistance = 999999 nearestSafeHaven, currentSafeHaven = NearestSafeCoordinate (unitID, safeHavenCoordinates, nearestSafeHavenDistance, nearestSafeHaven, currentSafeHaven) if nearestSafeHaven.params[1]~=nil then --//if nearest safe haven found then go there return nearestSafeHaven elseif currentSafeHaven.params[1]~=nil then --//elseif only current safe haven is available then go here return currentSafeHaven else --//elseif no safe haven detected then return nil return nil end end ---------------------------------Level3 ---------------------------------Level4 (lower than low-level function) function GetUnitOrFeaturePosition(id) --copied from cmd_commandinsert.lua widget (by dizekat) if id<=Game.maxUnits and spValidUnitID(id) then return spGetUnitPosition(id) elseif spValidFeatureID(id-Game.maxUnits) then return spGetFeaturePosition(id-Game.maxUnits) --featureID is always offset by maxunit count end return nil end function GetUnitDirection(unitID) --give unit direction in radian, 2D local dx, dz = 0,0 local isMoving = true local _,currentY = spGetUnitPosition(unitID) dx,_,dz= spGetUnitVelocity(unitID) if (dx == 0 and dz == 0) then --use the reported vector if velocity failed to reveal any vector dx,_,dz= spGetUnitDirection(unitID) isMoving = false end local dxdz = math.sqrt(dx*dx + dz*dz) --hypothenus for xz direction local unitDirection = math.atan2(dx/dxdz, dz/dxdz) if (turnOnEcho == 1) then Spring.Echo("direction(GetUnitDirection) " .. unitDirection*180/math.pi) end return unitDirection, currentY, isMoving end function ConvertToXZ(thisUnitID, newUnitAngleDerived, velocity, unitDirection, networkDelayDrift,doReverseNow) --localize global constant local velocityAddingCONSTANT=velocityAddingCONSTANTg local velocityScalingCONSTANT=velocityScalingCONSTANTg -- local x,_,z = spGetUnitPosition(thisUnitID) local distanceToTravelInSecond=velocity*velocityScalingCONSTANT+velocityAddingCONSTANT*Sgn(velocity) --add multiplier & adder. note: we multiply "velocityAddingCONSTANT" with velocity Sign ("Sgn") because we might have reverse speed (due to auto-reverse) local newX = 0 local newZ = 0 if doReverseNow then local reverseDirection = unitDirection+math.pi --0 degree + 180 degree = reverse direction newX = distanceToTravelInSecond*math.sin(reverseDirection) + x newZ = distanceToTravelInSecond*math.cos(reverseDirection) + z else newX = distanceToTravelInSecond*math.sin(newUnitAngleDerived) + x -- issue a command on the ground to achieve a desired angular turn newZ = distanceToTravelInSecond*math.cos(newUnitAngleDerived) + z end if (unitDirection ~= nil) and (networkDelayDrift~=0) then --need this check because argument #4 & #5 can be empty (for other usage). Also used in ExtractTarget for GUARD command. local distanceTraveledDueToNetworkDelay = networkDelayDrift newX = distanceTraveledDueToNetworkDelay*math.sin(unitDirection) + newX -- translate move command abit further forward; to account for lag. Network Lag makes move command lags behind the unit. newZ = distanceTraveledDueToNetworkDelay*math.cos(unitDirection) + newZ end newX = math.min(newX,Game.mapSizeX) newX = math.max(newX,0) newZ = math.min(newZ,Game.mapSizeZ) newZ = math.max(newZ,0) if (turnOnEcho == 1) then Spring.Echo("x(ConvertToXZ) " .. x) Spring.Echo("z(ConvertToXZ) " .. z) Spring.Echo("newX(ConvertToXZ) " .. newX) Spring.Echo("newZ(ConvertToXZ) " .. newZ) end return newX, newZ end function GetTargetPositionAfterDelay(targetUnitID, delay1,delay2,thisXvel_delay1,thisZvel_delay1,thisXvel_delay2,thisZvel_delay2,thisX,thisZ) local recXvel,_,recZvel = spGetUnitVelocity(targetUnitID) local recX,_,recZ = spGetUnitPosition(targetUnitID) recXvel = recXvel or 0 recZvel = recZvel or 0 local recXvel_delay2, recZvel_delay2 = GetDistancePerDelay(recXvel,recZvel, delay2) recXvel_delay2 = recXvel_delay2 - thisXvel_delay2 --calculate relative elmo-per-delay recZvel_delay2 = recZvel_delay2 - thisZvel_delay2 local recX_delay2 = recX + recXvel_delay2 --predict obstacle's offsetted position after a delay has passed local recZ_delay2 = recZ + recZvel_delay2 local unitSeparation_2 = Distance(recX_delay2,recZ_delay2,thisX,thisZ) local recXvel_delay1, recZvel_delay1 = GetDistancePerDelay(recXvel,recZvel,delay1) recXvel_delay1 = recXvel_delay1 - thisXvel_delay1 --calculate relative elmo-per-averageNetworkDelay recZvel_delay1 = recZvel_delay1 - thisZvel_delay1 local recX_delay1 = recX + recXvel_delay1 --predict obstacle's offsetted position after network delay has passed local recZ_delay1 = recZ + recZvel_delay1 local unitSeparation_1 = Distance(recX_delay1,recZ_delay1,thisX,thisZ) --spGetUnitSeparation (thisUnitID, unitRectangleID, true) --get 2D distance return recX_delay1,recZ_delay1,unitSeparation_1,recX_delay2,recZ_delay2,unitSeparation_2 end --get enemy angular size with respect to unit's perspective function GetUnitSubtendedAngle (unitIDmain, unitID2, losRadius,unitSeparation) local unitSize2 =32 --a commander size for an unidentified enemy unit local unitDefID2= spGetUnitDefID(unitID2) local unitDef2= UnitDefs[unitDefID2] if (unitDef2~=nil) then unitSize2 = unitDef2.xsize*8 --8 unitDistance per each square times unitDef's square, a correct size for an identified unit end local unitDefID= spGetUnitDefID(unitIDmain) local unitDef= UnitDefs[unitDefID] local unitSize = unitDef.xsize*8 --8 is the actual Distance per square if (not unitDef["canCloak"]) and (unitDef2~=nil) then --non-cloaky unit view enemy size as its weapon range (this to make it avoid getting into range) unitSize2 = unitDef2.maxWeaponRange end if (unitDef["canCloak"]) then --cloaky unit use decloak distance as body size (to avoid getting too close) unitSize = unitDef["decloakDistance"] end local separationDistance = unitSeparation --if (unitID2~=nil) then separationDistance = spGetUnitSeparation (unitIDmain, unitID2, true) --actual separation distance --else separationDistance = losRadius -- GetUnitLOSRadius(unitIDmain) --as far as unit's reported LOSradius --end local unit2SubtendedAngle = math.atan((unitSize + unitSize2)/separationDistance) --convert size and distance into radian (angle) return unit2SubtendedAngle --return angular size end --calculate enemy's wavefunction function GetRiWiDi (unitDirection, relativeAngle, subtendedAngle, separationDistance, safetyMarginCONSTANT, smCONSTANT, distanceCONSTANT, obsCONSTANT, isForSlope) unitDirection = unitDirection + math.pi --temporarily add a half of a circle to remove the negative part which could skew with circle-arithmetic relativeAngle = relativeAngle + math.pi local differenceInAngle = relativeAngle - unitDirection --relative difference if differenceInAngle > math.pi then --select difference that is smaller than half a circle differenceInAngle = differenceInAngle - 2*math.pi elseif differenceInAngle < -1*math.pi then differenceInAngle = 2*math.pi + differenceInAngle end if isForSlope then differenceInAngle = differenceInAngle + 0.05 end --Spring.Echo("differenceInAngle(GetRiWiDi) ".. differenceInAngle*180/math.pi) local rI = (differenceInAngle/ subtendedAngle)*math.exp(1- math.abs(differenceInAngle/subtendedAngle)) -- ratio of enemy-direction over the size-of-the-enemy local hI = windowingFuncMultG/ (math.cos(2*subtendedAngle) - math.cos(2*subtendedAngle+ safetyMarginCONSTANT)) local wI = obsCONSTANT* (math.tanh(hI- (math.cos(differenceInAngle) -math.cos(2*subtendedAngle +smCONSTANT)))+1) --graph with limiting window. Tanh graph multiplied by obsCONSTANT local dI = math.exp(-1*separationDistance/distanceCONSTANT) --distance multiplier return rI, wI, dI, differenceInAngle end --calculate wavefunction's slope function GetFObstacleSlope (fObstacle2, fObstacle, diff2, diff1) --local fObstacleSlope= (fObstacle2 -fObstacle)/((unitDirection+0.05)-unitDirection) local fObstacleSlope= (fObstacle2 -fObstacle)/(diff2-diff1) return fObstacleSlope end --sum the wavefunction from all enemy units function DoAllSummation (wi, fObstacle, fObstacleSlope, di,wTotal, unitDirection, unitSeparation, relativeAngle, dSum, fObstacleSum, dFobstacle, nearestFrontObstacleRange) --sum all wavefunction variable, send and return summation variable wTotal, dSum, fObstacleSum, dFobstacle=SumRiWiDiCalculation (wi, fObstacle, fObstacleSlope, di,wTotal, dSum, fObstacleSum, dFobstacle) --detect any obstacle 60 degrees (pi/6) to the side of unit, set as nearest obstacle unit (prevent head on collision) if (unitSeparation< nearestFrontObstacleRange) and math.abs(unitDirection- relativeAngle)< (fleeingAngleG) then nearestFrontObstacleRange = unitSeparation end return wTotal, dSum, fObstacleSum, dFobstacle, nearestFrontObstacleRange --return summation variable end -- function GetNewAngle (unitDirection, wTarget, fTarget, wObstacle, fObstacleSum, normalizingFactor) fObstacleSum = fObstacleSum*normalizingFactor --downscale value depend on the entire graph's maximum (if normalization is used) local angleFromTarget = math.abs(wTarget)*fTarget local angleFromObstacle = math.abs(wObstacle)*fObstacleSum --Spring.Echo(math.modf(angleFromObstacle)) local angleFromNoise = Sgn((-1)*angleFromObstacle)*(noiseAngleG)*GaussianNoise() --(noiseAngleG)*(GaussianNoise()*2-1) --for random in negative & positive direction local unitAngleDerived= angleFromTarget + (-1)*angleFromObstacle + angleFromNoise --add attractor amplitude, add repulsive amplitude, and add noise between -ve & +ve noiseAngle. NOTE: somehow "angleFromObstacle" have incorrect sign (telling unit to turn in opposite direction) if math.abs(unitAngleDerived) > maximumTurnAngleG then --to prevent excess in avoidance causing overflow in angle changes (maximum angle should be pi, but useful angle should be pi/2 eg: 90 degree) --Spring.Echo("Dynamic Avoidance warning: total angle changes excess") unitAngleDerived = Sgn(unitAngleDerived)*maximumTurnAngleG end unitDirection = unitDirection+math.pi --temporarily remove negative hemisphere so that arithmetic with negative angle won't skew the result local newUnitAngleDerived= unitDirection +unitAngleDerived --add derived angle into current unit direction plus some noise newUnitAngleDerived = newUnitAngleDerived - math.pi --readd negative hemisphere if newUnitAngleDerived > math.pi then --add residual angle (angle > 2 circle) to respective negative or positive hemisphere newUnitAngleDerived = newUnitAngleDerived - 2*math.pi elseif newUnitAngleDerived < -1*math.pi then newUnitAngleDerived = newUnitAngleDerived + 2*math.pi end if (turnOnEcho == 1) then -- Spring.Echo("unitAngleDerived (getNewAngle)" ..unitAngleDerived*180/math.pi) -- Spring.Echo("newUnitAngleDerived (getNewAngle)" .. newUnitAngleDerived*180/math.pi) -- Spring.Echo("angleFromTarget (getNewAngle)" .. angleFromTarget*180/math.pi) -- Spring.Echo("angleFromObstacle (getNewAngle)" .. angleFromObstacle*180/math.pi) -- Spring.Echo("fTarget (getNewAngle)" .. fTarget) --Spring.Echo("fObstacleSum (getNewAngle)" ..fObstacleSum) --Spring.Echo("unitAngleDerived(GetNewAngle) " .. unitAngleDerived) --Spring.Echo("newUnitAngleDerived(GetNewAngle) " .. newUnitAngleDerived) end return newUnitAngleDerived --sent out derived angle end function NearestSafeCoordinate (unitID, safeHavenCoordinates, nearestSafeHavenDistance, nearestSafeHaven, currentSafeHaven) local x,_,z = spGetUnitPosition(unitID) local unitDefID = spGetUnitDefID(unitID) local unitDef = UnitDefs[unitDefID] --local movementType = unitDef.moveData.name for j=1, #safeHavenCoordinates, 1 do --//iterate over all possible retreat point (bases with at least 3 units in a cluster) local distance = Distance(safeHavenCoordinates[j][1], safeHavenCoordinates[j][3] , x, z) local pathOpen = false local validX = 0 local validZ = 0 local positionToCheck = {{0,0},{1,1},{-1,-1},{1,-1},{-1,1},{0,1},{0,-1},{1,0},{-1,0}} for i=1, 9, 1 do --//randomly select position around 100-meter from the center for 5 times before giving up, if given up: it imply that this position is too congested for retreating. --local xDirection = mathRandom(-1,1) --local zDirection = mathRandom(-1,1) local xDirection = positionToCheck[i][1] local zDirection = positionToCheck[i][2] validX = safeHavenCoordinates[j][1] + (xDirection*100 + xDirection*mathRandom(0,100)) validZ = safeHavenCoordinates[j][3] + (zDirection*100 + zDirection*mathRandom(0,100)) local units = spGetUnitsInRectangle( validX-40, validZ-40, validX+40, validZ+40 ) if units == nil or #units == 0 then --//if this box is empty then return this area as accessible. pathOpen = true break end end --local pathOpen = spRequestPath(movementType, x,y,z, safeHavenCoordinates[j][1], safeHavenCoordinates[j][2], safeHavenCoordinates[j][3]) -- if pathOpen == nil then -- pathOpen = spRequestPath(movementType, x,y,z, safeHavenCoordinates[j][1]-80, safeHavenCoordinates[j][2], safeHavenCoordinates[j][3]) -- validX = safeHavenCoordinates[j][1]-80 -- validZ = safeHavenCoordinates[j][3] -- if not pathOpen then -- pathOpen = spRequestPath(movementType, x,y,z, safeHavenCoordinates[j][1], safeHavenCoordinates[j][2], safeHavenCoordinates[j][3]-80) -- validX = safeHavenCoordinates[j][1] -- validZ = safeHavenCoordinates[j][3]-80 -- if not pathOpen then -- pathOpen = spRequestPath(movementType, x,y,z, safeHavenCoordinates[j][1], safeHavenCoordinates[j][2], safeHavenCoordinates[j][3]+80) -- validX = safeHavenCoordinates[j][1] -- validZ = safeHavenCoordinates[j][3]+80 -- if not pathOpen then -- pathOpen = spRequestPath(movementType, x,y,z, safeHavenCoordinates[j][1]+80, safeHavenCoordinates[j][2], safeHavenCoordinates[j][3]) -- validX = safeHavenCoordinates[j][1]+80 -- validZ = safeHavenCoordinates[j][3] -- end -- end -- end --end --Spring.MarkerAddPoint(validX, safeHavenCoordinates[j][2] , validZ, "here") if distance > 300 and distance < nearestSafeHavenDistance and pathOpen then nearestSafeHavenDistance = distance nearestSafeHaven.params[1] = validX nearestSafeHaven.params[2] = safeHavenCoordinates[j][2] nearestSafeHaven.params[3] = validZ elseif distance < 300 then --//theoretically this will run once because units can only be at 1 cluster at 1 time or not at any cluster at all currentSafeHaven.params[1] = validX currentSafeHaven.params[2] = safeHavenCoordinates[j][2] currentSafeHaven.params[3] = validZ end end return nearestSafeHaven, currentSafeHaven end ---------------------------------Level4 ---------------------------------Level5 function SumRiWiDiCalculation (wi, fObstacle, fObstacleSlope, di, wTotal, dSum, fObstacleSum, dFobstacle) wTotal = wTotal +wi fObstacleSum= fObstacleSum +(fObstacle) dFobstacle= dFobstacle + (fObstacleSlope) --Spring.Echo(dFobstacle) dSum= dSum +di return wTotal, dSum, fObstacleSum, dFobstacle end --Gaussian noise, Box-Muller method --from http://www.dspguru.com/dsp/howtos/how-to-generate-white-gaussian-noise --output value from -1 to +1 with bigger chance of getting 0 function GaussianNoise() local v1 local v2 local s = 0 repeat local u1=math.random() --U1=[0,1] local u2=math.random() --U2=[0,1] v1= 2 * u1 -1 -- V1=[-1,1] v2=2 * u2 - 1 -- V2=[-1,1] s=v1 * v1 + v2 * v2 until (s<1) local x=math.sqrt(-2 * math.log(s) / s) * v1 return x end function Sgn(x) if x == 0 then return 0 end local y= x/(math.abs(x)) return y end function Distance(x1,z1,x2,z2) local dis = math.sqrt((x1-x2)*(x1-x2)+(z1-z2)*(z1-z2)) return dis end function GetDistancePerDelay(velocityX, velocityZ, delaySecond) return velocityX*30*delaySecond,velocityZ*30*delaySecond --convert per-frame velocity into per-second velocity, then into elmo-per-delay end ---------------------------------Level5 --REFERENCE: --1 --Non-linear dynamical system approach to behavior modeling --Siome Goldenstein, Edward Large, Dimitris Metaxas --Dynamic autonomous agents: game applications -- Siome Goldenstein, Edward Large, Dimitris Metaxas --2 --"unit_tactical_ai.lua" -ZeroK gadget by Google Frog --3 --"Initial Queue" widget, "Allows you to queue buildings before game start" (unit_initial_queue.lua), author = "Niobium", --4 --"unit_smart_nanos.lua" widget, "Enables auto reclaim & repair for idle nano turrets , author = Owen Martindell --5 --"Chili Crude Player List", "Player List",, author=CarRepairer --6 --Gaussian noise, Box-Muller method, http://www.dspguru.com/dsp/howtos/how-to-generate-white-gaussian-noise --http://springrts.com/wiki/Lua_Scripting --7 --"gui_contextmenu.lua" -unit stat widget, by CarRepairer/WagonRepairer --8 --"unit_AA_micro.lua" -widget that micromanage AA, weaponsState example, by Jseah --9 --"cmd_retreat.lua" -Place 'retreat zones' on the map and order units to retreat to them at desired HP percentages, by CarRepairer (OPT_INTERNAL function) --"gui_epicmenu.lua" --"Extremely Powerful Ingame Chili Menu.", by Carrepairer --"gui_chili_integral_menu.lua" --Chili Integral Menu, by Licho, KingRaptor, Google Frog --10 --Thanks to versus666 for his endless playtesting and creating idea for improvement & bug report (eg: messy command queue case, widget overriding user's command case, "avoidance may be bad for gunship" case, avoidance depending on detected enemy sonar, constructor's retreat timeout, selection effect avoidance, ect) --11 -- Ref: http://en.wikipedia.org/wiki/Moving_average#Simple_moving_average (rolling average) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --Feature Tracking: -- Constructor under area reclaim will return to center of area command when sighting an enemy -- Attacked will mark last attacker and avoid them even when outside LOS for 3 second -- Unit outside user view will universally auto-avoidance, but remain still when seen -- Hold position prevent universal auto-avoidance when not seen, also prevent auto-retreat when unit perform auto-attack -- Unit under attack command will perform auto-retreat when reloading or shield < 50% regardless of hold-position state -- Cloakable unit will universally auto-avoid when moving... -- Area repair will cause unit auto-avoid from point to point (unit to repair); this is contrast to area reclaim. -- Area Reclaim/ressurect tolerance < area repair tolerance < move tolerance (unit within certain radius of target will ignore enemy/not avoid) -- Individual repair/reclaim command queue has same tolerance as area repair tolerance -- ???
gpl-2.0
lasko2112/legend-of-hondo
MMOCoreORB/bin/scripts/object/mobile/dressed_scolex_grath.lua
3
2196
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_mobile_dressed_scolex_grath = object_mobile_shared_dressed_scolex_grath:new { } ObjectTemplates:addTemplate(object_mobile_dressed_scolex_grath, "object/mobile/dressed_scolex_grath.iff")
agpl-3.0