diff --git a/cocos/scripting/lua-bindings/script/cocos2d/Cocos2d.lua b/cocos/scripting/lua-bindings/script/cocos2d/Cocos2d.lua index 386e19067a..40b721ebab 100644 --- a/cocos/scripting/lua-bindings/script/cocos2d/Cocos2d.lua +++ b/cocos/scripting/lua-bindings/script/cocos2d/Cocos2d.lua @@ -289,6 +289,55 @@ function cc.c4f( _r,_g,_b,_a ) return { r = _r, g = _g, b = _b, a = _a } end +local function isFloatColor(c) + return (c.r <= 1 and c.g <= 1 and c.b <= 1) and (math.ceil(c.r) ~= c.r or math.ceil(c.g) ~= c.g or math.ceil(c.b) ~= c.b) +end + +function cc.convertColor(input, typ) + assert(type(input) == "table" and input.r and input.g and input.b, "cc.convertColor() - invalid input color") + local ret + if typ == "3b" then + if isFloatColor(input) then + ret = {r = math.ceil(input.r * 255), g = math.ceil(input.g * 255), b = math.ceil(input.b * 255)} + else + ret = {r = input.r, g = input.g, b = input.b} + end + elseif typ == "4b" then + if isFloatColor(input) then + ret = {r = math.ceil(input.r * 255), g = math.ceil(input.g * 255), b = math.ceil(input.b * 255)} + else + ret = {r = input.r, g = input.g, b = input.b} + end + if input.a then + if math.ceil(input.a) ~= input.a or input.a >= 1 then + ret.a = input.a * 255 + else + ret.a = input.a + end + else + ret.a = 255 + end + elseif typ == "4f" then + if isFloatColor(input) then + ret = {r = input.r, g = input.g, b = input.b} + else + ret = {r = input.r / 255, g = input.g / 255, b = input.b / 255} + end + if input.a then + if math.ceil(input.a) ~= input.a or input.a >= 1 then + ret.a = input.a + else + ret.a = input.a / 255 + end + else + ret.a = 255 + end + else + error(string.format("cc.convertColor() - invalid type %s", typ), 0) + end + return ret +end + --Vertex2F function cc.vertex2F(_x,_y) return { x = _x, y = _y } diff --git a/cocos/scripting/lua-bindings/script/cocos2d/deprecated.lua b/cocos/scripting/lua-bindings/script/cocos2d/deprecated.lua new file mode 100644 index 0000000000..9c82fa8111 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/cocos2d/deprecated.lua @@ -0,0 +1,15 @@ + +function schedule(node, callback, delay) + local delay = cc.DelayTime:create(delay) + local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback)) + local action = cc.RepeatForever:create(sequence) + node:runAction(action) + return action +end + +function performWithDelay(node, callback, delay) + local delay = cc.DelayTime:create(delay) + local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback)) + node:runAction(sequence) + return sequence +end diff --git a/cocos/scripting/lua-bindings/script/cocos2d/extern.lua b/cocos/scripting/lua-bindings/script/cocos2d/extern.lua deleted file mode 100644 index 2c6687c55e..0000000000 --- a/cocos/scripting/lua-bindings/script/cocos2d/extern.lua +++ /dev/null @@ -1,93 +0,0 @@ - -function clone(object) - local lookup_table = {} - local function _copy(object) - if type(object) ~= "table" then - return object - elseif lookup_table[object] then - return lookup_table[object] - end - local new_table = {} - lookup_table[object] = new_table - for key, value in pairs(object) do - new_table[_copy(key)] = _copy(value) - end - return setmetatable(new_table, getmetatable(object)) - end - return _copy(object) -end - ---Create an class. -function class(classname, super) - local superType = type(super) - local cls - - if superType ~= "function" and superType ~= "table" then - superType = nil - super = nil - end - - if superType == "function" or (super and super.__ctype == 1) then - -- inherited from native C++ Object - cls = {} - - if superType == "table" then - -- copy fields from super - for k,v in pairs(super) do cls[k] = v end - cls.__create = super.__create - cls.super = super - else - cls.__create = super - end - - cls.ctor = function() end - cls.__cname = classname - cls.__ctype = 1 - - function cls.new(...) - local instance = cls.__create(...) - -- copy fields from class to native object - for k,v in pairs(cls) do instance[k] = v end - instance.class = cls - instance:ctor(...) - return instance - end - - else - -- inherited from Lua Object - if super then - cls = clone(super) - cls.super = super - else - cls = {ctor = function() end} - end - - cls.__cname = classname - cls.__ctype = 2 -- lua - cls.__index = cls - - function cls.new(...) - local instance = setmetatable({}, cls) - instance.class = cls - instance:ctor(...) - return instance - end - end - - return cls -end - -function schedule(node, callback, delay) - local delay = cc.DelayTime:create(delay) - local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback)) - local action = cc.RepeatForever:create(sequence) - node:runAction(action) - return action -end - -function performWithDelay(node, callback, delay) - local delay = cc.DelayTime:create(delay) - local sequence = cc.Sequence:create(delay, cc.CallFunc:create(callback)) - node:runAction(sequence) - return sequence -end diff --git a/cocos/scripting/lua-bindings/script/cocos2d/functions.lua b/cocos/scripting/lua-bindings/script/cocos2d/functions.lua new file mode 100644 index 0000000000..aa004503c7 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/cocos2d/functions.lua @@ -0,0 +1,634 @@ +--[[ + +Copyright (c) 2011-2014 chukong-inc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +function printLog(tag, fmt, ...) + local t = { + "[", + string.upper(tostring(tag)), + "] ", + string.format(tostring(fmt), ...) + } + print(table.concat(t)) +end + +function printError(fmt, ...) + printLog("ERR", fmt, ...) + print(debug.traceback("", 2)) +end + +function printInfo(fmt, ...) + if type(DEBUG) ~= "number" or DEBUG < 2 then return end + printLog("INFO", fmt, ...) +end + +local function dump_value_(v) + if type(v) == "string" then + v = "\"" .. v .. "\"" + end + return tostring(v) +end + +function dump(value, desciption, nesting) + if type(nesting) ~= "number" then nesting = 3 end + + local lookupTable = {} + local result = {} + + local traceback = string.split(debug.traceback("", 2), "\n") + print("dump from: " .. string.trim(traceback[3])) + + local function dump_(value, desciption, indent, nest, keylen) + desciption = desciption or "" + local spc = "" + if type(keylen) == "number" then + spc = string.rep(" ", keylen - string.len(dump_value_(desciption))) + end + if type(value) ~= "table" then + result[#result +1 ] = string.format("%s%s%s = %s", indent, dump_value_(desciption), spc, dump_value_(value)) + elseif lookupTable[tostring(value)] then + result[#result +1 ] = string.format("%s%s%s = *REF*", indent, dump_value_(desciption), spc) + else + lookupTable[tostring(value)] = true + if nest > nesting then + result[#result +1 ] = string.format("%s%s = *MAX NESTING*", indent, dump_value_(desciption)) + else + result[#result +1 ] = string.format("%s%s = {", indent, dump_value_(desciption)) + local indent2 = indent.." " + local keys = {} + local keylen = 0 + local values = {} + for k, v in pairs(value) do + keys[#keys + 1] = k + local vk = dump_value_(k) + local vkl = string.len(vk) + if vkl > keylen then keylen = vkl end + values[k] = v + end + table.sort(keys, function(a, b) + if type(a) == "number" and type(b) == "number" then + return a < b + else + return tostring(a) < tostring(b) + end + end) + for i, k in ipairs(keys) do + dump_(values[k], k, indent2, nest + 1, keylen) + end + result[#result +1] = string.format("%s}", indent) + end + end + end + dump_(value, desciption, "- ", 1) + + for i, line in ipairs(result) do + print(line) + end +end + +function printf(fmt, ...) + print(string.format(tostring(fmt), ...)) +end + +function checknumber(value, base) + return tonumber(value, base) or 0 +end + +function checkint(value) + return math.round(checknumber(value)) +end + +function checkbool(value) + return (value ~= nil and value ~= false) +end + +function checktable(value) + if type(value) ~= "table" then value = {} end + return value +end + +function isset(hashtable, key) + local t = type(hashtable) + return (t == "table" or t == "userdata") and hashtable[key] ~= nil +end + +local setmetatableindex_ +setmetatableindex_ = function(t, index) + if type(t) == "userdata" then + local peer = tolua.getpeer(t) + if not peer then + peer = {} + tolua.setpeer(t, peer) + end + setmetatableindex_(peer, index) + else + local mt = getmetatable(t) + if not mt then mt = {} end + if not mt.__index then + mt.__index = index + setmetatable(t, mt) + elseif mt.__index ~= index then + setmetatableindex_(mt, index) + end + end +end +setmetatableindex = setmetatableindex_ + +function clone(object) + local lookup_table = {} + local function _copy(object) + if type(object) ~= "table" then + return object + elseif lookup_table[object] then + return lookup_table[object] + end + local newObject = {} + lookup_table[object] = newObject + for key, value in pairs(object) do + newObject[_copy(key)] = _copy(value) + end + return setmetatable(newObject, getmetatable(object)) + end + return _copy(object) +end + +function class(classname, ...) + local cls = {__cname = classname} + + local supers = {...} + for _, super in ipairs(supers) do + local superType = type(super) + assert(superType == "nil" or superType == "table" or superType == "function", + string.format("class() - create class \"%s\" with invalid super class type \"%s\"", + classname, superType)) + + if superType == "function" then + assert(cls.__create == nil, + string.format("class() - create class \"%s\" with more than one creating function", + classname)); + -- if super is function, set it to __create + cls.__create = super + elseif superType == "table" then + if super[".isclass"] then + -- super is native class + assert(cls.__create == nil, + string.format("class() - create class \"%s\" with more than one creating function or native class", + classname)); + cls.__create = function() return super:create() end + else + -- super is pure lua class + cls.__supers = cls.__supers or {} + cls.__supers[#cls.__supers + 1] = super + if not cls.super then + -- set first super pure lua class as class.super + cls.super = super + end + end + else + error(string.format("class() - create class \"%s\" with invalid super type", + classname), 0) + end + end + + cls.__index = cls + if not cls.__supers or #cls.__supers == 1 then + setmetatable(cls, {__index = cls.super}) + else + setmetatable(cls, {__index = function(_, key) + local supers = cls.__supers + for i = 1, #supers do + local super = supers[i] + if super[key] then return super[key] end + end + end}) + end + + if not cls.ctor then + -- add default constructor + cls.ctor = function() end + end + cls.new = function(...) + local instance + if cls.__create then + instance = cls.__create(...) + else + instance = {} + end + setmetatableindex(instance, cls) + instance.class = cls + instance:ctor(...) + return instance + end + cls.create = function(_, ...) + return cls.new(...) + end + + return cls +end + +local iskindof_ +iskindof_ = function(cls, name) + local __index = rawget(cls, "__index") + if type(__index) == "table" and rawget(__index, "__cname") == name then return true end + + if rawget(cls, "__cname") == name then return true end + local __supers = rawget(cls, "__supers") + if not __supers then return false end + for _, super in ipairs(__supers) do + if iskindof_(super, name) then return true end + end + return false +end + +function iskindof(obj, classname) + local t = type(obj) + if t ~= "table" and t ~= "userdata" then return false end + + local mt + if t == "userdata" then + if tolua.iskindof(obj, classname) then return true end + mt = tolua.getpeer(obj) + else + mt = getmetatable(obj) + end + if mt then + return iskindof_(mt, classname) + end + return false +end + +function import(moduleName, currentModuleName) + local currentModuleNameParts + local moduleFullName = moduleName + local offset = 1 + + while true do + if string.byte(moduleName, offset) ~= 46 then -- . + moduleFullName = string.sub(moduleName, offset) + if currentModuleNameParts and #currentModuleNameParts > 0 then + moduleFullName = table.concat(currentModuleNameParts, ".") .. "." .. moduleFullName + end + break + end + offset = offset + 1 + + if not currentModuleNameParts then + if not currentModuleName then + local n,v = debug.getlocal(3, 1) + currentModuleName = v + end + + currentModuleNameParts = string.split(currentModuleName, ".") + end + table.remove(currentModuleNameParts, #currentModuleNameParts) + end + + return require(moduleFullName) +end + +function handler(obj, method) + return function(...) + return method(obj, ...) + end +end + +function math.newrandomseed() + local ok, socket = pcall(function() + return require("socket") + end) + + if ok then + -- 如果集成了 socket 模块,则使用 socket.gettime() 获取随机数种子 + math.randomseed(socket.gettime() * 1000) + else + math.randomseed(os.time()) + end + math.random() + math.random() + math.random() + math.random() +end + +function math.round(value) + value = checknumber(value) + return math.floor(value + 0.5) +end + +local pi_div_180 = math.pi / 180 +function math.angle2radian(angle) + return angle * pi_div_180 +end + +local pi_mul_180 = math.pi * 180 +function math.radian2angle(radian) + return radian / pi_mul_180 +end + +function io.exists(path) + local file = io.open(path, "r") + if file then + io.close(file) + return true + end + return false +end + +function io.readfile(path) + local file = io.open(path, "r") + if file then + local content = file:read("*a") + io.close(file) + return content + end + return nil +end + +function io.writefile(path, content, mode) + mode = mode or "w+b" + local file = io.open(path, mode) + if file then + if file:write(content) == nil then return false end + io.close(file) + return true + else + return false + end +end + +function io.pathinfo(path) + local pos = string.len(path) + local extpos = pos + 1 + while pos > 0 do + local b = string.byte(path, pos) + if b == 46 then -- 46 = char "." + extpos = pos + elseif b == 47 then -- 47 = char "/" + break + end + pos = pos - 1 + end + + local dirname = string.sub(path, 1, pos) + local filename = string.sub(path, pos + 1) + extpos = extpos - pos + local basename = string.sub(filename, 1, extpos - 1) + local extname = string.sub(filename, extpos) + return { + dirname = dirname, + filename = filename, + basename = basename, + extname = extname + } +end + +function io.filesize(path) + local size = false + local file = io.open(path, "r") + if file then + local current = file:seek() + size = file:seek("end") + file:seek("set", current) + io.close(file) + end + return size +end + +function table.nums(t) + local count = 0 + for k, v in pairs(t) do + count = count + 1 + end + return count +end + +function table.keys(hashtable) + local keys = {} + for k, v in pairs(hashtable) do + keys[#keys + 1] = k + end + return keys +end + +function table.values(hashtable) + local values = {} + for k, v in pairs(hashtable) do + values[#values + 1] = v + end + return values +end + +function table.merge(dest, src) + for k, v in pairs(src) do + dest[k] = v + end +end + +function table.insertto(dest, src, begin) + begin = checkint(begin) + if begin <= 0 then + begin = #dest + 1 + end + + local len = #src + for i = 0, len - 1 do + dest[i + begin] = src[i + 1] + end +end + +function table.indexof(array, value, begin) + for i = begin or 1, #array do + if array[i] == value then return i end + end + return false +end + +function table.keyof(hashtable, value) + for k, v in pairs(hashtable) do + if v == value then return k end + end + return nil +end + +function table.removebyvalue(array, value, removeall) + local c, i, max = 0, 1, #array + while i <= max do + if array[i] == value then + table.remove(array, i) + c = c + 1 + i = i - 1 + max = max - 1 + if not removeall then break end + end + i = i + 1 + end + return c +end + +function table.map(t, fn) + for k, v in pairs(t) do + t[k] = fn(v, k) + end +end + +function table.walk(t, fn) + for k,v in pairs(t) do + fn(v, k) + end +end + +function table.filter(t, fn) + for k, v in pairs(t) do + if not fn(v, k) then t[k] = nil end + end +end + +function table.unique(t, bArray) + local check = {} + local n = {} + local idx = 1 + for k, v in pairs(t) do + if not check[v] then + if bArray then + n[idx] = v + idx = idx + 1 + else + n[k] = v + end + check[v] = true + end + end + return n +end + +string._htmlspecialchars_set = {} +string._htmlspecialchars_set["&"] = "&" +string._htmlspecialchars_set["\""] = """ +string._htmlspecialchars_set["'"] = "'" +string._htmlspecialchars_set["<"] = "<" +string._htmlspecialchars_set[">"] = ">" + +function string.htmlspecialchars(input) + for k, v in pairs(string._htmlspecialchars_set) do + input = string.gsub(input, k, v) + end + return input +end + +function string.restorehtmlspecialchars(input) + for k, v in pairs(string._htmlspecialchars_set) do + input = string.gsub(input, v, k) + end + return input +end + +function string.nl2br(input) + return string.gsub(input, "\n", "
") +end + +function string.text2html(input) + input = string.gsub(input, "\t", " ") + input = string.htmlspecialchars(input) + input = string.gsub(input, " ", " ") + input = string.nl2br(input) + return input +end + +function string.split(input, delimiter) + input = tostring(input) + delimiter = tostring(delimiter) + if (delimiter=='') then return false end + local pos,arr = 0, {} + -- for each divider found + for st,sp in function() return string.find(input, delimiter, pos, true) end do + table.insert(arr, string.sub(input, pos, st - 1)) + pos = sp + 1 + end + table.insert(arr, string.sub(input, pos)) + return arr +end + +function string.ltrim(input) + return string.gsub(input, "^[ \t\n\r]+", "") +end + +function string.rtrim(input) + return string.gsub(input, "[ \t\n\r]+$", "") +end + +function string.trim(input) + input = string.gsub(input, "^[ \t\n\r]+", "") + return string.gsub(input, "[ \t\n\r]+$", "") +end + +function string.ucfirst(input) + return string.upper(string.sub(input, 1, 1)) .. string.sub(input, 2) +end + +local function urlencodechar(char) + return "%" .. string.format("%02X", string.byte(char)) +end +function string.urlencode(input) + -- convert line endings + input = string.gsub(tostring(input), "\n", "\r\n") + -- escape all characters but alphanumeric, '.' and '-' + input = string.gsub(input, "([^%w%.%- ])", urlencodechar) + -- convert spaces to "+" symbols + return string.gsub(input, " ", "+") +end + +function string.urldecode(input) + input = string.gsub (input, "+", " ") + input = string.gsub (input, "%%(%x%x)", function(h) return string.char(checknumber(h,16)) end) + input = string.gsub (input, "\r\n", "\n") + return input +end + +function string.utf8len(input) + local len = string.len(input) + local left = len + local cnt = 0 + local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc} + while left ~= 0 do + local tmp = string.byte(input, -left) + local i = #arr + while arr[i] do + if tmp >= arr[i] then + left = left - i + break + end + i = i - 1 + end + cnt = cnt + 1 + end + return cnt +end + +function string.formatnumberthousands(num) + local formatted = tostring(checknumber(num)) + local k + while true do + formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') + if k == 0 then break end + end + return formatted +end diff --git a/cocos/scripting/lua-bindings/script/framework/audio.lua b/cocos/scripting/lua-bindings/script/framework/audio.lua new file mode 100644 index 0000000000..59eb5663b7 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/audio.lua @@ -0,0 +1,206 @@ +--[[ + +Copyright (c) 2011-2014 chukong-inc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +local audio = {} + +local engine = cc.SimpleAudioEngine:getInstance() + +function audio.getMusicVolume() + local volume = engine:getMusicVolume() + if DEBUG > 1 then + printf("[audio] getMusicVolume() - volume: %0.2f", volume) + end + return volume +end + +function audio.setMusicVolume(volume) + volume = checknumber(volume) + if DEBUG > 1 then + printf("[audio] setMusicVolume() - volume: %0.2f", volume) + end + engine:setMusicVolume(volume) +end + +function audio.preloadMusic(filename) + assert(filename, "audio.preloadMusic() - invalid filename") + if DEBUG > 1 then + printf("[audio] preloadMusic() - filename: %s", tostring(filename)) + end + engine:preloadMusic(filename) +end + +function audio.playMusic(filename, isLoop) + assert(filename, "audio.playMusic() - invalid filename") + if type(isLoop) ~= "boolean" then isLoop = true end + + audio.stopMusic() + if DEBUG > 1 then + printf("[audio] playMusic() - filename: %s, isLoop: %s", tostring(filename), tostring(isLoop)) + end + engine:playMusic(filename, isLoop) +end + +function audio.stopMusic(isReleaseData) + isReleaseData = checkbool(isReleaseData) + if DEBUG > 1 then + printf("[audio] stopMusic() - isReleaseData: %s", tostring(isReleaseData)) + end + engine:stopMusic(isReleaseData) +end + +function audio.pauseMusic() + if DEBUG > 1 then + printf("[audio] pauseMusic()") + end + engine:pauseMusic() +end + +function audio.resumeMusic() + if DEBUG > 1 then + printf("[audio] resumeMusic()") + end + engine:resumeMusic() +end + +function audio.rewindMusic() + if DEBUG > 1 then + printf("[audio] rewindMusic()") + end + engine:rewindMusic() +end + +function audio.isMusicPlaying() + local ret = engine:isMusicPlaying() + if DEBUG > 1 then + printf("[audio] isMusicPlaying() - ret: %s", tostring(ret)) + end + return ret +end + +function audio.getSoundsVolume() + local volume = engine:getEffectsVolume() + if DEBUG > 1 then + printf("[audio] getSoundsVolume() - volume: %0.1f", volume) + end + return volume +end + +function audio.setSoundsVolume(volume) + volume = checknumber(volume) + if DEBUG > 1 then + printf("[audio] setSoundsVolume() - volume: %0.1f", volume) + end + engine:setEffectsVolume(volume) +end + +function audio.playSound(filename, isLoop) + if not filename then + printError("audio.playSound() - invalid filename") + return + end + if type(isLoop) ~= "boolean" then isLoop = false end + if DEBUG > 1 then + printf("[audio] playSound() - filename: %s, isLoop: %s", tostring(filename), tostring(isLoop)) + end + return engine:playEffect(filename, isLoop) +end + +function audio.pauseSound(handle) + if not handle then + printError("audio.pauseSound() - invalid handle") + return + end + if DEBUG > 1 then + printf("[audio] pauseSound() - handle: %s", tostring(handle)) + end + engine:pauseEffect(handle) +end + +function audio.pauseAllSounds() + if DEBUG > 1 then + printf("[audio] pauseAllSounds()") + end + engine:pauseAllEffects() +end + +function audio.resumeSound(handle) + if not handle then + printError("audio.resumeSound() - invalid handle") + return + end + if DEBUG > 1 then + printf("[audio] resumeSound() - handle: %s", tostring(handle)) + end + engine:resumeEffect(handle) +end + +function audio.resumeAllSounds() + if DEBUG > 1 then + printf("[audio] resumeAllSounds()") + end + engine:resumeAllEffects() +end + +function audio.stopSound(handle) + if not handle then + printError("audio.stopSound() - invalid handle") + return + end + if DEBUG > 1 then + printf("[audio] stopSound() - handle: %s", tostring(handle)) + end + engine:stopEffect(handle) +end + +function audio.stopAllSounds() + if DEBUG > 1 then + printf("[audio] stopAllSounds()") + end + engine:stopAllEffects() +end +audio.stopAllEffects = audio.stopAllSounds + +function audio.preloadSound(filename) + if not filename then + printError("audio.preloadSound() - invalid filename") + return + end + if DEBUG > 1 then + printf("[audio] preloadSound() - filename: %s", tostring(filename)) + end + engine:preloadEffect(filename) +end + +function audio.unloadSound(filename) + if not filename then + printError("audio.unloadSound() - invalid filename") + return + end + if DEBUG > 1 then + printf("[audio] unloadSound() - filename: %s", tostring(filename)) + end + engine:unloadEffect(filename) +end + +return audio diff --git a/cocos/scripting/lua-bindings/script/framework/components/event.lua b/cocos/scripting/lua-bindings/script/framework/components/event.lua new file mode 100644 index 0000000000..9fc7f13693 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/components/event.lua @@ -0,0 +1,155 @@ + +local Event = class("Event") + +local EXPORTED_METHODS = { + "addEventListener", + "dispatchEvent", + "removeEventListener", + "removeEventListenersByTag", + "removeEventListenersByEvent", + "removeAllEventListeners", + "hasEventListener", + "dumpAllEventListeners", +} + +function Event:init_() + self.target_ = nil + self.listeners_ = {} + self.nextListenerHandleIndex_ = 0 +end + +function Event:bind(target) + self:init_() + cc.setmethods(target, self, EXPORTED_METHODS) + self.target_ = target +end + +function Event:unbind(target) + cc.unsetmethods(target, EXPORTED_METHODS) + self:init_() +end + +function Event:addEventListener(eventName, listener, tag) + assert(type(eventName) == "string" and eventName ~= "", + "Event:addEventListener() - invalid eventName") + eventName = string.upper(eventName) + if self.listeners_[eventName] == nil then + self.listeners_[eventName] = {} + end + + self.nextListenerHandleIndex_ = self.nextListenerHandleIndex_ + 1 + local handle = tostring(self.nextListenerHandleIndex_) + tag = tag or "" + self.listeners_[eventName][handle] = {listener, tag} + + if DEBUG > 1 then + printInfo("%s [Event] addEventListener() - event: %s, handle: %s, tag: \"%s\"", + tostring(self.target_), eventName, handle, tostring(tag)) + end + + return self.target_, handle +end + +function Event:dispatchEvent(event) + event.name = string.upper(tostring(event.name)) + local eventName = event.name + if DEBUG > 1 then + printInfo("%s [Event] dispatchEvent() - event %s", tostring(self.target_), eventName) + end + + if self.listeners_[eventName] == nil then return end + event.target = self.target_ + event.stop_ = false + event.stop = function(self) + self.stop_ = true + end + + for handle, listener in pairs(self.listeners_[eventName]) do + if DEBUG > 1 then + printInfo("%s [Event] dispatchEvent() - dispatching event %s to listener %s", tostring(self.target_), eventName, handle) + end + -- listener[1] = listener + -- listener[2] = tag + event.tag = listener[2] + listener[1](event) + if event.stop_ then + if DEBUG > 1 then + printInfo("%s [Event] dispatchEvent() - break dispatching for event %s", tostring(self.target_), eventName) + end + break + end + end + + return self.target_ +end + +function Event:removeEventListener(handleToRemove) + for eventName, listenersForEvent in pairs(self.listeners_) do + for handle, _ in pairs(listenersForEvent) do + if handle == handleToRemove then + listenersForEvent[handle] = nil + if DEBUG > 1 then + printInfo("%s [Event] removeEventListener() - remove listener [%s] for event %s", tostring(self.target_), handle, eventName) + end + return self.target_ + end + end + end + + return self.target_ +end + +function Event:removeEventListenersByTag(tagToRemove) + for eventName, listenersForEvent in pairs(self.listeners_) do + for handle, listener in pairs(listenersForEvent) do + -- listener[1] = listener + -- listener[2] = tag + if listener[2] == tagToRemove then + listenersForEvent[handle] = nil + if DEBUG > 1 then + printInfo("%s [Event] removeEventListener() - remove listener [%s] for event %s", tostring(self.target_), handle, eventName) + end + end + end + end + + return self.target_ +end + +function Event:removeEventListenersByEvent(eventName) + self.listeners_[string.upper(eventName)] = nil + if DEBUG > 1 then + printInfo("%s [Event] removeAllEventListenersForEvent() - remove all listeners for event %s", tostring(self.target_), eventName) + end + return self.target_ +end + +function Event:removeAllEventListeners() + self.listeners_ = {} + if DEBUG > 1 then + printInfo("%s [Event] removeAllEventListeners() - remove all listeners", tostring(self.target_)) + end + return self.target_ +end + +function Event:hasEventListener(eventName) + eventName = string.upper(tostring(eventName)) + local t = self.listeners_[eventName] + for _, __ in pairs(t) do + return true + end + return false +end + +function Event:dumpAllEventListeners() + print("---- Event:dumpAllEventListeners() ----") + for name, listeners in pairs(self.listeners_) do + printf("-- event: %s", name) + for handle, listener in pairs(listeners) do + printf("-- listener: %s, handle: %s", tostring(listener[1]), tostring(handle)) + end + end + return self.target_ +end + +return Event diff --git a/cocos/scripting/lua-bindings/script/framework/device.lua b/cocos/scripting/lua-bindings/script/framework/device.lua new file mode 100644 index 0000000000..ea73f08812 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/device.lua @@ -0,0 +1,104 @@ +--[[ + +Copyright (c) 2011-2014 chukong-inc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +local device = {} + +device.platform = "unknown" +device.model = "unknown" + +local app = cc.Application:getInstance() +local target = app:getTargetPlatform() +if target == cc.PLATFORM_OS_WINDOWS then + device.platform = "windows" +elseif target == cc.PLATFORM_OS_MAC then + device.platform = "mac" +elseif target == cc.PLATFORM_OS_ANDROID then + device.platform = "android" +elseif target == cc.PLATFORM_OS_IPHONE or target == cc.PLATFORM_OS_IPAD then + device.platform = "ios" + local w, h = framesize.width, framesize.height + if w == 640 and h == 960 then + device.model = "iphone 4" + elseif w == 640 and h == 1136 then + device.model = "iphone 5" + elseif w == 750 and h == 1334 then + device.model = "iphone 6" + elseif w == 1242 and h == 2208 then + device.model = "iphone 6 plus" + elseif w == 768 and h == 1024 then + device.model = "ipad" + elseif w == 1536 and h == 2048 then + device.model = "ipad retina" + end +elseif target == cc.PLATFORM_OS_WINRT then + device.platform = "winrt" +elseif target == cc.PLATFORM_OS_WP8 then + device.platform = "wp8" +end + +local language_ = app:getCurrentLanguage() +if language_ == cc.LANGUAGE_CHINESE then + language_ = "cn" +elseif language_ == cc.LANGUAGE_FRENCH then + language_ = "fr" +elseif language_ == cc.LANGUAGE_ITALIAN then + language_ = "it" +elseif language_ == cc.LANGUAGE_GERMAN then + language_ = "gr" +elseif language_ == cc.LANGUAGE_SPANISH then + language_ = "sp" +elseif language_ == cc.LANGUAGE_RUSSIAN then + language_ = "ru" +elseif language_ == cc.LANGUAGE_KOREAN then + language_ = "kr" +elseif language_ == cc.LANGUAGE_JAPANESE then + language_ = "jp" +elseif language_ == cc.LANGUAGE_HUNGARIAN then + language_ = "hu" +elseif language_ == cc.LANGUAGE_PORTUGUESE then + language_ = "pt" +elseif language_ == cc.LANGUAGE_ARABIC then + language_ = "ar" +else + language_ = "en" +end + +device.language = language_ +device.writablePath = cc.FileUtils:getInstance():getWritablePath() +device.directorySeparator = "/" +device.pathSeparator = ":" +if device.platform == "windows" then + device.directorySeparator = "\\" + device.pathSeparator = ";" +end + +printInfo("# device.platform = " .. device.platform) +printInfo("# device.model = " .. device.model) +printInfo("# device.language = " .. device.language) +printInfo("# device.writablePath = " .. device.writablePath) +printInfo("# device.directorySeparator = " .. device.directorySeparator) +printInfo("# device.pathSeparator = " .. device.pathSeparator) +printInfo("#") + +return device diff --git a/cocos/scripting/lua-bindings/script/framework/display.lua b/cocos/scripting/lua-bindings/script/framework/display.lua new file mode 100644 index 0000000000..c32ed4a948 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/display.lua @@ -0,0 +1,534 @@ +--[[ + +Copyright (c) 2011-2014 chukong-inc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +local display = {} + +local director = cc.Director:getInstance() +local view = director:getOpenGLView() + +if not view then + local width = 960 + local height = 640 + if CC_DESIGN_RESOLUTION then + if CC_DESIGN_RESOLUTION.width then + width = CC_DESIGN_RESOLUTION.width + end + if CC_DESIGN_RESOLUTION.height then + height = CC_DESIGN_RESOLUTION.height + end + end + view = cc.GLViewImpl:createWithRect("Cocos2d-Lua", cc.rect(0, 0, width, height)) + director:setOpenGLView(view) +end + +local framesize = view:getFrameSize() +local textureCache = director:getTextureCache() +local spriteFrameCache = cc.SpriteFrameCache:getInstance() +local animationCache = cc.AnimationCache:getInstance() + +-- auto scale +local function checkResolution(r) + r.width = checknumber(r.width) + r.height = checknumber(r.height) + r.autoscale = string.upper(r.autoscale) + assert(r.width > 0 and r.height > 0, + string.format("display - invalid design resolution size %d, %d", r.width, r.height)) +end + +local function setDesignResolution(r, framesize) + if r.autoscale == "FILL_ALL" then + view:setDesignResolutionSize(framesize.width, framesize.height, cc.ResolutionPolicy.FILL_ALL) + else + local scaleX, scaleY = framesize.width / r.width, framesize.height / r.height + local width, height = framesize.width, framesize.height + if r.autoscale == "FIXED_WIDTH" then + width = framesize.width / scaleX + height = framesize.height / scaleX + elseif r.autoscale == "FIXED_HEIGHT" then + width = framesize.width / scaleY + height = framesize.height / scaleY + else + printError(string.format("display - invalid r.autoscale \"%s\"", r.autoscale)) + end + view:setDesignResolutionSize(width, height, cc.ResolutionPolicy.NO_BORDER) + end +end + +local function setConstants() + local sizeInPixels = view:getFrameSize() + display.sizeInPixels = {width = sizeInPixels.width, height = sizeInPixels.height} + + local viewsize = director:getWinSize() + display.contentScaleFactor = director:getContentScaleFactor() + display.size = {width = viewsize.width, height = viewsize.height} + display.width = display.size.width + display.height = display.size.height + display.cx = display.width / 2 + display.cy = display.height / 2 + display.c_left = -display.width / 2 + display.c_right = display.width / 2 + display.c_top = display.height / 2 + display.c_bottom = -display.height / 2 + display.left = 0 + display.right = display.width + display.top = display.height + display.bottom = 0 + display.center = cc.p(display.cx, display.cy) + display.left_top = cc.p(display.left, display.top) + display.left_bottom = cc.p(display.left, display.bottom) + display.left_center = cc.p(display.left, display.cy) + display.right_top = cc.p(display.right, display.top) + display.right_bottom = cc.p(display.right, display.bottom) + display.right_center = cc.p(display.right, display.cy) + display.top_center = cc.p(display.cx, display.top) + display.top_bottom = cc.p(display.cx, display.bottom) + + printInfo(string.format("# display.sizeInPixels = {width = %0.2f, height = %0.2f}", display.sizeInPixels.width, display.sizeInPixels.height)) + printInfo(string.format("# display.size = {width = %0.2f, height = %0.2f}", display.size.width, display.size.height)) + printInfo(string.format("# display.contentScaleFactor = %0.2f", display.contentScaleFactor)) + printInfo(string.format("# display.width = %0.2f", display.width)) + printInfo(string.format("# display.height = %0.2f", display.height)) + printInfo(string.format("# display.cx = %0.2f", display.cx)) + printInfo(string.format("# display.cy = %0.2f", display.cy)) + printInfo(string.format("# display.left = %0.2f", display.left)) + printInfo(string.format("# display.right = %0.2f", display.right)) + printInfo(string.format("# display.top = %0.2f", display.top)) + printInfo(string.format("# display.bottom = %0.2f", display.bottom)) + printInfo(string.format("# display.c_left = %0.2f", display.c_left)) + printInfo(string.format("# display.c_right = %0.2f", display.c_right)) + printInfo(string.format("# display.c_top = %0.2f", display.c_top)) + printInfo(string.format("# display.c_bottom = %0.2f", display.c_bottom)) + printInfo(string.format("# display.center = {x = %0.2f, y = %0.2f}", display.center.x, display.center.y)) + printInfo(string.format("# display.left_top = {x = %0.2f, y = %0.2f}", display.left_top.x, display.left_top.y)) + printInfo(string.format("# display.left_bottom = {x = %0.2f, y = %0.2f}", display.left_bottom.x, display.left_bottom.y)) + printInfo(string.format("# display.left_center = {x = %0.2f, y = %0.2f}", display.left_center.x, display.left_center.y)) + printInfo(string.format("# display.right_top = {x = %0.2f, y = %0.2f}", display.right_top.x, display.right_top.y)) + printInfo(string.format("# display.right_bottom = {x = %0.2f, y = %0.2f}", display.right_bottom.x, display.right_bottom.y)) + printInfo(string.format("# display.right_center = {x = %0.2f, y = %0.2f}", display.right_center.x, display.right_center.y)) + printInfo(string.format("# display.top_center = {x = %0.2f, y = %0.2f}", display.top_center.x, display.top_center.y)) + printInfo(string.format("# display.top_bottom = {x = %0.2f, y = %0.2f}", display.top_bottom.x, display.top_bottom.y)) + printInfo("#") +end + +function display.setAutoScale(configs) + if type(configs) ~= "table" then return end + + checkResolution(configs) + if type(configs.callback) == "function" then + local c = configs.callback(framesize) + for k, v in pairs(c or {}) do + configs[k] = v + end + checkResolution(configs) + end + + setDesignResolution(configs, framesize) + + printInfo(string.format("# design resolution size = {width = %0.2f, height = %0.2f}", configs.width, configs.height)) + printInfo(string.format("# design resolution autoscale = %s", configs.autoscale)) + setConstants() +end + +if type(CC_DESIGN_RESOLUTION) == "table" then + display.setAutoScale(CC_DESIGN_RESOLUTION) +end + +display.COLOR_WHITE = cc.c3b(255, 255, 255) +display.COLOR_BLACK = cc.c3b(0, 0, 0) +display.COLOR_RED = cc.c3b(255, 0, 0) +display.COLOR_GREEN = cc.c3b(0, 255, 0) +display.COLOR_BLUE = cc.c3b(0, 0, 255) + +display.AUTO_SIZE = 0 +display.FIXED_SIZE = 1 +display.LEFT_TO_RIGHT = 0 +display.RIGHT_TO_LEFT = 1 +display.TOP_TO_BOTTOM = 2 +display.BOTTOM_TO_TOP = 3 + +display.CENTER = cc.p(0.5, 0.5) +display.LEFT_TOP = cc.p(0, 1) +display.LEFT_BOTTOM = cc.p(0, 0) +display.LEFT_CENTER = cc.p(0, 0.5) +display.RIGHT_TOP = cc.p(1, 1) +display.RIGHT_BOTTOM = cc.p(1, 0) +display.RIGHT_CENTER = cc.p(1, 0.5) +display.CENTER_TOP = cc.p(0.5, 1) +display.CENTER_BOTTOM = cc.p(0.5, 0) + +display.SCENE_TRANSITIONS = { + CROSSFADE = cc.TransitionCrossFade, + FADE = {cc.TransitionFade, cc.c3b(0, 0, 0)}, + FADEBL = cc.TransitionFadeBL, + FADEDOWN = cc.TransitionFadeDown, + FADETR = cc.TransitionFadeTR, + FADEUP = cc.TransitionFadeUp, + FLIPANGULAR = {cc.TransitionFlipAngular, cc.TRANSITION_ORIENTATION_LEFT_OVER}, + FLIPX = {cc.TransitionFlipX, cc.TRANSITION_ORIENTATION_LEFT_OVER}, + FLIPY = {cc.TransitionFlipY, cc.TRANSITION_ORIENTATION_UP_OVER}, + JUMPZOOM = cc.TransitionJumpZoom, + MOVEINB = cc.TransitionMoveInB, + MOVEINL = cc.TransitionMoveInL, + MOVEINR = cc.TransitionMoveInR, + MOVEINT = cc.TransitionMoveInT, + PAGETURN = {cc.TransitionPageTurn, false}, + ROTOZOOM = cc.TransitionRotoZoom, + SHRINKGROW = cc.TransitionShrinkGrow, + SLIDEINB = cc.TransitionSlideInB, + SLIDEINL = cc.TransitionSlideInL, + SLIDEINR = cc.TransitionSlideInR, + SLIDEINT = cc.TransitionSlideInT, + SPLITCOLS = cc.TransitionSplitCols, + SPLITROWS = cc.TransitionSplitRows, + TURNOFFTILES = cc.TransitionTurnOffTiles, + ZOOMFLIPANGULAR = cc.TransitionZoomFlipAngular, + ZOOMFLIPX = {cc.TransitionZoomFlipX, cc.TRANSITION_ORIENTATION_LEFT_OVER}, + ZOOMFLIPY = {cc.TransitionZoomFlipY, cc.TRANSITION_ORIENTATION_UP_OVER}, +} + +display.TEXTURES_PIXEL_FORMAT = {} + +display.DEFAULT_TTF_FONT = "Arial" +display.DEFAULT_TTF_FONT_SIZE = 32 + + +local PARAMS_EMPTY = {} +local RECT_ZERO = cc.rect(0, 0, 0, 0) + +local sceneIndex = 0 +function display.newScene(name, params) + params = params or PARAMS_EMPTY + sceneIndex = sceneIndex + 1 + local scene + if not params.physics then + scene = cc.Scene:create() + else + scene = cc.Scene:createWithPhysics() + end + scene.name_ = string.format("%s:%d", name or "", sceneIndex) + + if params.transition then + scene = display.wrapSceneWithTransition(scene, params.transition, params.time, params.more) + end + + return scene +end + +function display.wrapScene(scene, transition, time, more) + local key = string.upper(tostring(transition)) + + if key == "RANDOM" then + local keys = table.keys(display.SCENE_TRANSITIONS) + key = keys[math.random(1, #keys)] + end + + if display.SCENE_TRANSITIONS[key] then + local t = display.SCENE_TRANSITIONS[key] + time = time or 0.2 + more = more or t[2] + if type(t) == "table" then + scene = t[1]:create(time, scene, more) + else + scene = t:create(time, scene) + end + else + error(string.format("display.wrapScene() - invalid transition %s", tostring(transition))) + end + return scene +end + +function display.runScene(newScene, transition, time, more) + if director:getRunningScene() then + if transition then + newScene = display.wrapScene(newScene, transition, time, more) + end + director:replaceScene(newScene) + else + director:runWithScene(newScene) + end +end + +function display.getRunningScene() + return director:getRunningScene() +end + +function display.newNode() + return cc.Node:create() +end + +function display.newLayer(...) + local params = {...} + local c = #params + local layer + if c == 0 then + -- /** creates a fullscreen black layer */ + -- static Layer *create(); + layer = cc.Layer:create() + elseif c == 1 then + -- /** creates a Layer with color. Width and height are the window size. */ + -- static LayerColor * create(const Color4B& color); + layer = cc.LayerColor:create(cc.convertColor(params[1], "4b")) + elseif c == 2 then + -- /** creates a Layer with color, width and height in Points */ + -- static LayerColor * create(const Color4B& color, const Size& size); + -- + -- /** Creates a full-screen Layer with a gradient between start and end. */ + -- static LayerGradient* create(const Color4B& start, const Color4B& end); + local color1 = cc.convertColor(params[1], "4b") + local p2 = params[2] + assert(type(p2) == "table" and (p2.width or p2.r), "display.newLayer() - invalid paramerter 2") + if p2.r then + layer = cc.LayerGradient:create(color1, cc.convertColor(p2, "4b")) + else + layer = cc.LayerColor:create(color1, p2.width, p2.height) + end + elseif c == 3 then + -- /** creates a Layer with color, width and height in Points */ + -- static LayerColor * create(const Color4B& color, GLfloat width, GLfloat height); + -- + -- /** Creates a full-screen Layer with a gradient between start and end in the direction of v. */ + -- static LayerGradient* create(const Color4B& start, const Color4B& end, const Vec2& v); + local color1 = cc.convertColor(params[1], "4b") + local p2 = params[2] + local p2type = type(p2) + if p2type == "table" then + layer = cc.LayerGradient:create(color1, cc.convertColor(p2, "4b"), params[3]) + else + layer = cc.LayerColor:create(color1, p2, params[3]) + end + end + return layer +end + +function display.newSprite(source, x, y, params) + local spriteClass = cc.Sprite + local scale9 = false + + if type(x) == "table" and not x.x then + -- x is params + params = x + x = nil + y = nil + end + + local params = params or PARAMS_EMPTY + if params.scale9 or params.capInsets then + spriteClass = ccui.Scale9Sprite + scale9 = true + params.capInsets = params.capInsets or RECT_ZERO + params.rect = params.rect or RECT_ZERO + end + + local sprite + while true do + -- create sprite + if not source then + sprite = spriteClass:create() + break + end + + local sourceType = type(source) + if sourceType == "string" then + if string.byte(source) == 35 then -- first char is # + -- create sprite from spriteFrame + if not scale9 then + sprite = spriteClass:createWithSpriteFrameName(string.sub(source, 2)) + else + sprite = spriteClass:createWithSpriteFrameName(string.sub(source, 2), params.capInsets) + end + break + end + + -- create sprite from image file + if display.TEXTURES_PIXEL_FORMAT[source] then + cc.Texture2D:setDefaultAlphaPixelFormat(display.TEXTURES_PIXEL_FORMAT[source]) + end + if not scale9 then + sprite = spriteClass:create(source) + else + sprite = spriteClass:create(source, params.rect, params.capInsets) + end + if display.TEXTURES_PIXEL_FORMAT[source] then + cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2D_PIXEL_FORMAT_RGBA8888) + end + break + elseif sourceType ~= "userdata" then + error(string.format("display.newSprite() - invalid source type \"%s\"", sourceType), 0) + else + sourceType = tolua.type(source) + if sourceType == "cc.SpriteFrame" then + if not scale9 then + sprite = spriteClass:createWithSpriteFrame(source) + else + sprite = spriteClass:createWithSpriteFrame(source, params.capInsets) + end + elseif sourceType == "cc.Texture2D" then + sprite = spriteClass:createWithTexture(source) + else + error(string.format("display.newSprite() - invalid source type \"%s\"", sourceType), 0) + end + end + break + end + + if sprite then + if x and y then sprite:setPosition(x, y) end + if params.size then sprite:setContentSize(params.size) end + else + error(string.format("display.newSprite() - create sprite failure, source \"%s\"", tostring(source)), 0) + end + + return sprite +end + +function display.newSpriteFrame(source, ...) + local frame + if type(source) == "string" then + if string.byte(souce) == 35 then -- first char is # + souce = string.sub(souce, 2) + end + frame = spriteFrameCache:getSpriteFrame(souce) + if not frame then + error(string.format("display.newSpriteFrame() - invalid frame name \"%s\"", tostring(souce)), 0) + end + elseif tolua.type(source) == "cc.Texture2D" then + frame = cc.SpriteFrame:createWithTexture(source, ...) + else + error("display.newSpriteFrame() - invalid parameters", 0) + end + return frame +end + +function display.newFrames(pattern, begin, length, isReversed) + local frames = {} + local step = 1 + local last = begin + length - 1 + if isReversed then + last, begin = begin, last + step = -1 + end + + for index = begin, last, step do + local frameName = string.format(pattern, index) + local frame = spriteFrameCache:getSpriteFrame(frameName) + if not frame then + error(string.format("display.newFrames() - invalid frame name %s", tostring(frameName)), 0) + end + frames[#frames + 1] = frame + end + return frames +end + +local function newAnimation(frames, time) + local count = #frames + assert(count > 0, "display.newAnimation() - invalid frames") + time = time or 1.0 / count + return cc.Animation:createWithSpriteFrames(frames, time), + cc.Sprite:createWithSpriteFrame(frames[1]) +end + +function display.newAnimation(...) + local params = {...} + local c = #params + if c == 2 then + -- frames, time + return newAnimation(params[1], params[2]) + elseif c == 4 then + -- pattern, begin, length, time + local frames = display.newFrames(params[1], params[2], params[3]) + return newAnimation(frames, params[4]) + elseif c == 5 then + -- pattern, begin, length, isReversed, time + local frames = display.newFrames(params[1], params[2], params[3], params[4]) + return newAnimation(frames, params[5]) + else + error("display.newAnimation() - invalid parameters") + end +end + +function display.loadImage(imageFilename, callback) + if not callback then + return textureCache:addImage(imageFilename) + else + textureCache:addImageAsync(imageFilename, callback) + end +end + +local fileUtils = cc.FileUtils:getInstance() +function display.getImage(imageFilename) + local fullpath = fileUtils:fullPathForFilename(imageFilename) + return textureCache:getTextureForKey(fullpath) +end + +function display.removeImage(imageFilename) + textureCache:removeTextureForKey(imageFilename) +end + +function display.loadSpriteFrames(dataFilename, imageFilename, callback) + if display.TEXTURES_PIXEL_FORMAT[imageFilename] then + cc.Texture2D:setDefaultAlphaPixelFormat(display.TEXTURES_PIXEL_FORMAT[imageFilename]) + end + if not callback then + spriteFrameCache:addSpriteFrames(dataFilename, imageFilename) + else + spriteFrameCache:addSpriteFramesAsync(dataFilename, imageFilename, callback) + end + if display.TEXTURES_PIXEL_FORMAT[imageFilename] then + cc.Texture2D:setDefaultAlphaPixelFormat(cc.TEXTURE2D_PIXEL_FORMAT_RGBA8888) + end +end + +function display.removeSpriteFrames(dataFilename, imageFilename) + spriteFrameCache:removeSpriteFramesFromFile(dataFilename) + if imageFilename then + display.removeImage(imageFilename) + end +end + +function display.removeSpriteFrame(imageFilename) + spriteFrameCache:removeSpriteFrameByName(imageFilename) +end + +function display.setTexturePixelFormat(imageFilename, format) + display.TEXTURES_PIXEL_FORMAT[imageFilename] = format +end + +function display.setAnimationCache(name, animation) + animationCache:addAnimation(animation, name) +end + +function display.getAnimationCache(name) + return animationCache:getAnimation(name) +end + +function display.removeAnimationCache(name) + animationCache:removeAnimation(name) +end + +function display.removeUnusedSpriteFrames() + spriteFrameCache:removeUnusedSpriteFrames() + textureCache:removeUnusedTextures() +end + +return display diff --git a/cocos/scripting/lua-bindings/script/framework/extends/LayerEx.lua b/cocos/scripting/lua-bindings/script/framework/extends/LayerEx.lua new file mode 100644 index 0000000000..8f4375332d --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/extends/LayerEx.lua @@ -0,0 +1,56 @@ +--[[ + +Copyright (c) 2011-2014 chukong-inc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +local Layer = cc.Layer + +function Layer:enableTouch(callback, isMultiTouches, swallowTouches) + if type(isMultiTouches) ~= "boolean" then isMultiTouches = false end + if type(swallowTouches) ~= "boolean" then swallowTouches = false end + + self:registerScriptTouchHandler(function(state, ...) + local args = {...} + local event = {name = state} + if isMultiTouches then + args = args[1] + local points = {} + for i = 1, #args, 3 do + local x, y, id = args[i], args[i + 1], args[i + 2] + points[id] = {x = x, y = y, id = id} + end + event.points = points + else + event.x = args[1] + event.y = args[2] + end + callback(event) + end, isMultiTouches, 0, swallowTouches) + self:setTouchEnabled(true) + return self +end + +function Layer:disableTouch() + self:unregisterScriptTouchHandler() + self:setTouchEnabled(false) + return self +end diff --git a/cocos/scripting/lua-bindings/script/framework/extends/MenuEx.lua b/cocos/scripting/lua-bindings/script/framework/extends/MenuEx.lua new file mode 100644 index 0000000000..16393271e6 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/extends/MenuEx.lua @@ -0,0 +1,31 @@ +--[[ + +Copyright (c) 2011-2014 chukong-inc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +local Menu = cc.Menu +local MenuItem = cc.MenuItem + +function MenuItem:onClicked(callback) + self:registerScriptTapHandler(callback) + return self +end diff --git a/cocos/scripting/lua-bindings/script/framework/extends/NodeEx.lua b/cocos/scripting/lua-bindings/script/framework/extends/NodeEx.lua new file mode 100644 index 0000000000..edd31adb50 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/extends/NodeEx.lua @@ -0,0 +1,163 @@ +--[[ + +Copyright (c) 2011-2014 chukong-inc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +local Node = cc.Node + +function Node:add(child, zorder, tag) + if tag then + self:addChild(child, zorder, tag) + elseif zorder then + self:addChild(child, zorder) + else + self:addChild(child) + end + return self +end + +function Node:addTo(parent, zorder, tag) + if tag then + parent:addChild(self, zorder, tag) + elseif zorder then + parent:addChild(self, zorder) + else + parent:addChild(self) + end + return self +end + +function Node:removeSelf() + self:removeFromParent() + return self +end + +function Node:align(anchorPoint, x, y) + self:setAnchorPoint(anchorPoint) + return self:move(x, y) +end + +function Node:show() + self:setVisible(true) + return self +end + +function Node:hide() + self:setVisible(false) + return self +end + +function Node:move(x, y) + if y then + self:setPosition(x, y) + else + self:setPosition(x) + end + return self +end + +function Node:moveTo(args) + transition.moveTo(self, args) + return self +end + +function Node:moveBy(args) + transition.moveBy(self, args) + return self +end + +function Node:fadeIn(args) + transition.fadeIn(self, args) + return self +end + +function Node:fadeOut(args) + transition.fadeOut(self, args) + return self +end + +function Node:fadeTo(args) + transition.fadeTo(self, args) + return self +end + +function Node:rotate(rotation) + self:setRotation(rotation) + return self +end + +function Node:rotateTo(args) + transition.rotateTo(self, args) + return self +end + +function Node:rotateBy(args) + transition.rotateBy(self, args) + return self +end + +function Node:scaleTo(args) + transition.scaleTo(self, args) + return self +end + +function Node:scheduleUpdate(callback) + self:scheduleUpdateWithPriorityLua(callback, 0) + return self +end + +function Node:enableNodeEvents() + self:registerScriptHandler(function(state) + if state == "enter" then + self:onEnter() + elseif state == "exit" then + self:onExit() + elseif state == "enterTransitionFinish" then + self:onEnterTransitionFinish() + elseif state == "exitTransitionStart" then + self:onExitTransitionStart() + elseif state == "cleanup" then + self:onCleanup() + end + end) + return self +end + +function Node:disableNodeEvents() + self:unregisterScriptHandler() + return self +end + +function Node:onEnter() +end + +function Node:onExit() +end + +function Node:onEnterTransitionFinish() +end + +function Node:onExitTransitionStart() +end + +function Node:onCleanup() +end diff --git a/cocos/scripting/lua-bindings/script/framework/extends/SpriteEx.lua b/cocos/scripting/lua-bindings/script/framework/extends/SpriteEx.lua new file mode 100644 index 0000000000..642c8d97e7 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/extends/SpriteEx.lua @@ -0,0 +1,67 @@ +--[[ + +Copyright (c) 2011-2014 chukong-inc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +local Sprite = cc.Sprite + +function Sprite:playAnimationOnce(animation, args) + local actions = {} + + local showDelay = args.showDelay or 0 + if showDelay then + self:setVisible(false) + actions[#actions + 1] = cc.DelayTime:create(showDelay) + actions[#actions + 1] = cc.Show:create() + end + + local delay = args.delay or 0 + if delay > 0 then + actions[#actions + 1] = cc.DelayTime:create(delay) + end + + actions[#actions + 1] = cc.Animate:create(animation) + + if args.removeSelf then + actions[#actions + 1] = cc.RemoveSelf:create() + end + + if onComplete then + actions[#actions + 1] = cc.CallFunc:create(onComplete) + end + + local action + if #actions > 1 then + action = cc.Sequence:create(actions) + else + action = actions[1] + end + self:runAction(action) + return action +end + +function Sprite:playAnimationForever(animation) + local animate = cc.Animate:create(animation) + local action = cc.RepeatForever:create(animate) + self:runAction(action) + return action +end diff --git a/cocos/scripting/lua-bindings/script/framework/init.lua b/cocos/scripting/lua-bindings/script/framework/init.lua new file mode 100644 index 0000000000..fc721f668e --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/init.lua @@ -0,0 +1,77 @@ +--[[ + +Copyright (c) 2011-2015 chukong-incc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +__G__TRACKBACK__ = function(msg) + local msg = debug.traceback(msg, 3) + print(msg) + return msg +end + +if type(DEBUG) ~= "number" then DEBUG = 0 end + +-- load framework +printInfo("") +printInfo("# DEBUG = " .. DEBUG) +printInfo("#") + +device = require("cocos.framework.device") +display = require("cocos.framework.display") +audio = require("cocos.framework.audio") +transition = require("cocos.framework.transition") + +require("cocos.framework.extends.NodeEx") +require("cocos.framework.extends.SpriteEx") +require("cocos.framework.extends.LayerEx") +require("cocos.framework.extends.MenuEx") + +require("cocos.framework.package_support") + +-- register the build-in packages +cc.register("event", require("cocos.framework.components.event")) + +-- export global variable +local __g = _G +cc.exports = {} +setmetatable(cc.exports, { + __newindex = function(_, name, value) + rawset(__g, name, value) + end, + + __index = function(_, name) + return rawget(__g, name) + end +}) + +-- disable create unexpected global variable +function cc.disable_global() + setmetatable(__g, { + __newindex = function(_, name, value) + error(string.format("USE \" cc.exports.%s = value \" INSTEAD OF SET GLOBAL VARIABLE", name), 0) + end + }) +end + +if CC_DISABLE_GLOBAL then + cc.disable_global() +end diff --git a/cocos/scripting/lua-bindings/script/framework/package_support.lua b/cocos/scripting/lua-bindings/script/framework/package_support.lua new file mode 100644 index 0000000000..e5c5e14de2 --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/package_support.lua @@ -0,0 +1,113 @@ +--[[ + +Copyright (c) 2011-2015 chukong-incc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +-- Cocos2d-Lua core functions +cc.loaded_packages = {} +local loaded_packages = cc.loaded_packages + +function cc.register(name, package) + cc.loaded_packages[name] = package +end + +function cc.load(...) + local names = {...} + assert(#names > 0, "cc.load() - invalid package names") + + local packages = {} + for _, name in ipairs(names) do + assert(type(name) == "string", string.format("cc.load() - invalid package name \"%s\"", tostring(name))) + if not loaded_packages[name] then + local packageName = string.format("packages.%s.init", name) + local cls = require(packageName) + assert(cls, string.format("cc.load() - package class \"%s\" load failed", packageName)) + loaded_packages[name] = cls + + if DEBUG > 1 then + printInfo("cc.load() - load module \"packages.%s.init\"", name) + end + end + packages[#packages + 1] = loaded_packages[name] + end + return unpack(packages) +end + +local load_ = cc.load +local bind_ +bind_ = function(target, ...) + local t = type(target) + assert(t == "table" or t == "userdata", string.format("cc.bind() - invalid target, expected is object, actual is %s", t)) + local names = {...} + assert(#names > 0, "cc.bind() - package names expected") + + load_(...) + if not target.components_ then target.components_ = {} end + for _, name in ipairs(names) do + assert(type(name) == "string" and name ~= "", string.format("cc.bind() - invalid package name \"%s\"", name)) + if not target.components_[name] then + local cls = loaded_packages[name] + for __, depend in ipairs(cls.depends or {}) do + if not target.components_[depend] then + bind_(target, depend) + end + end + local component = cls:create() + target.components_[name] = component + component:bind(target) + end + end + + return target +end +cc.bind = bind_ + +function cc.unbind(target, ...) + if not target.components_ then return end + + local names = {...} + assert(#names > 0, "cc.unbind() - invalid package names") + + for _, name in ipairs(names) do + assert(type(name) == "string" and name ~= "", string.format("cc.unbind() - invalid package name \"%s\"", name)) + local component = target.components_[name] + assert(component, string.format("cc.unbind() - component \"%s\" not found", tostring(name))) + component:unbind(target) + target.components_[name] = nil + end + return target +end + +function cc.setmethods(target, component, methods) + for _, name in ipairs(methods) do + local method = component[name] + target[name] = function(__, ...) + return method(component, ...) + end + end +end + +function cc.unsetmethods(target, methods) + for _, name in ipairs(methods) do + target[name] = nil + end +end diff --git a/cocos/scripting/lua-bindings/script/framework/transition.lua b/cocos/scripting/lua-bindings/script/framework/transition.lua new file mode 100644 index 0000000000..78c441266d --- /dev/null +++ b/cocos/scripting/lua-bindings/script/framework/transition.lua @@ -0,0 +1,213 @@ +--[[ + +Copyright (c) 2011-2014 chukong-inc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] + +local transition = {} + +local ACTION_EASING = {} +ACTION_EASING["BACKIN"] = {cc.EaseBackIn, 1} +ACTION_EASING["BACKINOUT"] = {cc.EaseBackInOut, 1} +ACTION_EASING["BACKOUT"] = {cc.EaseBackOut, 1} +ACTION_EASING["BOUNCE"] = {cc.EaseBounce, 1} +ACTION_EASING["BOUNCEIN"] = {cc.EaseBounceIn, 1} +ACTION_EASING["BOUNCEINOUT"] = {cc.EaseBounceInOut, 1} +ACTION_EASING["BOUNCEOUT"] = {cc.EaseBounceOut, 1} +ACTION_EASING["ELASTIC"] = {cc.EaseElastic, 2, 0.3} +ACTION_EASING["ELASTICIN"] = {cc.EaseElasticIn, 2, 0.3} +ACTION_EASING["ELASTICINOUT"] = {cc.EaseElasticInOut, 2, 0.3} +ACTION_EASING["ELASTICOUT"] = {cc.EaseElasticOut, 2, 0.3} +ACTION_EASING["EXPONENTIALIN"] = {cc.EaseExponentialIn, 1} +ACTION_EASING["EXPONENTIALINOUT"] = {cc.EaseExponentialInOut, 1} +ACTION_EASING["EXPONENTIALOUT"] = {cc.EaseExponentialOut, 1} +ACTION_EASING["IN"] = {cc.EaseIn, 2, 1} +ACTION_EASING["INOUT"] = {cc.EaseInOut, 2, 1} +ACTION_EASING["OUT"] = {cc.EaseOut, 2, 1} +ACTION_EASING["RATEACTION"] = {cc.EaseRateAction, 2, 1} +ACTION_EASING["SINEIN"] = {cc.EaseSineIn, 1} +ACTION_EASING["SINEINOUT"] = {cc.EaseSineInOut, 1} +ACTION_EASING["SINEOUT"] = {cc.EaseSineOut, 1} + +local actionManager = cc.Director:getInstance():getActionManager() + +function transition.newEasing(action, easingName, more) + local key = string.upper(tostring(easingName)) + local easing + if ACTION_EASING[key] then + local cls, count, default = unpack(ACTION_EASING[key]) + if count == 2 then + easing = cls:create(action, more or default) + else + easing = cls:create(action) + end + end + return easing or action +end + +function transition.create(action, args) + args = checktable(args) + if args.easing then + if type(args.easing) == "table" then + action = transition.newEasing(action, unpack(args.easing)) + else + action = transition.newEasing(action, args.easing) + end + end + + local actions = {} + local delay = checknumber(args.delay) + if delay > 0 then + actions[#actions + 1] = cc.DelayTime:create(delay) + end + actions[#actions + 1] = action + + local onComplete = args.onComplete + if type(onComplete) ~= "function" then onComplete = nil end + if onComplete then + actions[#actions + 1] = cc.CallFunc:create(onComplete) + end + + if args.removeSelf then + actions[#actions + 1] = cc.RemoveSelf:create() + end + + if #actions > 1 then + return transition.sequence(actions) + else + return actions[1] + end +end + +function transition.execute(target, action, args) + assert(not tolua.isnull(target), "transition.execute() - target is not cc.Node") + local action = transition.create(action, args) + target:runAction(action) + return action +end + +function transition.moveTo(target, args) + assert(not tolua.isnull(target), "transition.moveTo() - target is not cc.Node") + local x = args.x or target:getPositionX() + local y = args.y or target:getPositionY() + local action = cc.MoveTo:create(args.time, cc.p(x, y)) + return transition.execute(target, action, args) +end + +function transition.moveBy(target, args) + assert(not tolua.isnull(target), "transition.moveBy() - target is not cc.Node") + local x = args.x or 0 + local y = args.y or 0 + local action = cc.MoveBy:create(args.time, cc.p(x, y)) + return transition.execute(target, action, args) +end + +function transition.fadeIn(target, args) + assert(not tolua.isnull(target), "transition.fadeIn() - target is not cc.Node") + local action = cc.FadeIn:create(args.time) + return transition.execute(target, action, args) +end + +function transition.fadeOut(target, args) + assert(not tolua.isnull(target), "transition.fadeOut() - target is not cc.Node") + local action = cc.FadeOut:create(args.time) + return transition.execute(target, action, args) +end + +function transition.fadeTo(target, args) + assert(not tolua.isnull(target), "transition.fadeTo() - target is not cc.Node") + local opacity = checkint(args.opacity) + if opacity < 0 then + opacity = 0 + elseif opacity > 255 then + opacity = 255 + end + local action = cc.FadeTo:create(args.time, opacity) + return transition.execute(target, action, args) +end + +function transition.scaleTo(target, args) + assert(not tolua.isnull(target), "transition.scaleTo() - target is not cc.Node") + local action + if args.scale then + action = cc.ScaleTo:create(checknumber(args.time), checknumber(args.scale)) + elseif args.scaleX or args.scaleY then + local scaleX, scaleY + if args.scaleX then + scaleX = checknumber(args.scaleX) + else + scaleX = target:getScaleX() + end + if args.scaleY then + scaleY = checknumber(args.scaleY) + else + scaleY = target:getScaleY() + end + action = cc.ScaleTo:create(checknumber(args.time), scaleX, scaleY) + end + return transition.execute(target, action, args) +end + +function transition.rotateTo(target, args) + assert(not tolua.isnull(target), "transition.rotateTo() - target is not cc.Node") + local rotation = args.rotation or target:getRotation() + local action = cc.RotateTo:create(args.time, rotation) + return transition.execute(target, action, args) +end + +function transition.rotateBy(target, args) + assert(not tolua.isnull(target), "transition.rotateTo() - target is not cc.Node") + local rotation = args.rotation or 0 + local action = cc.RotateBy:create(args.time, rotation) + return transition.execute(target, action, args) +end + +function transition.sequence(actions) + if #actions < 1 then return end + if #actions < 2 then return actions[1] end + return cc.Sequence:create(actions) +end + +function transition.removeAction(action) + if not tolua.isnull(action) then + actionManager:removeAction(action) + end +end + +function transition.stopTarget(target) + if not tolua.isnull(target) then + actionManager:removeAllActionsFromTarget(target) + end +end + +function transition.pauseTarget(target) + if not tolua.isnull(target) then + actionManager:pauseTarget(target) + end +end + +function transition.resumeTarget(target) + if not tolua.isnull(target) then + actionManager:resumeTarget(target) + end +end + +return transition diff --git a/cocos/scripting/lua-bindings/script/init.lua b/cocos/scripting/lua-bindings/script/init.lua index 3307f40bc0..81a44fa38b 100644 --- a/cocos/scripting/lua-bindings/script/init.lua +++ b/cocos/scripting/lua-bindings/script/init.lua @@ -1,37 +1,57 @@ +--[[ + +Copyright (c) 2011-2015 chukong-incc.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +]] require "cocos.cocos2d.Cocos2d" require "cocos.cocos2d.Cocos2dConstants" -require "cocos.cocos2d.extern" -require "cocos.cocos2d.bitExtend" -require "cocos.cocos2d.DrawPrimitives" +require "cocos.cocos2d.functions" --- opengl -require "cocos.cocos2d.Opengl" -require "cocos.cocos2d.OpenglConstants" +if CC_USE_FRAMEWORK then + require "cocos.framework.init" +else + -- opengl + require "cocos.cocos2d.Opengl" + require "cocos.cocos2d.OpenglConstants" + -- audio + require "cocos.cocosdenshion.AudioEngine" + -- cocosstudio + require "cocos.cocostudio.CocoStudio" + -- ui + require "cocos.ui.GuiConstants" + require "cocos.ui.experimentalUIConstants" + -- extensions + require "cocos.extension.ExtensionConstants" + -- network + require "cocos.network.NetworkConstants" + -- Spine + require "cocos.spine.SpineConstants" --- cocosbuilder -require "cocos.cocosbuilder.CCBReaderLoad" + require "cocos.deprecated" + require "cocos.cocos2d.DrawPrimitives" --- cocosdenshion -require "cocos.cocosdenshion.AudioEngine" + -- Lua extensions + require "cocos.cocos2d.bitExtend" --- cocosstudio -require "cocos.cocostudio.CocoStudio" - --- ui -require "cocos.ui.GuiConstants" -require "cocos.ui.experimentalUIConstants" - --- extensions -require "cocos.extension.ExtensionConstants" - --- network -require "cocos.network.NetworkConstants" - --- Spine -require "cocos.spine.SpineConstants" - -if CC_USE_DEPRECATED_API then -- CCLuaEngine require "cocos.cocos2d.DeprecatedCocos2dClass" require "cocos.cocos2d.DeprecatedCocos2dEnum" @@ -62,4 +82,7 @@ if CC_USE_DEPRECATED_API then -- register_ui_moudle require "cocos.ui.DeprecatedUIEnum" require "cocos.ui.DeprecatedUIFunc" + + -- cocosbuilder + require "cocos.cocosbuilder.CCBReaderLoad" end