let fs = require('fs'); let util = require('util'); let os = require('os'); let crypto = require('crypto'); let nodePath = require('path'); var grunt = require("grunt"); let fileHelp = require('./tools/fileHelp'); let CONST = { //系统路径设置 TEXTURE_PACKER_ROOT_WIN: 'TexturePacker', TEXTURE_PACKER_ROOT_MAC: 'TexturePacker', // CREATOR_PATH_WIN: 'engine\\win\\CocosCreator_2.1.1\\CocosCreator.exe', CREATOR_PATH_WIN: 'CocosCreator222.exe', CREATOR_PATH_MAC: './engine/mac/CocosCreator.app/Contents/MacOS/CocosCreator', //编译目录 BUILD_DEFAULT_DIR: 'build', BUILD_NATIVE_DIR: 'build_native', //png压缩率 PNG_QUALITY_MIN: 30, PNG_QUALITY_MAX: 60, //忽略压缩的文件 IGNORE_IMG_NAMES: ['ui.png'], //音频压缩临时文件前缀 TMP_AUDIO_HEAD:'_tmp_ad_', //图片加密标识 PNG_KEY: 'Top1Studio', //图片加密密钥 PNG_KEYS: [ 0x18, 0xD4, 0x56, 0x11, 0xD4, 0x34, 0x18, 0x22, 0x41, 0x31, 0xD1, 0x33 ] }; let Global = { ignorePng8Files : {}, realIgnorePng8Files : {}, fbPath: './' + CONST.BUILD_DEFAULT_DIR + '/fb-instant-games/', nativeResPath : './' + CONST.BUILD_NATIVE_DIR + '/jsb-default/res/' }; /** * 递归文件 * @param path 文件夹路径 * @param handleFile 回调,只有文件时才执行 */ function walk(path, handleFile) { // console.log('path = ' + path); let files = fs.readdirSync(path); files.forEach(function (item) { if (item.indexOf('.DS_Store') >= 0) { } else { let tmpPath = path + '/' + item; // console.log('tmpPath = ' + tmpPath); if (fs.statSync(tmpPath).isDirectory()) { walk(tmpPath, handleFile); } else { handleFile(path, item); } } }); } /** * 递归文件夹 * @param path 文件夹路径 * @param handleFile 回调方法,只有文件夹才回调 */ function walkDir(path, handleFile) { let files = fs.readdirSync(path); files.forEach(function (item) { if (item.indexOf('.DS_Store') >= 0) { } else { let tmpPath = path + '/' + item; if (fs.statSync(tmpPath).isDirectory()) { handleFile(path, item); walkDir(tmpPath, handleFile); } } }); } function pngEncode(input, output) { let keyLen = CONST.PNG_KEY.length; let keys = CONST.PNG_KEYS; let _buffer_input = grunt.file.read(input, {encoding: "Binary"}); //return a Buffer let _buffer = Buffer.from(_buffer_input, "Binary"); let _buffer_output = Buffer.alloc(_buffer_input.length + keyLen); _buffer_output.write(CONST.PNG_KEY); for(let i = 0; i < _buffer.length; i++){ _buffer_output[keyLen + i] = _buffer[i]; //加密 if(i < keys.length){ _buffer_output[keyLen + i] = _buffer[i] ^ keys[i]; } } grunt.file.write(output, _buffer_output, {encoding: "Binary"}); } function pngDecode(input,output){ let _buffer_input = grunt.file.read(input, {encoding: "Binary"}); //return a Buffer let _buffer_output = Buffer.from(_buffer_input, "Binary"); grunt.file.write(output, _buffer_output, {encoding: "Binary"}); } /** * 操作系统类型,返回值有'darwin', 'freebsd', 'linux', 'sunos' , 'win32' * @returns {boolean} */ let isWindows = function () { return os.platform() === 'win32'; }; let isMac = function () { return os.platform() === 'darwin'; }; let getMd5 = function(data){ let md5 = crypto.createHash('md5').update(data, 'utf-8').digest('hex'); return md5; }; let getFileMd5 = function(filePath){ if(!fs.existsSync(filePath)){ error('getFileMd5 error') } let data = fs.readFileSync(filePath,'utf-8'); return getMd5(data); }; module.exports = function (grunt) { grunt.loadNpmTasks('grunt-shell'); // Project configuration. grunt.initConfig({ shell: { options: { stderr: true, stdout: true, execOptions: { maxBuffer: Infinity } }, cmd: { command: function (file, arg0, arg1, arg2, arg3) { let _ret = '$1 '.replace('$1', file); for (let i = 1; i < arguments.length; i++) { _ret += " " + arguments[i]; } grunt.log.debug("run cmd:" + _ret); return _ret; } }, // apk: { command: function (file) { let _param = file == 'debug' ? 'assembleDebug' : 'assembleRelease'; if (isWindows()) { return util.format( "cd "+CONST.BUILD_NATIVE_DIR+"\\jsb-default\\frameworks\\runtime-src\\proj.android-studio && gradlew.bat %s", _param ) } else { return util.format( "cd ./"+CONST.BUILD_NATIVE_DIR+"/jsb-default/frameworks/runtime-src/proj.android-studio && ./gradlew %s", _param ) } } }, //安卓发布bundle bundle: { command: function (file) { let _param = file == 'debug' ? 'bundleDebug' : 'bundleRelease'; if (isWindows()) { return util.format( "cd "+CONST.BUILD_NATIVE_DIR+"\\jsb-default\\frameworks\\runtime-src\\proj.android-studio && gradlew.bat %s", _param ) } else { return util.format( "cd ./"+CONST.BUILD_NATIVE_DIR+"/jsb-default/frameworks/runtime-src/proj.android-studio && ./gradlew %s", _param ) } } }, //图片压缩 pngquant: { command: function (file) { let PNG_QUALITY_MIN = '--quality=' + CONST.PNG_QUALITY_MIN + '-' + CONST.PNG_QUALITY_MAX; if (isWindows()) { return util.format( "tools\\pngquant\\windows\\pngquant.exe --speed 1 " + PNG_QUALITY_MIN + " --force %s --ext .png", file ) } else { return util.format( "./tools/pngquant/mac/pngquant --speed 1 " + PNG_QUALITY_MIN + " --force %s --ext .png", file ) } } }, minjs: { command: function () { if (isWindows()) { return util.format( "tools\\min\\min.bat" ) } else { return util.format( "tools\\min\\min.bat" ) } } }, //音频压缩 ffmpeg: { command: function (file, outputFile) { if(isWindows()){ return util.format( "tools\\ffmpeg\\windows\\bin\\ffmpeg.exe -i %s -ac 1 -ab 60k %s -y", file, outputFile ) } else { return util.format( "./tools/ffmpeg/mac/ffmpeg -i %s -ac 1 -ab 60k %s -y", file, outputFile ) } } }, //zip zip: { command: function (file_name, file_dir) { if(isWindows()){ return util.format( 'tools\\zip\\7z.exe a %s %s', CONST.BUILD_DEFAULT_DIR + '\\' + file_name, file_dir ) } else{ return util.format( 'cd %s && zip -r %s %s', file_dir, file_name, './' ) } } }, //加密 jm: { command: function () { if(isWindows()){ return 'jm.bat'; } } }, //texture packer 自动合图 build_img: { command: function (spriteFrameDirPath, spriteSheetPath) { let head = ''; if (isMac()) { head = CONST.TEXTURE_PACKER_ROOT_MAC + ' ' } else { head = CONST.TEXTURE_PACKER_ROOT_WIN + ' ' } return util.format( head + '--smart-update ' + '%s ' + '--texture-format png ' + '--format cocos2d-x ' + '--data %s.plist ' + '--sheet %s.png ' + '--maxrects-heuristics best ' + '--scale 1 ' + '--shape-padding 2 ' + '--size-constraints WordAligned ' + '--max-size 2048 ' + '--trim ' // + '--force-squared ' + '--opt RGBA8888 ', spriteFrameDirPath, spriteSheetPath, spriteSheetPath ) }.bind(this) } } }); /** * FB打包 */ grunt.registerTask('export-fb', function (debug) { debug = debug || 'false'; grunt.task.run('build-fb:' + debug); grunt.task.run('png8-fb'); grunt.task.run('ffmpeg-fb'); grunt.task.run('shell:jm'); grunt.task.run('concat-fb-js'); // grunt.task.run('delete-fb-zip'); // grunt.task.run('zip-fb'); }); grunt.registerTask('change-gamejs-name', function(v){ console.log('\n开始修改引用的js'); var path = fs.realpathSync('.') + "/build/fb-instant-games/index.html"; var Content = fs.readFileSync(path,'utf-8').replace(/game.min.*.js/, v).replace(/game.min.js/, v); fs.writeFileSync(path,Content,"utf-8"); }); grunt.registerTask('concat-fb-js', function(){ console.log('合并导出的js'); let paths = []; walk('build/fb-instant-games', function (path, item) { let tmpPath = path + '/' + item; //console.log('item = ', item); if (item.indexOf('settings.') >= 0 && item.indexOf('.js') >= 0){ paths[0] = tmpPath; }else if(item.indexOf('cocos2d-js-min.') >= 0 && item.indexOf('.js') >= 0){ paths[1] = tmpPath; }else if(item.indexOf('project.') >= 0 && item.indexOf('.js') >= 0){ paths[2] = tmpPath; }else if(item.indexOf('main.') >= 0 && item.indexOf('.js') >= 0){ paths[3] = tmpPath; }else if(item.indexOf('game.min.') >= 0 && item.indexOf('.js') >= 0){ fs.unlinkSync(tmpPath); } }.bind(this)); let content = ""; for(let i = 0, len = paths.length; i < len; ++i){ console.log('path = ', paths[i]); let _filejs = fs.readFileSync(paths[i],'utf-8') content += _filejs; } let now = new Date(); let new_name = 'game.min.' + now.getTime() + '.js'; let targetfile = './build/fb-instant-games/' + new_name; fs.writeFileSync(targetfile,content,"utf-8"); grunt.task.run(util.format( "change-gamejs-name:%s", new_name )); }); grunt.registerTask('min-fb-js', function(){ grunt.task.run( util.format( "shell:minjs" ) ) }); grunt.registerTask('delete-fb-zip', function(){ let zips = './build/fb-instant-games/AvoidRedDots.zip'; if (fs.existsSync(zips)) { fs.unlinkSync(zips); } }); /** * FB编译 */ grunt.registerTask('build-fb', function (_debug) { let debug = _debug;//待处理 let cmd = ''; let path = '' + __dirname; if (isWindows()) { cmd = CONST.CREATOR_PATH_WIN; } else { cmd = CONST.CREATOR_PATH_MAC; } console.log('debug: ' + debug); let keyStr = '"'; keyStr += ';platform=fb-instant-games'; keyStr += ';buildPath=' + CONST.BUILD_DEFAULT_DIR; keyStr += ';debug=' + debug; keyStr += ';sourceMaps=' + debug; keyStr += ';embedWebDebugger=' + debug; keyStr += ';md5Cache=true'; keyStr += '"'; console.log('keyStr: ' + keyStr); cmd += ' --path ' + path + ' --build ' + keyStr; grunt.task.run('shell:cmd:' + cmd); }); /** * FB压缩zip */ grunt.registerTask('zip-fb', function () { let origin_zip_path = './build/fb-instant-games.zip'; if (fs.existsSync(origin_zip_path)) { console.log('删除 ' + origin_zip_path); fs.unlinkSync(origin_zip_path); } //拷贝json // let json_config = './template/fbapp-config.json'; // fileHelp.copyFile(json_config, './build/fb-instant-games/fbapp-config.json'); let file_name = 'fb-instant-games.zip'; let file_path = './build/fb-instant-games/*'; grunt.task.run( util.format( "shell:zip:%s:%s", file_name, file_path ) ); }); grunt.registerTask('moveZip', function () { let output_file = 'fb-instant-games.zip'; if (fs.existsSync(output_file)) { console.log('移动 ' + output_file); fileHelp.moveFile('./' + output_file, './build/fb-instant-games/' + output_file) } }); /** * 导出安卓 */ grunt.registerTask('export-android', function () { grunt.task.run('build-android'); grunt.task.run('png8-native'); grunt.task.run('png-encode'); grunt.task.run('ffmpeg-native'); grunt.task.run('export-apk'); }); grunt.registerTask('export-android-bundle', function () { grunt.task.run('build-android'); grunt.task.run('png8-native'); grunt.task.run('png-encode'); grunt.task.run('ffmpeg-native'); grunt.task.run('export-bundle'); }); /** * 打安卓包apk */ grunt.registerTask('export-apk', function () { grunt.task.run( util.format("shell:apk") ); }); grunt.registerTask('export-bundle', function () { grunt.task.run( util.format("shell:bundle") ); }); /** * 导出ios */ grunt.registerTask('export-ios', function () { grunt.task.run('build-ios'); grunt.task.run('png8-native'); grunt.task.run('png-encode'); grunt.task.run('ffmpeg-native'); }); /** * 编译android */ grunt.registerTask('build-android', function () { grunt.task.run('build-native:android'); }); /** * 编译ios */ grunt.registerTask('build-ios', function () { grunt.task.run('build-native:ios'); }); /** * 编译native */ grunt.registerTask('build-native', function (platform) { let debug = false;//待处理 let cmd = isWindows() ? CONST.CREATOR_PATH_WIN : CONST.CREATOR_PATH_MAC; let path = '' + __dirname; let keyStr = 'platform=' + platform; keyStr += ';buildPath=' + CONST.BUILD_NATIVE_DIR; keyStr += ';debug=' + debug; keyStr += ';sourceMaps=' + debug; keyStr += ';embedWebDebugger=' + debug; keyStr += ';md5Cache=' + !debug; keyStr += ';template=default'; //native 平台下的模板选项 [default、link] cmd += ' --path ' + path + ' --build ' + keyStr; console.log('cmd = ' + cmd); grunt.task.run('shell:cmd:' + cmd); }); /** * 遍历assets_dev目录,对其下面的散图文件夹使用TexturePacker打包成图集,并自动拷贝到assets对应目录 */ grunt.registerTask('build-img', function () { walkDir('assets_dev', function (path, item) { let tmpPath = path + '/' + item; let isNeedBuild = true; let files = fs.readdirSync(tmpPath); for (let i = 0; i < files.length; i++) { if (files[i].indexOf('.DS_Store') >= 0) { continue; } if (files[i].indexOf('.png') < 0) { console.log('文件夹包含非png文件, 跳过合图! ' + files[i]); isNeedBuild = false; break; } } if (isNeedBuild) { console.log('需要转换' + tmpPath); let framesPath = tmpPath; let sheetsPath = tmpPath.replace('_dev', ''); console.log('framesPath = ' + framesPath); console.log('sheetsPath = ' + sheetsPath); //检查并创建路径文件夹 fileHelp.checkAndCreateDir(path); grunt.task.run( util.format( "shell:build_img:%s:%s", framesPath, sheetsPath ) ); } }.bind(this)); }); /** * 遍历assets_dev目录,对目录下所有的mp3文件转码压缩 */ grunt.registerTask('build-audio', "mp3转码", function () { walk('assets_dev', function (path, item) { let tmpPath = path + '/' + item; console.log('item ' + item); if (item.indexOf('.mp3') >= 0) { console.log('path = ' + path); fileHelp.checkAndCreateDir(path); let originPath = tmpPath; let outPath = tmpPath.replace('_dev', ''); if (fs.existsSync(outPath)) { fileHelp.deleteFile(outPath); } grunt.task.run( util.format( "shell:ffmpeg:%s:%s", originPath, outPath ) ) } }.bind(this)); }); //获取忽略文件md5列表,扫描assets目录 let getIgnoreImgList = function(){ let imgFileList = {}; walk('assets', function (path, item) { let tmpFilePath = path + '/' + item; if (nodePath.extname(item) === '.png') { for(let i = 0; i < CONST.IGNORE_IMG_NAMES.length; i++){ if(item === CONST.IGNORE_IMG_NAMES[i]){ // if(item.indexOf(CONST.IGNORE_IMG_NAMES[i]) >= 0){ let md5 = getFileMd5(tmpFilePath); imgFileList[md5] = tmpFilePath; } } } }); return imgFileList; }; /** * 对facebook文件夹下的图片进行压缩 */ grunt.registerTask('png8-fb', function () { grunt.task.run('png8Dir:' + Global.fbPath); }); /** * 对web文件夹下的图片进行压缩 */ grunt.registerTask('png8-web', function () { let fbPath = './' + CONST.BUILD_DEFAULT_DIR + '/web-desktop/'; grunt.task.run('png8Dir:' + fbPath); }); /** * 对native文件夹下的图片进行压缩 */ grunt.registerTask('png8-native',function(){ grunt.task.run('png8Dir:' + Global.nativeResPath); }); //遍历文件夹压缩图片 grunt.registerTask('png8Dir',function(path){ if(!path){ console.log('png8Dir 需传递path路径'); return; } let ignoreImgList = getIgnoreImgList(); console.log('\n开始执行图片压缩...'); console.log('预计跳过图片:\n' , ignoreImgList); walk(path, function (path, item) { if (nodePath.extname(item) === '.png') { let tmpFilePath = path + '/' + item; let md5 = getFileMd5(tmpFilePath); if(ignoreImgList[md5]){ Global.realIgnorePng8Files[md5] = ignoreImgList[md5]; } else{ grunt.task.run( util.format( "shell:pngquant:%s", path + '/' + item ) ) } } }); grunt.task.run('logPng8Result'); }); //输出图片压缩结果 grunt.registerTask('logPng8Result',function(){ console.log('\n'); console.log('图片压缩完成'); console.log('跳过图片:\n',Global.realIgnorePng8Files); }); /** * 图片加密 */ grunt.registerTask('png-encode',function(){ // let pngPath = 'assets/resources/texture/battle2.png'; // pngDecode(pngPath, 'assets/resources/texture/battle3.png'); // // return; walk(Global.nativeResPath, function (path, item) { if (nodePath.extname(item) === '.png') { let tmpFilePath = path + '/' + item; pngEncode(tmpFilePath,tmpFilePath) } }); }); /** * 对fb文件夹下的音效进行压缩 */ grunt.registerTask('ffmpeg-fb', function () { // grunt.task.run('ffmpegDir:./test/'); grunt.task.run('ffmpegDir:' + Global.fbPath); }); /** * 对native文件夹下的音效进行压缩 */ grunt.registerTask('ffmpeg-native', function () { grunt.task.run('ffmpegDir:' + Global.nativeResPath); }); //遍历文件夹压缩音频 grunt.registerTask('ffmpegDir',function(path){ if(!path){ console.log('ffmpegDir 需传递path路径'); return; } let ignoreImgList = getIgnoreImgList(); console.log('\n开始执行音频压缩...'); walk(path, function (path, item) { if (nodePath.extname(item) === '.wav' || nodePath.extname(item) === '.mp3') { let tmpFilePath = path + '/' + item; let tmpFilePathWithHead = path + '/' + CONST.TMP_AUDIO_HEAD + item; let md5 = getFileMd5(tmpFilePath); //压缩音频,以CONST.TMP_AUDIO_HEAD输出 grunt.task.run( util.format("shell:ffmpeg:%s:%s", tmpFilePath, tmpFilePathWithHead) ); //删除源文件,重命名输出后的文件 grunt.task.run( "rnameFile:" + tmpFilePathWithHead + ":" + tmpFilePath ) } }); }); /** * 重命名文件 */ grunt.registerTask('rnameFile',function(from,to){ if (fs.existsSync(to)) { console.log('删除 ' + to); fs.unlinkSync(to); } console.log('重命名:' + from + ' -> ' + to); fs.renameSync(from,to,function(){ console.log('done !') }); }); };