Best JavaScript code snippet using redwood
YEP_X_AttachAugments.js
Source:YEP_X_AttachAugments.js
1//=============================================================================2// Yanfly Engine Plugins - Item Core Extension - Attachable Augments3// YEP_X_AttachAugments.js4//=============================================================================5var Imported = Imported || {};6Imported.YEP_X_AttachAugments = true;7var Yanfly = Yanfly || {};8Yanfly.Augment = Yanfly.Augment || {};9Yanfly.Augment.version = 1.10;10//=============================================================================11 /*:12 * @plugindesc v1.10 (Requires YEP_ItemCore.js) Players can attach and13 * detach augments to independent equipment.14 * @author Yanfly Engine Plugins15 *16 * @param ---Default---17 * @default18 *19 * @param Weapon Slots20 * @parent ---Default---21 * @desc The default augment slots your weapon uses.22 * Separate each slot with a comma.23 * @default Glyph, Mark, Orb, Orb24 *25 * @param Armor Slots26 * @parent ---Default---27 * @desc The default augment slots your weapon uses.28 * Separate each slot with a comma.29 * @default Sphere, Orb, Orb, Orb30 *31 * @param Enable Augments32 * @parent ---Default---33 * @type boolean34 * @on Enable35 * @off Disable36 * @desc Enable augments by default at game start in action window?37 * NO - false YES - true38 * @default true39 *40 * @param Show Augments41 * @parent ---Default---42 * @type boolean43 * @on Show44 * @off Hide45 * @desc Show augments by default at game start in info window?46 * NO - false YES - true47 * @default true48 *49 * @param ---Command Window---50 * @default51 *52 * @param Augment Slot Format53 * @parent ---Command Window---54 * @desc This is how the augment slots will appear:55 * %1 - Slot Name %2 - Equipment Name56 * @default \c[16]%1:\c[0] %257 *58 * @param No Augment Text59 * @parent ---Command Window---60 * @desc This is how a slot appears if it has no augments.61 * @default \c[7]- None -62 *63 * @param Remove Augment64 * @parent ---Command Window---65 * @desc Text used to remove augments from item.66 * @default \i[16]Detach Augment67 *68 * @param ---Info Window---69 * @default70 *71 * @param Show Augment Info72 * @parent ---Info Window---73 * @type boolean74 * @on Show75 * @off Hide76 * @desc Show Augments in the info window?77 * NO - false YES - true78 * @default true79 *80 * @param Info Title81 * @parent ---Info Window---82 * @desc Text used to display augments.83 * @default Augments84 *85 * @param Title Alignment86 * @parent ---Info Window---87 * @type combo88 * @option left89 * @option center90 * @option right91 * @desc What alignment do you want to use for the title?92 * left center right93 * @default center94 *95 * @help96 * ============================================================================97 * Introduction98 * ============================================================================99 *100 * This plugin requires YEP_ItemCore.101 * Make sure this plugin is located under YEP_ItemCore in the plugin list.102 *103 * Attachable Augments is an extension plugin made for the Item Core plugin. It104 * allows equipment to be able to attach augment components to various slots,105 * that you can define individually per item. These slots can be of a certain106 * category unique to that item or global across all items. The effects used107 * with the augment can involve parameter changes, adding skills, adjust state108 * resistances, place attack elements, and more!109 *110 * ============================================================================111 * Notetags112 * ============================================================================113 *114 * You can use the following notetags to setup how augments work in your game115 * and affect your equipment.116 *117 * Weapon and Armor Notetags:118 *119 * <Augment Slots>120 * Rune121 * Glyph122 * Orb123 * Mark124 * </Augment Slots>125 * This allows you to set what kind of augments are used for the item. The126 * names used for the augment slots are the augment types used for that item.127 *128 * <No Augment Slots>129 * This makes the item have no augment slots.130 *131 * Item, Weapon, Armor Notetags132 *133 * <Augment: type>134 * augment effect135 * augment effect136 * </Augment: type>137 * This will change the item into a non-Independent item. This item can be138 * used to augment equipment that contain the appropriate augment 'type'.139 * This particular notetag will decide the augment effect for attaching the140 * augment component and the reverse effect for detaching the component.141 * Insert multiple sets of these notetags to allow different augment effects142 * when used on different augment slot types.143 *144 * <Augment Attach: type>145 * augment effect146 * augment effect147 * </Augment Attach: type>148 * This will change the item into a non-Independent item. This item can be149 * used to augment equipment that contain the appropriate augment 'type'.150 * This notetag will decide only the augment effects that are applied when151 * the augment component is attached to the equipment and not when detached.152 * Insert multiple sets of these notetags to allow different augment effects153 * when used on different augment slot types.154 *155 * <Augment Detach: type>156 * augment effect157 * augment effect158 * </Augment Detach: type>159 * This will change the item into a non-Independent item. This item can be160 * used to augment equipment that contain the appropriate augment 'type'.161 * This notetag will decide only the augment effects that are applied when162 * the augment component is detached from the equipment and not attached.163 * Insert multiple sets of these notetags to allow different augment effects164 * when used on different augment slot types.165 *166 * ============================================================================167 * Augment Effect List168 * ============================================================================169 *170 * The following is a list of effects you can use for the <Augment: type>,171 * <Augment Attach: type>, <Augment Detatch: type> notetags to have it apply172 * the desired effects to the upgraded item.173 *174 * --- Effects ---175 *176 * Param: +x177 * Param: -x178 * - Replace 'Param' with 'MaxHP', 'MaxMP', 'ATK', 'DEF', 'MAT', 'MDF', 'AGI',179 * or 'LUK'. This will increase/decrease the parameter for the item by x.180 *181 * ---182 *183 * Param: +x%184 * Param: -x%185 * - Replace 'Param' with 'MaxHP', 'MaxMP', 'ATK', 'DEF', 'MAT', 'MDF', 'AGI',186 * 'LUK', 'HIT', 'EVA', 'CRI', 'CEV', 'MEV', 'MRF', 'CNT', 'HRG', 'MRG', 'TRG',187 * 'TGR', 'GRD', 'REC', 'PHA', 'MCR', 'TCR', 'PDR', 'MDR', 'FDR', or 'EXR'.188 * This will increase/decrease the rate for that parameter for the item by x%.189 * Refer to the Base Parameter Control, Extra Parameter Formula, and Special190 * Parameter Formula plugins for more information regarding these stats.191 *192 * ---193 *194 * Boost: +x195 * Boost: -x196 * - This will increase or decrease the boost count of the item by x.197 *198 * ---199 *200 * Price: +x201 * Price: -x202 * - This will increase or decrease the price of the item by x.203 *204 * ---205 *206 * Cannot Detach207 * - This makes the augment unable to be detached once applied.208 *209 * ---210 *211 * Add Attack Element: x212 * Remove Attack Element: x213 * - Add/Remove Attack Element 'x' to item. You can use either the name or the214 * ID of the element. If the name is used and you have multiple elements in215 * your database with the same name, priority will be given to the element with216 * the highest ID.217 *218 * ---219 *220 * Add Attack State: x221 * Add Attack State: x, y%222 * Remove Attack State: x223 * Remove Attack State: x, y%224 * - Add/Remove Attack State 'x' to item. You can use either the name of the ID225 * of the state. If the name is used and you have multiple states in your226 * database with the same name, priority will be given to the state with the227 * highest ID. If 'y' is used, then the success rate of landing the state will228 * be y%. If 'y' is not used, the success rate of landing the state is 100%.229 *230 * ---231 *232 * Add Debuff Rate: param, x%233 * Add Debuff Rate: param, +x%234 * Add Debuff Rate: param, -x%235 * Remove Debuff Rate: param, x%236 * Remove Debuff Rate: param, +x%237 * Remove Debuff Rate: param, -x%238 * - Replace 'param' with 'MaxHP', 'MaxMP', 'ATK', 'DEF', 'MAT', 'MDF', 'AGI',239 * or LUK. Add/remove the debuff affliction rate of the parameter for the item240 * to 'x%' rate.241 *242 * ---243 *244 * Add Element Rate: x, y%245 * Add Element Rate: x, +y%246 * Add Element Rate: x, -y%247 * Remove Element Rate: x, y%248 * Remove Element Rate: x, +y%249 * Remove Element Rate: x, -y%250 * - Add/Remove element rate 'x' to item. You can use either the name or the251 * ID of the element. If the name is used and you have multiple elements in252 * your database with the same name, priority will be given to the element with253 * the highest ID. The item's element rate for 'x' will be 'y%' rate.254 *255 * ---256 *257 * Add Passive State: x258 * Remove Passive State: x259 * - Requires YEP_AutoPassiveStates.js installed. Add/Remove passive state 'x'260 * to item. You can use either the name or the ID of the state. If the name is261 * used and you have multiple states in your database with the same name,262 * priority will be given to the state with the highest ID.263 *264 * ---265 *266 * Add Skill: x267 * Remove Skill: x268 * - Add/Remove skill 'x' to item. You can use either the name or the ID of the269 * skill. If the name is used and you have multiple skills in your database270 * with the same name, priority will be given to the skill with the highest ID.271 * This will make the skill temporarily usable by the actor as long as the item272 * is equipped with the augment on it.273 *274 * ---275 *276 * Add Skill Type: x277 * Add SType: x278 * Remove Skill Type: x279 * Remove SType: x280 * - Add/Remove skill type 'x' to item. You can use either the name or the ID281 * of the skill type. If the name is used and you have multiple skills in your282 * database with the same name, priority will be given to the skill type with283 * the highest ID. This will make the skill type temporarily usable by the284 * actor as long as the item is equipped with the augment on it.285 *286 * ---287 *288 * Add State Rate: x, y%289 * Add State Rate: x, +y%290 * Add State Rate: x, -y%291 * Remove State Rate: x, y%292 * Remove State Rate: x, +y%293 * Remove State Rate: x, -y%294 * - Add/Remove state rate for state 'x' to item. You can use either the name295 * or the ID of the state. If the name is used and you have multiple states in296 * your database with the same name, priority will be given to the state with297 * the highest ID. The item's state rate for 'x' will be 'y%' rate.298 *299 * ---300 *301 * Add State Resist: x302 * Remove State Resist: x303 * - Add/Remove state resist for state 'x' to item. You can use either the name304 * or the ID of the state. If the name is used and you have multiple states in305 * your database with the same name, priority will be given to the state with306 * the highest ID.307 *308 * ---309 *310 * Change Base Name: x311 * Cancel Base Name: x312 * - Changes/Cancels the base name of the item to 'x' while the augment is on313 * the item. If an item has multiple augments that alter the base name, then314 * priority is given to the first augment that alters the base name.315 *316 * ---317 *318 * Change Icon: x319 * Cancel Icon: x320 * - Changes/cancels the icon of the item to 'x' while the augment is on the321 * item. If an item has multiple augments that alter the icon, then priority is322 * given to the first augment that alters the icon.323 *324 * ---325 *326 * Change Picture Hue: x327 * Cancel Picture Hue: x328 * - Changes/cancels the picture hue used for the item to 'x' while the329 * augment is on the item. If an item has multiple augments that alter the330 * picture hue, then priority is given to the first augment that alters the331 * picture hue. This requires the plugin: Item Picture Images.332 *333 * ---334 *335 * Change Picture Image: x336 * Cancel Picture Image: x337 * - Changes/cancels the picture image used for the item to 'x' while the338 * augment is on the item. If an item has multiple augments that alter the339 * picture image, then priority is given to the first augment that alters the340 * picture image. This requires the plugin: Item Picture Images.341 *342 * ---343 *344 * Change Prefix: x345 * Cancel Prefix: x346 * - Changes/Cancels the prefix of the item to 'x' while the augment is on the347 * item. If an item has multiple augments that alter the prefix, then priority348 * is given to the first augment that alters the priority.349 *350 * ---351 *352 * Change Priority Name: x353 * Cancel Priority Name: x354 * - Changes/Cancels the priority name of the item to 'x' while the augment is355 * on the item. If an item has multiple augments that alter the priority name,356 * then priority is given to the first augment that alters the priority name.357 *358 * ---359 *360 * Change Suffix: x361 * Cancel Suffix: x362 * - Changes/Cancels the suffix of the item to 'x' while the augment is on the363 * item. If an item has multiple augments that alter the suffix, then priority364 * is given to the first augment that alters the suffix.365 *366 * ---367 *368 * Change Text Color: x369 * Cancel Text Color: x370 * - Changes/Cancels the text color used for the item to 'x' while the augment371 * is on the item. If an item has multiple augments that alter the text color,372 * then priority is given to the first augment that alters text color.373 *374 * ============================================================================375 * Lunatic Mode - Attach and Detach Evals376 * ============================================================================377 *378 * For those with JavaScript experience, you can use the following Lunatic Mode379 * notetags to make custom effects regarding the attaching and detaching of380 * certain augments.381 *382 * --- Attach ---383 *384 * <Augment Attach Eval: type>385 * item.price += $gameParty.highestLevel();386 * item.params[0] += $gameParty.highestLevel();387 * </Augment Attach Eval: type>388 * The 'type' refers to the slot type used for the augment. The 'item' variable389 * refers to the main item being augmented. The 'effectItem' variable refers to390 * the item being used as an augment component. This eval will only run when391 * the augment is being attached.392 *393 * --- Detach ---394 *395 * <Augment Detach Eval: type>396 * item.price -= $gameParty.highestLevel();397 * item.params[0] -= $gameParty.highestLevel();398 * </Augment Detach Eval: type>399 * The 'type' refers to the slot type used for the augment. The 'item' variable400 * refers to the main item being augmented. The 'effectItem' variable refers to401 * the item being used as an augment component. This eval will only run when402 * the augment is being attached.403 *404 * ============================================================================405 * Plugin Commands406 * ============================================================================407 *408 * There's a couple of pluging commands you can use with this plugin.409 *410 * Plugin Command:411 *412 * EnableAugments413 * - This will enable augments in the item action menu. With them enabled,414 * the player can now attach and detach augments to their items.415 *416 * DisableAugments417 * - This will disable augments in the item action menu and hide their418 * options so that the player will be unable to attach or detach augments419 * from their items.420 *421 * ShowAugments422 * - This will show the augments in the item info window when looking at423 * item details.424 *425 * HideAugments426 * - This will hide the augments in the item info window when looking at427 * item details.428 *429 * ============================================================================430 * Changelog431 * ============================================================================432 *433 * Version 1.10:434 * - Updated for RPG Maker MV version 1.5.0.435 *436 * Version 1.09:437 * - Lunatic Mode fail safes added.438 *439 * Version 1.08a:440 * - Fixed a typo within the code. Please update Item Core, Item Disassemble,441 * Attachable Augments, and More Currencies if you are using those plugins.442 * - Optimization update.443 *444 * Version 1.07:445 * - Fixed a bug that caused adding attack state augments without a rate to not446 * work properly.447 *448 * Version 1.06:449 * - Fixed a bug that caused certain named augment settings to not work450 * work properly upon reloading a game.451 *452 * Version 1.05:453 * - Fixed a bug that specifically made the LUK: +x% and LUK: -x% augments not454 * work properly.455 *456 * Version 1.04:457 * - Added +y% and -y% versions of attachments for various augment effects.458 *459 * Version 1.03:460 * - Bug fixed for Add Element Rate: x, y% not working properly.461 *462 * Verison 1.02a:463 * - Fixed a bug that caused Independent Item-types to crash the game when used464 * within the menu.465 * - Fixed a bug that caused custom Lunatic Mode effects to not operate unless466 * there existed basic augment effects.467 * - Fixed a bug that caused param% changes to not function correctly.468 *469 * Version 1.01:470 * - Fixed a bug that caused a crash when equipping "empty" augments.471 *472 * Version 1.00:473 * - Finished Plugin!474 */475//=============================================================================476if (Imported.YEP_ItemCore) {477//=============================================================================478// Parameter Variables479//=============================================================================480Yanfly.Parameters = PluginManager.parameters('YEP_X_AttachAugments');481Yanfly.Param = Yanfly.Param || {};482Yanfly.makeAttachableAugmentParameterSettings = function() {483 var array = String(Yanfly.Parameters['Weapon Slots']).split(',');484 var length = array.length;485 for (var i = 0; i < length; ++i) {486 array[i] = array[i].trim();487 }488 Yanfly.Param.AugmentWeapons = array;489 var array = String(Yanfly.Parameters['Armor Slots']).split(',');490 var length = array.length;491 for (var i = 0; i < length; ++i) {492 array[i] = array[i].trim();493 }494 Yanfly.Param.AugmentArmors = array;495};496Yanfly.makeAttachableAugmentParameterSettings();497Yanfly.Param.AugmentEnable = eval(String(Yanfly.Parameters['Enable Augments']));498Yanfly.Param.AugmentShow = eval(String(Yanfly.Parameters['Show Augments']));499Yanfly.Param.AugmentSlotFmt = String(Yanfly.Parameters['Augment Slot Format']);500Yanfly.Param.AugmentNoneText = String(Yanfly.Parameters['No Augment Text']);501Yanfly.Param.AugmentRemoveText = String(Yanfly.Parameters['Remove Augment']);502Yanfly.Param.AugmentShow = eval(String(Yanfly.Parameters['Show Augment Info']));503Yanfly.Param.AugmentInfoTitle = String(Yanfly.Parameters['Info Title']);504Yanfly.Param.AugmentInfoAlign = String(Yanfly.Parameters['Title Alignment']);505//=============================================================================506// DataManager507//=============================================================================508Yanfly.Augment.DataManager_isDatabaseLoaded = DataManager.isDatabaseLoaded;509DataManager.isDatabaseLoaded = function() {510 if (!Yanfly.Augment.DataManager_isDatabaseLoaded.call(this)) return false;511 if (!Yanfly.YEP_X_AttachAugments) {512 this.processAugmentNotetagsS($dataSkills);513 this.processAugmentNotetagsT($dataStates);514 this.processAugmentNotetagsSys($dataSystem);515 this.processAugmentNotetags1($dataWeapons, true);516 this.processAugmentNotetags1($dataArmors, false);517 this.processAugmentNotetags2($dataItems);518 this.processAugmentNotetags2($dataWeapons);519 this.processAugmentNotetags2($dataArmors);520 Yanfly.YEP_X_AttachAugments = true;521 }522 523 return true;524};525DataManager.processAugmentNotetagsS = function(group) {526 if (Yanfly.SkillIdRef) return;527 Yanfly.SkillIdRef = {};528 for (var n = 1; n < group.length; n++) {529 var obj = group[n];530 if (obj.name.length <= 0) continue;531 Yanfly.SkillIdRef[obj.name.toUpperCase()] = n;532 }533};534DataManager.processAugmentNotetagsT = function(group) {535 if (Yanfly.StateIdRef) return;536 Yanfly.StateIdRef = {};537 for (var n = 1; n < group.length; n++) {538 var obj = group[n];539 if (obj.name.length <= 0) continue;540 Yanfly.StateIdRef[obj.name.toUpperCase()] = n;541 }542};543DataManager.processAugmentNotetagsSys = function(group) {544 Yanfly.STypeIdRef = {};545 for (var i = 1; i < group.skillTypes.length; ++i) {546 var name = group.skillTypes[i].toUpperCase();547 name = name.replace(/\\I\[(\d+)\]/gi, '');548 Yanfly.STypeIdRef[name] = i;549 }550 Yanfly.ElementIdRef = {};551 for (var i = 1; i < group.elements.length; ++i) {552 var name = group.elements[i].toUpperCase();553 name = name.replace(/\\I\[(\d+)\]/gi, '');554 Yanfly.ElementIdRef[name] = i;555 }556};557DataManager.processAugmentNotetags1 = function(group, isWeapon) {558 for (var n = 1; n < group.length; n++) {559 var obj = group[n];560 var notedata = obj.note.split(/[\r\n]+/);561 if (isWeapon) {562 obj.augmentSlots = JsonEx.makeDeepCopy(Yanfly.Param.AugmentWeapons);563 } else {564 obj.augmentSlots = JsonEx.makeDeepCopy(Yanfly.Param.AugmentArmors);565 }566 567 var evalMode = 'none';568 for (var i = 0; i < notedata.length; i++) {569 var line = notedata[i];570 if (line.match(/<(?:AUGMENT SLOT|AUGMENT SLOTS)>/i)) {571 var evalMode = 'augment slots';572 obj.augmentSlots = [];573 } else if (line.match(/<\/(?:AUGMENT SLOT|AUGMENT SLOTS)>/i)) {574 var evalMode = 'none';575 } else if (evalMode === 'augment slots') {576 obj.augmentSlots.push(line.trim());577 } else if (line.match(/<(?:NO AUGMENTS|NO AUGMENT SLOTS)>/i)) {578 obj.augmentSlots = [];579 }580 }581 }582};583DataManager.processAugmentNotetags2 = function(group, isWeapon) {584 for (var n = 1; n < group.length; n++) {585 var obj = group[n];586 var notedata = obj.note.split(/[\r\n]+/);587 obj.augmentTypes = [];588 obj.augmentDataAttach = {};589 obj.augmentDataDetach = {};590 var evalMode = 'none';591 var evalType = 'none';592 obj.augmentEvalAttach = {};593 obj.augmentEvalDetach = {};594 for (var i = 0; i < notedata.length; i++) {595 var line = notedata[i];596 if (line.match(/<AUGMENT:[ ](.*)>/i)) {597 var evalMode = 'augment auto';598 var evalType = String(RegExp.$1).toUpperCase().trim();599 this.makeAugmentEvalType(obj, evalType);600 } else if (line.match(/<\/AUGMENT:[ ](.*)>/i)) {601 var evalMode = 'none';602 var evalType = 'none';603 } else if (evalMode === 'augment auto') {604 obj.augmentDataAttach[evalType].push(line);605 obj.augmentDataDetach[evalType].push(this.reverseAugmentAutoLine(line));606 } else if (line.match(/<AUGMENT ATTACH:[ ](.*)>/i)) {607 var evalMode = 'augment attach';608 var evalType = String(RegExp.$1).toUpperCase().trim();609 this.makeAugmentEvalType(obj, evalType);610 } else if (line.match(/<\/AUGMENT ATTACH:[ ](.*)>/i)) {611 var evalMode = 'none';612 var evalType = 'none';613 } else if (evalMode === 'augment attach') {614 obj.augmentDataAttach[evalType].push(line);615 } else if (line.match(/<AUGMENT DETACH:[ ](.*)>/i)) {616 var evalMode = 'augment detach';617 var evalType = String(RegExp.$1).toUpperCase().trim();618 this.makeAugmentEvalType(obj, evalType);619 } else if (line.match(/<\/AUGMENT DETACH:[ ](.*)>/i)) {620 var evalMode = 'none';621 var evalType = 'none';622 } else if (evalMode === 'augment detach') {623 obj.augmentDataDetach[evalType].push(line);624 } else if (line.match(/<AUGMENT ATTACH EVAL:[ ](.*)>/i)) {625 var evalMode = 'augment eval attach';626 var evalType = String(RegExp.$1).toUpperCase().trim();627 this.makeAugmentEvalType(obj, evalType);628 } else if (line.match(/<\/AUGMENT ATTACH EVAL:[ ](.*)>/i)) {629 var evalMode = 'none';630 var evalType = 'none';631 } else if (evalMode === 'augment eval attach') {632 obj.augmentEvalAttach[evalType] += line + '\n';633 } else if (line.match(/<AUGMENT DETACH EVAL:[ ](.*)>/i)) {634 var evalMode = 'augment eval detach';635 var evalType = String(RegExp.$1).toUpperCase().trim();636 this.makeAugmentEvalType(obj, evalType);637 } else if (line.match(/<\/AUGMENT DETACH EVAL:[ ](.*)>/i)) {638 var evalMode = 'none';639 var evalType = 'none';640 } else if (evalMode === 'augment eval detach') {641 obj.augmentEvalDetach[evalType] += line + '\n';642 }643 }644 }645};646DataManager.reverseAugmentAutoLine = function(line) {647 if (line.match(/ADD[ ](.*):(.*)/i)) {648 var str1 = String(RegExp.$1);649 var str2 = String(RegExp.$2);650 return 'REMOVE ' + str1 + ':' + str2;651 } else if (line.match(/REMOVE[ ](.*):(.*)/i)) {652 var str1 = String(RegExp.$1);653 var str2 = String(RegExp.$2);654 return 'ADD ' + str1 + ':' + str2;655 } else if (line.match(/CHANGE[ ](.*):(.*)/i)) {656 var str1 = String(RegExp.$1);657 var str2 = String(RegExp.$2);658 return 'CANCEL ' + str1 + ':' + str2;659 } else if (line.match(/CANCEL[ ](.*):(.*)/i)) {660 var str1 = String(RegExp.$1);661 var str2 = String(RegExp.$2);662 return 'CHANGE ' + str1 + ':' + str2;663 } else if (line.match(/(.*):[ ]([\+\-]\d+)([%ï¼
])/i)) {664 // var str = String(RegExp.$1);665 // var value = parseInt(RegExp.$2) * -1;666 // if (value > 0) value = '+' + value;667 // return str + ': ' + value + '%';668 return line;669 } else if (line.match(/(.*):[ ]([\+\-]\d+)/i)) {670 var str = String(RegExp.$1);671 var value = parseInt(RegExp.$2) * -1;672 if (value > 0) value = '+' + value;673 return str + ': ' + value;674 }675 return line;676};677DataManager.makeAugmentEvalType = function(obj, evalType) {678 obj.nonIndependent = true;679 obj.augmentDataAttach[evalType] = obj.augmentDataAttach[evalType] || [];680 obj.augmentDataDetach[evalType] = obj.augmentDataDetach[evalType] || [];681 obj.augmentEvalAttach[evalType] = obj.augmentEvalAttach[evalType] || '';682 obj.augmentEvalDetach[evalType] = obj.augmentEvalDetach[evalType] || '';683 obj.augmentTypes.push(evalType);684};685//=============================================================================686// ItemManager687//=============================================================================688ItemManager.checkAugmentSlots = function(item) {689 if (DataManager.isItem(item)) return;690 if (item.augmentSlots === undefined) {691 var baseItem = DataManager.getBaseItem(item);692 item.augmentSlots = JsonEx.makeDeepCopy(baseItem.augmentSlots);693 }694 item.augmentSlotEnable = item.augmentSlotEnable || [];695 item.augmentSlotItems = item.augmentSlotItems || [];696 var length = item.augmentSlots.length;697 for (var i = 0; i < length; ++i) {698 if (item.augmentSlotEnable[i] === undefined) {699 item.augmentSlotEnable[i] = true;700 }701 if (item.augmentSlotItems[i] === undefined) {702 item.augmentSlotItems[i] = 'none';703 }704 }705};706ItemManager.applyAugmentEffects = function(item, effectItem, slotId, gain) {707 if (!item) return;708 gain = gain || 0;709 this.checkAugmentSlots(item);710 if (item.augmentSlotItems[slotId] !== 'none') {711 var augment = this.removeAugmentFromSlot(item, slotId);712 if (augment) $gameParty.gainItem(augment, gain);713 }714 this.installAugmentToSlot(item, effectItem, slotId);715 $gameParty.loseItem(effectItem, gain);716 this.augmentRefreshParty(item);717};718ItemManager.removeAugmentFromSlot = function(item, slotId) {719 $gameTemp._augmentSetting = 'detach';720 var type = item.augmentSlots[slotId].toUpperCase().trim();721 var augment = this.augmentInSlot(item, slotId);722 if (!augment) {723 $gameTemp._augmentSetting = undefined;724 return augment;725 }726 var list = augment.augmentDataDetach[type];727 if (list && list.length > 0) {728 this.processAugmentList(item, augment, slotId, list);729 }730 var code = augment.augmentEvalDetach[type];731 this.processAugmentEval(code, item, augment, slotId);732 $gameTemp._augmentSetting = undefined;733 return augment;734};735ItemManager.removeAllAugments = function(item) {736 var augments = [];737 this.checkAugmentSlots(item);738 var length = item.augmentSlotItems.length;739 for (var i = 0; i < length; ++i) {740 var augment = this.removeAugmentFromSlot(item, i);741 augments.push(augment);742 }743 return augments;744};745ItemManager.installAugmentToSlot = function(item, effectItem, slotId) {746 $gameTemp._augmentSetting = 'attach';747 var type = item.augmentSlots[slotId].toUpperCase().trim();748 if (DataManager.isItem(effectItem)) {749 item.augmentSlotItems[slotId] = 'item ' + effectItem.id;750 } else if (DataManager.isWeapon(effectItem)) {751 item.augmentSlotItems[slotId] = 'weapon ' + effectItem.id;752 } else if (DataManager.isArmor(effectItem)) {753 item.augmentSlotItems[slotId] = 'armor ' + effectItem.id;754 } else if (effectItem === null) {755 item.augmentSlotItems[slotId] = 'none';756 $gameTemp._augmentSetting = undefined;757 return;758 }759 if (!effectItem) {760 $gameTemp._augmentSetting = undefined;761 return;762 }763 var list = effectItem.augmentDataAttach[type];764 if (list && list.length > 0) {765 this.processAugmentList(item, effectItem, slotId, list);766 }767 var code = effectItem.augmentEvalAttach[type];768 this.processAugmentEval(code, item, effectItem, slotId);769 $gameTemp._augmentSetting = undefined;770};771ItemManager.installAugments = function(item, augments) {772 this.checkAugmentSlots(item);773 var length = augments.length;774 for (var i = 0; i < length; ++i) {775 var augment = augments[i];776 this.installAugmentToSlot(item, augment, i);777 }778};779ItemManager.augmentInSlot = function(item, slotId) {780 var augment = item.augmentSlotItems[slotId];781 if (augment.match(/ITEM[ ](\d+)/i)) {782 var id = parseInt(RegExp.$1);783 var item = $dataItems[id];784 return item || null;785 } else if (augment.match(/WEAPON[ ](\d+)/i)) {786 var id = parseInt(RegExp.$1);787 var item = $dataWeapons[id];788 return item || null;789 } else if (augment.match(/ARMOR[ ](\d+)/i)) {790 var id = parseInt(RegExp.$1);791 var item = $dataArmors[id];792 return item || null;793 }794 return null;795};796ItemManager.augmentRefreshParty = function(item) {797 var length = $gameParty.allMembers().length;798 for (var i = 0; i < length; ++i) {799 var member = $gameParty.allMembers()[i];800 if (member && member.equips().contains(item)) member.refresh();801 }802};803ItemManager.processAugmentList = function(item, effectItem, slotId, list) {804 var length = list.length;805 for (var i = 0; i < length; ++i) {806 var line = list[i];807 this.processAugmentEffect(line, item, effectItem, slotId);808 }809};810ItemManager.processAugmentEffect = function(line, mainItem, effectItem, slot) {811 // CANNOT DETACH812 if (line.match(/CANNOT DETACH/i)) {813 return this.applyAugmentCanotDetach(mainItem, slot);814 }815 // ADD ATTACK ELEMENT: x816 if (line.match(/ADD ATTACK ELEMENT:[ ](.*)/i)) {817 var element = String(RegExp.$1).toUpperCase().trim();818 return this.applyAugmentAttackElement(mainItem, element, true);819 } else if (line.match(/REMOVE ATTACK ELEMENT:[ ](.*)/i)) {820 var element = String(RegExp.$1).toUpperCase().trim();821 return this.applyAugmentAttackElement(mainItem, element, false);822 }823 // ADD ATTACK STATE: x824 if (line.match(/ADD ATTACK STATE:[ ](.*)/i)) {825 var text = String(RegExp.$1).toUpperCase().trim();826 return this.applyAugmentAttackState(mainItem, text, true);827 } else if (line.match(/REMOVE ATTACK STATE:[ ](.*)/i)) {828 var text = String(RegExp.$1).toUpperCase().trim();829 return this.applyAugmentAttackState(mainItem, text, false);830 }831 // ADD DEBUFF RATE: x832 if (line.match(/ADD DEBUFF:[ ](.*)/i)) {833 var text = String(RegExp.$1).toUpperCase().trim();834 return this.applyAugmentDebuff(mainItem, text, true);835 } else if (line.match(/REMOVE DEBUFF:[ ](.*)/i)) {836 var text = String(RegExp.$1).toUpperCase().trim();837 return this.applyAugmentDebuff(mainItem, text, false);838 }839 // ADD ELEMENT RATE: x840 if (line.match(/ADD ELEMENT RATE:[ ](.*)/i)) {841 var text = String(RegExp.$1).toUpperCase().trim();842 return this.applyAugmentElement(mainItem, text, true);843 } else if (line.match(/REMOVE ELEMENT RATE:[ ](.*)/i)) {844 var text = String(RegExp.$1).toUpperCase().trim();845 return this.applyAugmentElement(mainItem, text, false);846 }847 // ADD PASSIVE STATE: x848 if (Imported.YEP_AutoPassiveStates) {849 if (line.match(/ADD PASSIVE STATE:[ ](.*)/i)) {850 var text = String(RegExp.$1).toUpperCase().trim();851 return this.applyAugmentPassiveState(mainItem, text, true);852 } else if (line.match(/REMOVE PASSIVE STATE:[ ](.*)/i)) {853 var text = String(RegExp.$1).toUpperCase().trim();854 return this.applyAugmentPassiveState(mainItem, text, false);855 }856 }857 // ADD SKILL: x858 if (line.match(/ADD SKILL:[ ](.*)/i)) {859 var text = String(RegExp.$1).toUpperCase().trim();860 return this.applyAugmentSkill(mainItem, text, true);861 } else if (line.match(/REMOVE SKILL:[ ](.*)/i)) {862 var text = String(RegExp.$1).toUpperCase().trim();863 return this.applyAugmentSkill(mainItem, text, false);864 }865 // ADD SKILL TYPE: x866 if (line.match(/ADD SKILL TYPE:[ ](.*)/i)) {867 var text = String(RegExp.$1).toUpperCase().trim();868 return this.applyAugmentSkillType(mainItem, text, true);869 } else if (line.match(/ADD STYPE:[ ](.*)/i)) {870 var text = String(RegExp.$1).toUpperCase().trim();871 return this.applyAugmentSkillType(mainItem, text, true);872 } else if (line.match(/REMOVE SKILL TYPE:[ ](.*)/i)) {873 var text = String(RegExp.$1).toUpperCase().trim();874 return this.applyAugmentSkillType(mainItem, text, false);875 } else if (line.match(/REMOVE STYPE:[ ](.*)/i)) {876 var text = String(RegExp.$1).toUpperCase().trim();877 return this.applyAugmentSkillType(mainItem, text, false);878 }879 // ADD STATE RATE: x880 if (line.match(/ADD STATE RATE:[ ](.*)/i)) {881 var text = String(RegExp.$1).toUpperCase().trim();882 return this.applyAugmentStateRate(mainItem, text, true);883 } else if (line.match(/REMOVE STATE RATE:[ ](.*)/i)) {884 var text = String(RegExp.$1).toUpperCase().trim();885 return this.applyAugmentStateRate(mainItem, text, false);886 }887 // ADD STATE RESIST: x888 if (line.match(/ADD STATE RESIST:[ ](.*)/i)) {889 var text = String(RegExp.$1).toUpperCase().trim();890 return this.applyAugmentStateResist(mainItem, text, true);891 } else if (line.match(/REMOVE STATE RESIST:[ ](.*)/i)) {892 var text = String(RegExp.$1).toUpperCase().trim();893 return this.applyAugmentStateResist(mainItem, text, false);894 }895 // CHANGE BASE NAME: x896 if (line.match(/CHANGE BASE NAME:[ ](.*)/i)) {897 var text = String(RegExp.$1).trim();898 return this.applyAugmentSetBaseName(mainItem, text, slot, true);899 } else if (line.match(/CANCEL BASE NAME:[ ](.*)/i)) {900 var text = String(RegExp.$1).trim();901 return this.applyAugmentSetBaseName(mainItem, text, slot, false);902 }903 // CHANGE PREFIX: x904 if (line.match(/CHANGE PREFIX:[ ](.*)/i)) {905 var text = String(RegExp.$1).trim();906 return this.applyAugmentSetPrefix(mainItem, text, slot, true);907 } else if (line.match(/CANCEL PREFIX:[ ](.*)/i)) {908 var text = String(RegExp.$1).trim();909 return this.applyAugmentSetPrefix(mainItem, text, slot, false);910 }911 // CHANGE SUFFIX: x912 if (line.match(/CHANGE SUFFIX:[ ](.*)/i)) {913 var text = String(RegExp.$1).trim();914 return this.applyAugmentSetSuffix(mainItem, text, slot, true);915 } else if (line.match(/CANCEL SUFFIX:[ ](.*)/i)) {916 var text = String(RegExp.$1).trim();917 return this.applyAugmentSetSuffix(mainItem, text, slot, false);918 }919 // CHANGE PRIORITY NAME: x920 if (line.match(/CHANGE PRIORITY NAME:[ ](.*)/i)) {921 var text = String(RegExp.$1).trim();922 return this.applyAugmentSetPriorityName(mainItem, text, slot, true);923 } else if (line.match(/CANCEL PRIORITY NAME:[ ](.*)/i)) {924 var text = String(RegExp.$1).trim();925 return this.applyAugmentSetPriorityName(mainItem, text, slot, false);926 }927 // CHANGE ICON: x928 if (line.match(/CHANGE ICON:[ ](\d+)/i)) {929 var icon = parseInt(RegExp.$1);930 return this.applyAugmentSetIcon(mainItem, icon, slot, true);931 } else if (line.match(/CANCEL ICON:[ ](\d+)/i)) {932 var icon = parseInt(RegExp.$1);933 return this.applyAugmentSetIcon(mainItem, icon, slot, false);934 }935 // Imported.YEP_X_ItemPictureImg936 if (Imported.YEP_X_ItemPictureImg) {937 // CHANGE PICTURE IMAGE: x938 if (line.match(/CHANGE PICTURE IMAGE:[ ](.*)/i)) {939 var text = String(RegExp.$1).trim();940 return this.applyAugmentSetPictureImg(mainItem, text, slot, true);941 } else if (line.match(/CANCEL PICTURE IMAGE:[ ](.*)/i)) {942 var text = String(RegExp.$1).trim();943 return this.applyAugmentSetPictureImg(mainItem, text, slot, false);944 }945 // CHANGE ICON: x946 if (line.match(/CHANGE PICTURE HUE:[ ](\d+)/i)) {947 var icon = parseInt(RegExp.$1).clamp(0, 360);948 return this.applyAugmentSetPictureHue(mainItem, icon, slot, true);949 } else if (line.match(/CANCEL PICTURE HUE:[ ](\d+)/i)) {950 var icon = parseInt(RegExp.$1).clamp(0, 360);951 return this.applyAugmentSetPictureHue(mainItem, icon, slot, false);952 }953 } // Imported.YEP_X_ItemPictureImg954 // CHANGE TEXT COLOR: x955 if (line.match(/CHANGE TEXT COLOR:[ ](\d+)/i)) {956 var color = parseInt(RegExp.$1);957 return this.applyAugmentSetTextColor(mainItem, color, slot, true);958 } else if (line.match(/CANCEL TEXT COLOR:[ ](\d+)/i)) {959 var color = parseInt(RegExp.$1);960 return this.applyAugmentSetTextColor(mainItem, color, slot, false);961 }962 // PARAM: +/-X%963 if (line.match(/(.*):[ ]([\+\-]\d+)([%ï¼
])/i)) {964 var param = String(RegExp.$1).toUpperCase().trim();965 var value = parseFloat(RegExp.$2);966 return this.applyAugmentParamRate(mainItem, param, value);967 }968 // PARAM: +/-X969 if (line.match(/(.*):[ ]([\+\-]\d+)/i)) {970 var param = String(RegExp.$1).toUpperCase().trim();971 var value = parseInt(RegExp.$2);972 return this.applyAugmentParamPlus(mainItem, param, value);973 }974};975ItemManager.adjustItemTrait = function(mainItem, code, dataId, value, add) {976 if (add) {977 this.addTraitToItem(mainItem, code, dataId, value);978 } else {979 this.deleteTraitFromItem(mainItem, code, dataId, value);980 }981};982ItemManager.addTraitToItem = function(mainItem, code, dataId, value) {983 var trait = {984 code: code,985 dataId: dataId,986 value: value987 }988 mainItem.traits.push(trait);989};990ItemManager.deleteTraitFromItem = function(mainItem, code, dataId, value) {991 var index = this.getMatchingTraitIndex(mainItem, code, dataId, value);992 if (index >= 0) mainItem.traits.splice(index, 1);993};994ItemManager.getMatchingTraitIndex = function(mainItem, code, dataId, value) {995 var i = mainItem.traits.length;996 while (i--) {997 var trait = mainItem.traits[i];998 if (trait.code !== code) continue;999 if (trait.dataId !== dataId) continue;1000 if (trait.value !== value) continue;1001 return i;1002 }1003 return i;1004}1005ItemManager.applyAugmentCanotDetach = function(mainItem, slotId) {1006 mainItem.augmentSlotEnable[slotId] = false;1007};1008ItemManager.applyAugmentAttackElement = function(mainItem, element, add) {1009 if (element.match(/(\d+)/i)) {1010 var id = parseInt(RegExp.$1);1011 } else {1012 var id = Yanfly.ElementIdRef[element];1013 if (!id) return;1014 }1015 var code = Game_BattlerBase.TRAIT_ATTACK_ELEMENT;1016 this.adjustItemTrait(mainItem, code, id, 0, add);1017};1018ItemManager.applyAugmentAttackState = function(mainItem, text, add) {1019 if (text.match(/(\d+),[ ](\d+)([%ï¼
])/i)) {1020 var id = parseInt(RegExp.$1);1021 var rate = parseFloat(RegExp.$2) * 0.01;1022 } else if (text.match(/(.*),[ ](\d+)([%ï¼
])/i)) {1023 var name = String(RegExp.$1);1024 var rate = parseFloat(RegExp.$2) * 0.01;1025 var id = Yanfly.StateIdRef[name];1026 if (!id) return;1027 } else if (text.match(/(\d+)/i)) {1028 var id = parseInt(RegExp.$1);1029 var rate = 1.0;1030 } else {1031 var id = Yanfly.StateIdRef[text];1032 if (!id) return;1033 var rate = 1.0;1034 }1035 var code = Game_BattlerBase.TRAIT_ATTACK_STATE;1036 this.adjustItemTrait(mainItem, code, id, rate, add);1037};1038ItemManager.applyAugmentDebuff = function(mainItem, element, add) {1039 if (text.match(/(.*),[ ](\d+)([%ï¼
])/i)) {1040 var param = String(RegExp.$1);1041 var rate = parseFloat(RegExp.$2) * 0.01;1042 if (!id) return;1043 } else if (text.match(/(.*),[ ]([\+\-]\d+)([%ï¼
])/i)) {1044 var add = $gameTemp._augmentSetting === 'attach';1045 var name = String(RegExp.$1);1046 var rate = parseFloat(RegExp.$2) * 0.01;1047 rate += 1;1048 } else {1049 return;1050 }1051 if (['MAXHP', 'MHP', 'MAX HP', 'HP'].contains(param)) {1052 var paramId = 0;1053 } else if (['MAXMP', 'MMP', 'MAX MP', 'MP'].contains(param)) {1054 var paramId = 1;1055 } else if (['ATK', 'STR'].contains(param)) {1056 var paramId = 2;1057 } else if (['DEF'].contains(param)) {1058 var paramId = 3;1059 } else if (['MAT', 'INT', 'SPI'].contains(param)) {1060 var paramId = 4;1061 } else if (['MDF', 'RES'].contains(param)) {1062 var paramId = 5;1063 } else if (['AGI', 'SPD'].contains(param)) {1064 var paramId = 6;1065 } else if (['LUK'].contains(param)) {1066 var paramId = 7;1067 } else {1068 return;1069 }1070 var code = Game_BattlerBase.TRAIT_DEBUFF_RATE;1071 this.adjustItemTrait(mainItem, code, paramId, rate, add);1072};1073ItemManager.applyAugmentElement = function(mainItem, text, add) {1074 if (text.match(/(\d+),[ ](\d+)([%ï¼
])/i)) {1075 var id = parseInt(RegExp.$1);1076 var rate = parseFloat(RegExp.$2) * 0.01;1077 } else if (text.match(/(.*),[ ](\d+)([%ï¼
])/i)) {1078 var name = String(RegExp.$1);1079 var rate = parseFloat(RegExp.$2) * 0.01;1080 var id = Yanfly.ElementIdRef[name];1081 if (!id) return;1082 } else if (text.match(/(\d+),[ ]([\+\-]\d+)([%ï¼
])/i)) {1083 var add = $gameTemp._augmentSetting === 'attach';1084 var id = parseInt(RegExp.$1);1085 var rate = parseFloat(RegExp.$2) * 0.01;1086 rate += 1;1087 } else if (text.match(/(.*),[ ]([\+\-]\d+)([%ï¼
])/i)) {1088 var add = $gameTemp._augmentSetting === 'attach';1089 var name = String(RegExp.$1);1090 var id = Yanfly.ElementIdRef[name];1091 var rate = parseFloat(RegExp.$2) * 0.01;1092 rate += 1;1093 } else {1094 return;1095 }1096 var code = Game_BattlerBase.TRAIT_ELEMENT_RATE;1097 this.adjustItemTrait(mainItem, code, id, rate, add);1098};1099ItemManager.applyAugmentPassiveState = function(mainItem, text, add) {1100 if (text.match(/(\d+)/i)) {1101 var id = parseInt(RegExp.$1);1102 } else {1103 var id = Yanfly.StateIdRef[text];1104 if (!id) return;1105 }1106 mainItem.passiveStates = mainItem.passiveStates || [];1107 if (add) {1108 mainItem.passiveStates.push(id);1109 } else {1110 var index = mainItem.passiveStates.indexOf(id);1111 if (index >= 0) mainItem.passiveStates.splice(index, 1);1112 }1113};1114ItemManager.applyAugmentSkill = function(mainItem, text, add) {1115 if (text.match(/(\d+)/i)) {1116 var id = parseInt(RegExp.$1);1117 } else {1118 var id = Yanfly.SkillIdRef[text];1119 if (!id) return;1120 }1121 var code = Game_BattlerBase.TRAIT_SKILL_ADD;1122 this.adjustItemTrait(mainItem, code, id, 1, add);1123};1124ItemManager.applyAugmentSkillType = function(mainItem, text, add) {1125 if (text.match(/(\d+)/i)) {1126 var id = parseInt(RegExp.$1);1127 } else {1128 var id = Yanfly.STypeIdRef[text];1129 if (!id) return;1130 }1131 var code = Game_BattlerBase.TRAIT_STYPE_ADD;1132 this.adjustItemTrait(mainItem, code, id, 1, add);1133};1134ItemManager.applyAugmentStateRate = function(mainItem, text, add) {1135 if (text.match(/(\d+),[ ](\d+)([%ï¼
])/i)) {1136 var id = parseInt(RegExp.$1);1137 var rate = parseFloat(RegExp.$2) * 0.01;1138 } else if (text.match(/(.*),[ ](\d+)([%ï¼
])/i)) {1139 var name = String(RegExp.$1);1140 var rate = parseFloat(RegExp.$2) * 0.01;1141 var id = Yanfly.StateIdRef[name];1142 if (!id) return;1143 } else if (text.match(/(\d+),[ ]([\+\-]\d+)([%ï¼
])/i)) {1144 var add = $gameTemp._augmentSetting === 'attach';1145 var id = parseInt(RegExp.$1);1146 var rate = parseFloat(RegExp.$2) * 0.01;1147 rate += 1;1148 } else if (text.match(/(.*),[ ]([\+\-]\d+)([%ï¼
])/i)) {1149 var add = $gameTemp._augmentSetting === 'attach';1150 var name = String(RegExp.$1);1151 var id = Yanfly.StateIdRef[name];1152 var rate = parseFloat(RegExp.$2) * 0.01;1153 rate += 1;1154 } else {1155 return;1156 }1157 var code = Game_BattlerBase.TRAIT_STATE_RATE;1158 this.adjustItemTrait(mainItem, code, id, rate, add);1159};1160ItemManager.getAugmentFirstValue = function(array, def) {1161 var length = array.length;1162 for (var i = 0; i < length; ++i) {1163 var item = array[i];1164 if (item === null) continue;1165 if (item !== undefined) return item;1166 }1167 return def;1168};1169ItemManager.applyAugmentStateResist = function(mainItem, text, add) {1170 if (text.match(/(\d+)/i)) {1171 var id = parseInt(RegExp.$1);1172 } else {1173 var id = Yanfly.StateIdRef[text];1174 if (!id) return;1175 }1176 var code = Game_BattlerBase.TRAIT_STATE_RESIST;1177 this.adjustItemTrait(mainItem, code, id, 1, add);1178};1179ItemManager.applyAugmentSetBaseName = function(mainItem, text, slot, add) {1180 mainItem.augmentBaseNames = mainItem.augmentBaseNames || [];1181 if (add) {1182 mainItem.augmentBaseNames[slot] = text;1183 } else {1184 mainItem.augmentBaseNames[slot] = undefined;1185 }1186 var baseName = DataManager.getBaseItem(mainItem).name;1187 var name = this.getAugmentFirstValue(mainItem.augmentBaseNames, baseName);1188 this.setBaseName(mainItem, name);1189 this.updateItemName(mainItem);1190};1191ItemManager.applyAugmentSetPrefix = function(mainItem, text, slot, add) {1192 mainItem.augmentPrefixes = mainItem.augmentPrefixes || [];1193 if (add) {1194 mainItem.augmentPrefixes[slot] = text;1195 } else {1196 mainItem.augmentPrefixes[slot] = undefined;1197 }1198 var name = this.getAugmentFirstValue(mainItem.augmentPrefixes, '');1199 this.setNamePrefix(mainItem, name);1200 this.updateItemName(mainItem);1201};1202ItemManager.applyAugmentSetSuffix = function(mainItem, text, slot, add) {1203 mainItem.augmentSuffixes = mainItem.augmentSuffixes || [];1204 if (add) {1205 mainItem.augmentSuffixes[slot] = text;1206 } else {1207 mainItem.augmentSuffixes[slot] = undefined;1208 }1209 var name = this.getAugmentFirstValue(mainItem.augmentSuffixes, '');1210 this.setNameSuffix(mainItem, name);1211 this.updateItemName(mainItem);1212};1213ItemManager.applyAugmentSetPriorityName = function(mainItem, text, slot, add) {1214 mainItem.augmentPriorityNames = mainItem.augmentPriorityNames || [];1215 if (add) {1216 mainItem.augmentPriorityNames[slot] = text;1217 } else {1218 mainItem.augmentPriorityNames[slot] = undefined;1219 }1220 var name = this.getAugmentFirstValue(mainItem.augmentPriorityNames, '');1221 this.setPriorityName(mainItem, name);1222 this.updateItemName(mainItem);1223};1224ItemManager.applyAugmentSetIcon = function(mainItem, icon, slot, add) {1225 mainItem.augmentIcons = mainItem.augmentIcons || [];1226 if (add) {1227 mainItem.augmentIcons[slot] = icon;1228 } else {1229 mainItem.augmentIcons[slot] = undefined;1230 }1231 var baseIcon = DataManager.getBaseItem(mainItem).iconIndex;1232 var id = this.getAugmentFirstValue(mainItem.augmentIcons, baseIcon);1233 mainItem.iconIndex = id;1234};1235ItemManager.applyAugmentSetTextColor = function(mainItem, color, slot, add) {1236 mainItem.augmentTextColor = mainItem.augmentTextColor || [];1237 if (add) {1238 mainItem.augmentTextColor[slot] = color;1239 } else {1240 mainItem.augmentTextColor[slot] = undefined;1241 }1242 var id = this.getAugmentFirstValue(mainItem.augmentTextColor, 0);1243 mainItem.textColor = id;1244};1245Yanfly.Param.AugmentXParams = 1246 ['HIT', 'EVA', 'CRI', 'CEV', 'MEV', 'MRF', 'CNT', 'HRG', 'MRG', 'TRG'];1247Yanfly.Param.AugmentSParams = 1248 ['TGR', 'GRD', 'REC', 'PHA', 'MCR', 'TCR', 'PDR', 'MDR', 'FDR', 'EXR'];1249ItemManager.applyAugmentParamRate = function(mainItem, param, value) {1250 var add = $gameTemp._augmentSetting === 'attach';1251 value = parseFloat(value * 0.01);1252 var rate = value + 1;1253 if (['MAXHP', 'MHP', 'MAX HP', 'HP'].contains(param)) {1254 var code = Game_BattlerBase.TRAIT_PARAM;1255 var id = 0;1256 } else if (['MAXMP', 'MMP', 'MAX MP', 'MP'].contains(param)) {1257 var code = Game_BattlerBase.TRAIT_PARAM;1258 var id = 1;1259 } else if (['ATK', 'STR'].contains(param)) {1260 var code = Game_BattlerBase.TRAIT_PARAM;1261 var id = 2;1262 } else if (['DEF'].contains(param)) {1263 var code = Game_BattlerBase.TRAIT_PARAM;1264 var id = 3;1265 } else if (['MAT', 'INT', 'SPI'].contains(param)) {1266 var code = Game_BattlerBase.TRAIT_PARAM;1267 var id = 4;1268 } else if (['MDF', 'RES'].contains(param)) {1269 var code = Game_BattlerBase.TRAIT_PARAM;1270 var id = 5;1271 } else if (['AGI', 'SPD'].contains(param)) {1272 var code = Game_BattlerBase.TRAIT_PARAM;1273 var id = 6;1274 } else if (['LUK'].contains(param)) {1275 var code = Game_BattlerBase.TRAIT_PARAM;1276 var id = 7;1277 } else if (Yanfly.Param.AugmentXParams.contains(param)) {1278 var code = Game_BattlerBase.TRAIT_XPARAM;1279 var id = Yanfly.Param.AugmentXParams.indexOf(param);1280 rate -= 1;1281 } else if (Yanfly.Param.AugmentSParams.contains(param)) {1282 var code = Game_BattlerBase.TRAIT_SPARAM;1283 var id = Yanfly.Param.AugmentSParams.indexOf(param);1284 } else {1285 return;1286 }1287 this.adjustItemTrait(mainItem, code, id, rate, add);1288};1289ItemManager.applyAugmentParamPlus = function(mainItem, param, value) {1290 if (['MAXHP', 'MHP', 'MAX HP', 'HP'].contains(param)) {1291 var paramId = 0;1292 } else if (['MAXMP', 'MMP', 'MAX MP', 'MP'].contains(param)) {1293 var paramId = 1;1294 } else if (['ATK', 'STR'].contains(param)) {1295 var paramId = 2;1296 } else if (['DEF'].contains(param)) {1297 var paramId = 3;1298 } else if (['MAT', 'INT', 'SPI'].contains(param)) {1299 var paramId = 4;1300 } else if (['MDF', 'RES'].contains(param)) {1301 var paramId = 5;1302 } else if (['AGI', 'SPD'].contains(param)) {1303 var paramId = 6;1304 } else if (['LUK'].contains(param)) {1305 var paramId = 7;1306 } else if (['PRICE', 'COST'].contains(param)) {1307 mainItem.price += value;1308 return;1309 } else if (['BOOST'].contains(param)) {1310 mainItem.boostCount += value;1311 this.updateItemName(mainItem);1312 return;1313 } else {1314 return;1315 }1316 mainItem.params[paramId] += value;1317};1318ItemManager.processAugmentEval = function(code, item, effectItem, slotId) {1319 if (code === '') return;1320 var mainItem = item;1321 var weapon = item;1322 var armor = item;1323 var baseItem = DataManager.getBaseItem(item);1324 var baseWeapon = baseItem;1325 var baseArmor = baseArmor;1326 var s = $gameSwitches._data;1327 var v = $gameVariables._data;1328 try {1329 eval(code);1330 } catch (e) {1331 Yanfly.Util.displayError(e, code, 'ATTACH AUGMENT CUSTOM EFFECT ERROR');1332 }1333};1334//=============================================================================1335// Game_System1336//=============================================================================1337Yanfly.Augment.Game_System_initialize = Game_System.prototype.initialize;1338Game_System.prototype.initialize = function() {1339 Yanfly.Augment.Game_System_initialize.call(this);1340 this.initAugments();1341};1342Game_System.prototype.initAugments = function() {1343 this._augmentsEnabled = Yanfly.Param.AugmentEnable;1344 this._augmentsShow = Yanfly.Param.AugmentShow;1345};1346Game_System.prototype.isAugmentEnabled = function() {1347 if (this._augmentsEnabled === undefined) this.initAugments();1348 return this._augmentsEnabled;1349};1350Game_System.prototype.setAugmentEnable = function(value) {1351 if (this._augmentsEnabled === undefined) this.initAugments();1352 this._augmentsEnabled = value;1353};1354Game_System.prototype.isAugmentShown = function() {1355 if (this._augmentsShow === undefined) this.initAugments();1356 return this._augmentsShow;1357};1358Game_System.prototype.setAugmentShow = function(value) {1359 if (this._augmentsShow === undefined) this.initAugments();1360 this._augmentsShow = value;1361};1362//=============================================================================1363// Game_Interpreter1364//=============================================================================1365Yanfly.Augment.Game_Interpreter_pluginCommand =1366 Game_Interpreter.prototype.pluginCommand;1367Game_Interpreter.prototype.pluginCommand = function(command, args) {1368 Yanfly.Augment.Game_Interpreter_pluginCommand.call(this, command, args);1369 if (command === 'EnableAugments') $gameSystem.setAugmentEnable(true);1370 if (command === 'DisableAugments') $gameSystem.setAugmentEnable(false);1371 if (command === 'ShowAugments') $gameSystem.setAugmentShow(true);1372 if (command === 'HideAugments') $gameSystem.setAugmentShow(false);1373};1374//=============================================================================1375// Window_ItemInfo1376//=============================================================================1377if (Yanfly.Param.AugmentShow) {1378Yanfly.Augment.Window_ItemInfo_drawItemInfoF =1379 Window_ItemInfo.prototype.drawItemInfoF;1380Window_ItemInfo.prototype.drawItemInfoF = function(dy) {1381 dy = Yanfly.Augment.Window_ItemInfo_drawItemInfoF.call(this, dy);1382 dy = this.drawAugmentInfo(dy);1383 return dy;1384};1385Window_ItemInfo.prototype.drawAugmentInfo = function(dy) {1386 if (!$gameSystem.isAugmentShown()) return dy;1387 var item = this._item;1388 var baseItem = DataManager.getBaseItem(item);1389 if (!DataManager.isIndependent(item)) return dy;1390 if (DataManager.isItem(item)) return dy;1391 if (Yanfly.Param.AugmentInfoTitle !== '') {1392 this.resetFontSettings();1393 this.changePaintOpacity(true);1394 this.changeTextColor(this.systemColor());1395 var align = Yanfly.Param.AugmentInfoAlign;1396 this.drawText(Yanfly.Param.AugmentInfoTitle, this.textPadding(), dy,1397 this.contentsWidth() - this.textPadding() * 2, align);1398 this.resetFontSettings();1399 dy += this.lineHeight();1400 }1401 ItemManager.checkAugmentSlots(item);1402 var length = item.augmentSlotItems.length;1403 for (var i = 0; i < length; ++i) {1404 this.drawAugmentData(i, dy);1405 dy += this.lineHeight();1406 }1407 return dy;1408};1409Window_ItemInfo.prototype.drawAugmentData = function(slot, dy) {1410 var text = this._item.augmentSlotItems[slot];1411 if (text.match(/NONE/i)) {1412 text = Yanfly.Param.AugmentNoneText;1413 } else if (text.match(/ITEM[ ](\d+)/i)) {1414 var id = parseInt(RegExp.$1);1415 var item = $dataItems[id];1416 if (item) {1417 text = '\\i[' + item.iconIndex + ']' + item.name;1418 } else {1419 text = Yanfly.Param.AugmentNoneText;1420 }1421 } else if (text.match(/WEAPON[ ](\d+)/i)) {1422 var id = parseInt(RegExp.$1);1423 var item = $dataWeapons[id];1424 if (item) {1425 text = '\\i[' + item.iconIndex + ']' + item.name;1426 } else {1427 text = Yanfly.Param.AugmentNoneText;1428 }1429 } else if (text.match(/ARMOR[ ](\d+)/i)) {1430 var id = parseInt(RegExp.$1);1431 var item = $dataArmors[id];1432 if (item) {1433 text = '\\i[' + item.iconIndex + ']' + item.name;1434 } else {1435 text = Yanfly.Param.AugmentNoneText;1436 }1437 }1438 this.drawTextEx(text, this.textPadding(), dy);1439};1440}; // Yanfly.Param.AugmentShow1441//=============================================================================1442// Window_ItemActionCommand1443//=============================================================================1444Yanfly.Augment.Window_ItemActionCommand_addCustomCommandsF =1445 Window_ItemActionCommand.prototype.addCustomCommandsF;1446Window_ItemActionCommand.prototype.addCustomCommandsF = function() {1447 Yanfly.Augment.Window_ItemActionCommand_addCustomCommandsF.call(this);1448 if (this.isAugmentable()) this.addAugmentSlots();1449};1450Window_ItemActionCommand.prototype.isAugmentable = function() {1451 if (!$gameSystem.isAugmentEnabled()) return false;1452 if (DataManager.isItem(this._item)) return false;1453 return DataManager.isIndependent(this._item);1454};1455Window_ItemActionCommand.prototype.addAugmentSlots = function() {1456 ItemManager.checkAugmentSlots(this._item);1457 var length = this._item.augmentSlots.length;1458 for (var i = 0; i < length; ++i) {1459 var enabled = this._item.augmentSlotEnable[i];1460 var fmt = Yanfly.Param.AugmentSlotFmt;1461 var slot = this._item.augmentSlots[i];1462 var name = this.getAugmentSlotItemName(i);1463 var text = fmt.format(slot, name);1464 this.addCommand(text, 'augment', enabled, i);1465 }1466 this.changePaintOpacity(true);1467};1468Window_ItemActionCommand.prototype.getAugmentSlotItemName = function(slot) {1469 var str = this._item.augmentSlotItems[slot];1470 if (str.match(/NONE/i)) {1471 return Yanfly.Param.AugmentNoneText;1472 } else if (str.match(/ITEM[ ](\d+)/i)) {1473 var id = parseInt(RegExp.$1);1474 var item = $dataItems[id];1475 if (item) {1476 return '\\i[' + item.iconIndex + ']' + item.name;1477 } else {1478 this._item.augmentSlotItems[slot] = 'none';1479 return Yanfly.Param.AugmentNoneText;1480 }1481 } else if (str.match(/WEAPON[ ](\d+)/i)) {1482 var id = parseInt(RegExp.$1);1483 var item = $dataWeapons[id];1484 if (item) {1485 return '\\i[' + item.iconIndex + ']' + item.name;1486 } else {1487 this._item.augmentSlotItems[slot] = 'none';1488 return Yanfly.Param.AugmentNoneText;1489 }1490 } else if (str.match(/ARMOR[ ](\d+)/i)) {1491 var id = parseInt(RegExp.$1);1492 var item = $dataArmors[id];1493 if (item) {1494 return '\\i[' + item.iconIndex + ']' + item.name;1495 } else {1496 this._item.augmentSlotItems[slot] = 'none';1497 return Yanfly.Param.AugmentNoneText;1498 }1499 }1500};1501//=============================================================================1502// Window_AugmentItemList1503//=============================================================================1504function Window_AugmentItemList() {1505 this.initialize.apply(this, arguments);1506}1507Window_AugmentItemList.prototype = Object.create(Window_ItemList.prototype);1508Window_AugmentItemList.prototype.constructor = Window_AugmentItemList;1509Window_AugmentItemList.prototype.initialize = function(x, y, width, height) {1510 Window_ItemList.prototype.initialize.call(this, x, y, width, height);1511 this._item = null;1512 this._slotId = -1;1513 this.hide();1514 this.deactivate();1515};1516Window_AugmentItemList.prototype.setItem = function(item, slotId) {1517 if (this._item === item && this._slotId === slotId) return;1518 ItemManager.checkAugmentSlots(item);1519 this._item = item;1520 this._slotId = slotId;1521 this.refresh();1522 this.select(0);1523};1524Window_AugmentItemList.prototype.includes = function(item) {1525 if (!item) return false;1526 if (DataManager.isIndependent(item)) return false;1527 if (!this.containsType(item)) return false;1528 return true;1529};1530Window_AugmentItemList.prototype.containsType = function(item) {1531 if (!this._item) return false;1532 var type = this._item.augmentSlots[this._slotId].toUpperCase().trim();1533 return item.augmentTypes.contains(type);1534};1535Window_AugmentItemList.prototype.isEnabled = function(item) {1536 if (item === null) return true;1537 return true;1538};1539Window_AugmentItemList.prototype.selectLast = function() {1540};1541Window_AugmentItemList.prototype.playOkSound = function() {1542 SoundManager.playEquip();1543};1544Window_AugmentItemList.prototype.makeItemList = function() {1545 this._data = $gameParty.allItems().filter(function(item) {1546 return this.includes(item);1547 }, this);1548 if (this._item && this._item.augmentSlotItems[this._slotId] !== 'none') {1549 this._data.unshift(null);1550 }1551};1552Window_AugmentItemList.prototype.drawItem = function(index) {1553 if (this._data[index] === null) this.drawEmptyIcon(index);1554 Window_ItemList.prototype.drawItem.call(this, index);1555};1556Window_AugmentItemList.prototype.drawEmptyIcon = function(index) {1557 var rect = this.itemRect(index);1558 rect.width -= this.textPadding();1559 this.changePaintOpacity(true);1560 var text = Yanfly.Param.AugmentRemoveText;1561 this.drawTextEx(text, rect.x, rect.y);1562};1563//=============================================================================1564// Scene_Item1565//=============================================================================1566Yanfly.Augment.Scene_Item_createItemWindow = 1567 Scene_Item.prototype.createItemWindow;1568Scene_Item.prototype.createItemWindow = function() {1569 Yanfly.Augment.Scene_Item_createItemWindow.call(this);1570 this.createAugmentListWindow();1571};1572Yanfly.Augment.Scene_Item_createActionWindow =1573 Scene_Item.prototype.createActionWindow;1574Scene_Item.prototype.createActionWindow = function() {1575 Yanfly.Augment.Scene_Item_createActionWindow.call(this);1576 this._itemActionWindow.setHandler('augment', this.onActionAugment.bind(this));1577};1578Scene_Item.prototype.createAugmentListWindow = function() {1579 var wy = this._itemWindow.y;1580 var ww = this._itemWindow.width;1581 var wh = this._itemWindow.height;1582 this._augmentListWindow = new Window_AugmentItemList(0, wy, ww, wh);1583 this._augmentListWindow.setHelpWindow(this._helpWindow);1584 this._augmentListWindow.setHandler('ok', this.onAugmentListOk.bind(this));1585 this._augmentListWindow.setHandler('cancel',1586 this.onAugmentListCancel.bind(this));1587 this.addWindow(this._augmentListWindow);1588};1589Scene_Item.prototype.onActionAugment = function() {1590 this._itemActionWindow.hide();1591 this._itemActionWindow.deactivate();1592 this._augmentListWindow.show();1593 this._augmentListWindow.activate();1594 var slotId = this._itemActionWindow.currentExt();1595 this._augmentListWindow.setItem(this.item(), slotId);1596};1597Scene_Item.prototype.onAugmentListOk = function() {1598 var effectItem = this._augmentListWindow.item();1599 var slotId = this._itemActionWindow.currentExt();1600 ItemManager.applyAugmentEffects(this.item(), effectItem, slotId, 1);1601 this._augmentListWindow.refresh();1602 this._augmentListWindow.activate();1603 this._statusWindow.refresh();1604 this._infoWindow.refresh();1605 this._itemWindow.refresh();1606 this._itemActionWindow.refresh();1607 var index = this._augmentListWindow.index();1608 this.onAugmentListCancel();1609};1610Scene_Item.prototype.onAugmentListCancel = function() {1611 this._augmentListWindow.hide();1612 this._augmentListWindow.deactivate();1613 this._itemActionWindow.show();1614 this._itemActionWindow.activate();1615 this._helpWindow.setItem(this.item());1616 this._augmentListWindow.select(0);1617};1618//=============================================================================1619// Utilities1620//=============================================================================1621Yanfly.Util = Yanfly.Util || {};1622Yanfly.Util.displayError = function(e, code, message) {1623 console.log(message);1624 console.log(code || 'NON-EXISTENT');1625 console.error(e);1626 if (Utils.isNwjs() && Utils.isOptionValid('test')) {1627 if (!require('nw.gui').Window.get().isDevToolsOpen()) {1628 require('nw.gui').Window.get().showDevTools();1629 }1630 }1631};1632//=============================================================================1633// End of File1634//=============================================================================...
data_augmentation.py
Source:data_augmentation.py
1import random2import copy3import itertools4class CombinatorialEnumerate(object):5 """Given M type of augmentations, and a original sequence, successively call \6 the augmentation 2*C(M, 2) times can generate total C(M, 2) augmentaion pairs. 7 In another word, the augmentation method pattern will repeat after every 2*C(M, 2) calls.8 9 For example, M = 3, the argumentation methods to be called are in following order: 10 a1, a2, a1, a3, a2, a3. Which formed three pair-wise augmentations:11 (a1, a2), (a1, a3), (a2, a3) for multi-view contrastive learning.12 """13 def __init__(self, tao=0.2, gamma=0.7, beta=0.2, \14 item_similarity_model=None, insert_rate=0.3, \15 max_insert_num_per_pos=3, substitute_rate=0.3, n_views=5):16 self.data_augmentation_methods = [Crop(tao=tao), Mask(gamma=gamma), Reorder(beta=gamma), 17 Insert(item_similarity_model, insert_rate=insert_rate, 18 max_insert_num_per_pos=max_insert_num_per_pos),19 Substitute(item_similarity_model, substitute_rate=substitute_rate)]20 self.n_views = n_views21 # length of the list == C(M, 2)22 self.augmentation_idx_list = self.__get_augmentation_idx_order()23 self.total_augmentation_samples = len(self.augmentation_idx_list)24 self.cur_augmentation_idx_of_idx = 0 25 def __get_augmentation_idx_order(self):26 augmentation_idx_list = []27 for (view_1, view_2) in itertools.combinations([i for i in range(self.n_views)], 2):28 augmentation_idx_list.append(view_1)29 augmentation_idx_list.append(view_2)30 return augmentation_idx_list31 def __call__(self, sequence):32 augmentation_idx = self.augmentation_idx_list[self.cur_augmentation_idx_of_idx]33 augment_method = self.data_augmentation_methods[augmentation_idx]34 # keep the index of index in range(0, C(M,2))35 self.cur_augmentation_idx_of_idx += 136 self.cur_augmentation_idx_of_idx = self.cur_augmentation_idx_of_idx % self.total_augmentation_samples37 # print(augment_method.__class__.__name__)38 return augment_method(sequence)39class Random(object):40 """Randomly pick one data augmentation type every time call"""41 def __init__(self, tao=0.2, gamma=0.7, beta=0.2, \42 item_similarity_model=None, insert_rate=0.3, \43 max_insert_num_per_pos=3, substitute_rate=0.3,\44 augment_threshold=-1,45 augment_type_for_short='SIM'):46 self.augment_threshold = augment_threshold47 self.augment_type_for_short = augment_type_for_short48 if self.augment_threshold == -1:49 self.data_augmentation_methods = [Crop(tao=tao), Mask(gamma=gamma), Reorder(beta=beta), 50 Insert(item_similarity_model, insert_rate=insert_rate, 51 max_insert_num_per_pos=max_insert_num_per_pos),52 Substitute(item_similarity_model, substitute_rate=substitute_rate)]53 print("Total augmentation numbers: ", len(self.data_augmentation_methods))54 elif self.augment_threshold > 0:55 print("short sequence augment type:", self.augment_type_for_short)56 if self.augment_type_for_short == 'SI':57 self.short_seq_data_aug_methods = [Insert(item_similarity_model, insert_rate=insert_rate, 58 max_insert_num_per_pos=max_insert_num_per_pos, 59 augment_threshold=self.augment_threshold),60 Substitute(item_similarity_model, substitute_rate=substitute_rate)]61 elif self.augment_type_for_short == 'SIM':62 self.short_seq_data_aug_methods = [Insert(item_similarity_model, insert_rate=insert_rate, 63 max_insert_num_per_pos=max_insert_num_per_pos, 64 augment_threshold=self.augment_threshold),65 Substitute(item_similarity_model, substitute_rate=substitute_rate),66 Mask(gamma=gamma)]67 elif self.augment_type_for_short == 'SIR':68 self.short_seq_data_aug_methods = [Insert(item_similarity_model, insert_rate=insert_rate, 69 max_insert_num_per_pos=max_insert_num_per_pos, 70 augment_threshold=self.augment_threshold),71 Substitute(item_similarity_model, substitute_rate=substitute_rate),72 Reorder(beta=gamma)]73 elif self.augment_type_for_short == 'SIC':74 self.short_seq_data_aug_methods = [Insert(item_similarity_model, insert_rate=insert_rate, 75 max_insert_num_per_pos=max_insert_num_per_pos, 76 augment_threshold=self.augment_threshold),77 Substitute(item_similarity_model, substitute_rate=substitute_rate),78 Crop(tao=tao)]79 elif self.augment_type_for_short == 'SIMR':80 self.short_seq_data_aug_methods = [Insert(item_similarity_model, insert_rate=insert_rate, 81 max_insert_num_per_pos=max_insert_num_per_pos, 82 augment_threshold=self.augment_threshold),83 Substitute(item_similarity_model, substitute_rate=substitute_rate),84 Mask(gamma=gamma), Reorder(beta=gamma)]85 elif self.augment_type_for_short == 'SIMC':86 self.short_seq_data_aug_methods = [Insert(item_similarity_model, insert_rate=insert_rate, 87 max_insert_num_per_pos=max_insert_num_per_pos, 88 augment_threshold=self.augment_threshold),89 Substitute(item_similarity_model, substitute_rate=substitute_rate),90 Mask(gamma=gamma), Crop(tao=tao)]91 elif self.augment_type_for_short == 'SIRC':92 self.short_seq_data_aug_methods = [Insert(item_similarity_model, insert_rate=insert_rate, 93 max_insert_num_per_pos=max_insert_num_per_pos, 94 augment_threshold=self.augment_threshold),95 Substitute(item_similarity_model, substitute_rate=substitute_rate),96 Reorder(beta=gamma), Crop(tao=tao)]97 else:98 print("all aug set for short sequences")99 self.short_seq_data_aug_methods = [Insert(item_similarity_model, insert_rate=insert_rate, 100 max_insert_num_per_pos=max_insert_num_per_pos, 101 augment_threshold=self.augment_threshold),102 Substitute(item_similarity_model, substitute_rate=substitute_rate),103 Crop(tao=tao), Mask(gamma=gamma), Reorder(beta=gamma)] 104 self.long_seq_data_aug_methods = [Insert(item_similarity_model, insert_rate=insert_rate, 105 max_insert_num_per_pos=max_insert_num_per_pos, 106 augment_threshold=self.augment_threshold),107 Crop(tao=tao), Mask(gamma=gamma), Reorder(beta=gamma),108 Substitute(item_similarity_model, substitute_rate=substitute_rate)]109 print("Augmentation methods for Long sequences:", len(self.long_seq_data_aug_methods))110 print("Augmentation methods for short sequences:", len(self.short_seq_data_aug_methods))111 else:112 raise ValueError("Invalid data type.")113 def __call__(self, sequence):114 if self.augment_threshold == -1:115 #randint generate int x in range: a <= x <= b116 augment_method_idx = random.randint(0, len(self.data_augmentation_methods)-1)117 augment_method = self.data_augmentation_methods[augment_method_idx]118 # print(augment_method.__class__.__name__) # debug usage119 return augment_method(sequence)120 elif self.augment_threshold > 0:121 seq_len = len(sequence)122 if seq_len > self.augment_threshold:123 #randint generate int x in range: a <= x <= b124 augment_method_idx = random.randint(0, len(self.long_seq_data_aug_methods)-1)125 augment_method = self.long_seq_data_aug_methods[augment_method_idx]126 # print(augment_method.__class__.__name__) # debug usage127 return augment_method(sequence)128 elif seq_len <= self.augment_threshold:129 #randint generate int x in range: a <= x <= b130 augment_method_idx = random.randint(0, len(self.short_seq_data_aug_methods)-1)131 augment_method = self.short_seq_data_aug_methods[augment_method_idx]132 # print(augment_method.__class__.__name__) # debug usage133 return augment_method(sequence) 134def _ensmeble_sim_models(top_k_one, top_k_two):135 # only support top k = 1 case so far136# print("offline: ",top_k_one, "online: ", top_k_two)137 if top_k_one[0][1] >= top_k_two[0][1]:138 return [top_k_one[0][0]]139 else:140 return [top_k_two[0][0]]141 142class Insert(object):143 """Insert similar items every time call"""144 def __init__(self, item_similarity_model, insert_rate=0.4, max_insert_num_per_pos=1,145 augment_threshold=14):146 self.augment_threshold = augment_threshold147 if type(item_similarity_model) is list:148 self.item_sim_model_1 = item_similarity_model[0]149 self.item_sim_model_2 = item_similarity_model[1]150 self.ensemble = True151 else:152 self.item_similarity_model = item_similarity_model153 self.ensemble = False154 self.insert_rate = insert_rate155 self.max_insert_num_per_pos = max_insert_num_per_pos156 157 158 def __call__(self, sequence):159 # make a deep copy to avoid original sequence be modified160 copied_sequence = copy.deepcopy(sequence)161 insert_nums = max(int(self.insert_rate*len(copied_sequence)), 1)162 insert_idx = random.sample([i for i in range(len(copied_sequence))], k = insert_nums)163 inserted_sequence = []164 for index, item in enumerate(copied_sequence):165 if index in insert_idx:166 top_k = random.randint(1, max(1, int(self.max_insert_num_per_pos/insert_nums)))167 if self.ensemble:168 top_k_one = self.item_sim_model_1.most_similar(item,169 top_k=top_k, with_score=True)170 top_k_two = self.item_sim_model_2.most_similar(item,171 top_k=top_k, with_score=True)172 inserted_sequence += _ensmeble_sim_models(top_k_one, top_k_two)173 else:174 inserted_sequence += self.item_similarity_model.most_similar(item,175 top_k=top_k)176 inserted_sequence += [item]177 return inserted_sequence178 179class Substitute(object):180 """Substitute with similar items"""181 def __init__(self, item_similarity_model, substitute_rate=0.1):182 if type(item_similarity_model) is list:183 self.item_sim_model_1 = item_similarity_model[0]184 self.item_sim_model_2 = item_similarity_model[1]185 self.ensemble = True186 else:187 self.item_similarity_model = item_similarity_model188 self.ensemble = False189 self.substitute_rate = substitute_rate190 def __call__(self, sequence):191 # make a deep copy to avoid original sequence be modified192 copied_sequence = copy.deepcopy(sequence)193 substitute_nums = max(int(self.substitute_rate*len(copied_sequence)), 1)194 substitute_idx = random.sample([i for i in range(len(copied_sequence))], k = substitute_nums)195 inserted_sequence = []196 for index in substitute_idx:197 if self.ensemble:198 top_k_one = self.item_sim_model_1.most_similar(copied_sequence[index],199 with_score=True)200 top_k_two = self.item_sim_model_2.most_similar(copied_sequence[index],201 with_score=True)202 substitute_items = _ensmeble_sim_models(top_k_one, top_k_two)203 copied_sequence[index] = substitute_items[0]204 else:205 206 copied_sequence[index] = copied_sequence[index] = self.item_similarity_model.most_similar(copied_sequence[index])[0]207 return copied_sequence208class Crop(object):209 """Randomly crop a subseq from the original sequence"""210 def __init__(self, tao=0.2):211 self.tao = tao212 def __call__(self, sequence):213 # make a deep copy to avoid original sequence be modified214 copied_sequence = copy.deepcopy(sequence)215 sub_seq_length = int(self.tao*len(copied_sequence))216 #randint generate int x in range: a <= x <= b217 start_index = random.randint(0, len(copied_sequence)-sub_seq_length-1)218 if sub_seq_length<1:219 return [copied_sequence[start_index]]220 else:221 cropped_seq = copied_sequence[start_index:start_index+sub_seq_length]222 return cropped_seq223class Mask(object):224 """Randomly mask k items given a sequence"""225 def __init__(self, gamma=0.7):226 self.gamma = gamma227 def __call__(self, sequence):228 # make a deep copy to avoid original sequence be modified229 copied_sequence = copy.deepcopy(sequence)230 mask_nums = int(self.gamma*len(copied_sequence))231 mask = [0 for i in range(mask_nums)]232 mask_idx = random.sample([i for i in range(len(copied_sequence))], k = mask_nums)233 for idx, mask_value in zip(mask_idx, mask):234 copied_sequence[idx] = mask_value235 return copied_sequence236class Reorder(object):237 """Randomly shuffle a continuous sub-sequence"""238 def __init__(self, beta=0.2):239 self.beta = beta240 def __call__(self, sequence):241 # make a deep copy to avoid original sequence be modified242 copied_sequence = copy.deepcopy(sequence)243 sub_seq_length = int(self.beta*len(copied_sequence))244 start_index = random.randint(0, len(copied_sequence)-sub_seq_length-1)245 sub_seq = copied_sequence[start_index:start_index+sub_seq_length]246 random.shuffle(sub_seq)247 reordered_seq = copied_sequence[:start_index] + sub_seq + \248 copied_sequence[start_index+sub_seq_length:]249 assert len(copied_sequence) == len(reordered_seq)250 return reordered_seq251if __name__ == '__main__':252 reorder = Reorder(beta=0.2)253 sequence=[14052, 10908, 2776, 16243, 2726, 2961, 11962, 4672, 2224,254 5727, 4985, 9310, 2181, 3428, 4156, 16536, 180, 12044, 13700]255 rs = reorder(sequence)256 crop = Crop(tao=0.2)257 rs = crop(sequence)258 # rt = RandomType()259 # rs = rt(sequence)260 n_views = 5261 enum_type = CombinatorialEnumerateType(n_views=n_views)262 for i in range(40):263 if i == 20:264 print('-------')...
augment.py
Source:augment.py
1import os2import yaml3import random 4import PIL5from augmentations.augmentations import augment_random_erase, augment_rotate_90, augment_horizontal_flip6from augmentations.augment_util import findRelevantTrainingEx, findTargetDatasets7# from augmentations import augment_random_erase, augment_rotate_90, augment_horizontal_flip8# from augment_util import findRelevantTrainingEx, findTargetDatasets9def _getTrainingConfig(training_directory : str, config_filename : str):10 if not config_filename.endswith('.yaml'):11 config_filename += '.yaml'12 network_config_filename = os.path.join(training_directory, config_filename)13 with open(network_config_filename, "r") as stream:14 try:15 network_config = yaml.safe_load(stream)16 except yaml.YAMLError as exc:17 print(exc)18 return network_config19def applySingleAugmentation(apply_to, augment_func, augment_type, augment_copy, 20 augment_probability, augment_args, augment_kwargs):21 for target_set in apply_to:22 training_dir = os.path.join(target_set, 'train')23 print(f"Apply augmentation \'{augment_type}\' to data in {training_dir}")24 print(f"\tp={augment_probability}, copy={augment_copy}")25 print(f"\targs={augment_args}, kwargs={augment_kwargs}")26 #list if image and txt files, with same names 27 # AAA.jpeg and AAA.txt for example28 original_training_list = os.listdir(training_dir)29 #only want unique names, each entry has img and txt associated with it30 original_name_list = list(set([os.path.splitext(s)[0] for s in original_training_list]))31 num_to_augment = int(augment_probability * len(original_name_list))32 random.shuffle(original_name_list)33 to_augment = original_name_list[:num_to_augment]34 for name in to_augment:35 orig_img_file, orig_annotation_file = findRelevantTrainingEx(original_training_list, name)36 orig_img_path = os.path.join(training_dir, orig_img_file)37 orig_annotation_path = os.path.join(training_dir, orig_annotation_file)38 #apply augmentation and forward arguments39 pil_img, annotation_list = augment_func(orig_img_path, orig_annotation_path, 40 *augment_args, **augment_kwargs)41 #save augmentation42 new_img_path = os.path.join(training_dir, f'{augment_type}_{orig_img_file}')43 new_annotation_path = os.path.join(training_dir, f'{augment_type}_{orig_annotation_file}')44 pil_img.save(new_img_path)45 with open(new_annotation_path, 'w') as f:46 for anno in annotation_list:47 f.write(f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}\n")48 #maybe delete original 49 if not augment_copy:50 #delete old versions51 os.remove(orig_img_path)52 os.remove(orig_annotation_path)53def applyAugmentations(config, local_storage_dir, local_dsets_list):54 augments_to_apply = config['augmentations']55 print(__name__)56 # target_augment = augments_to_apply[0]57 for target_augment in augments_to_apply:58 augment_type = target_augment['type']59 augment_copy = target_augment['copy']60 augment_probability = target_augment['probability']61 augment_args = target_augment['args']62 augment_kwargs = target_augment['kwargs']63 apply_to = findTargetDatasets(target_augment, local_storage_dir, local_dsets_list)64 if augment_type == 'random_erase':65 augment_func = augment_random_erase66 elif augment_type == 'rotate_90':67 augment_func = augment_rotate_9068 elif augment_type == 'horizontal_flip':69 augment_func = augment_horizontal_flip70 else:71 raise NotImplementedError(f'Augmentation type \'{augment_type}\' not supported')72 applySingleAugmentation(apply_to, augment_func, augment_type, augment_copy, 73 augment_probability, augment_args, augment_kwargs)74def main():75 local_storage_dir = './'76 local_dsets_list = ['./thermal_indoor_playground_small',77 './big_ol_fake']78 this_config = _getTrainingConfig('./', 'thermal_augmentation_test.yaml')79 applyAugmentations(this_config, local_storage_dir, local_dsets_list)80 81if __name__ == '__main__':82 main()...
config.py
Source:config.py
1from collections import namedtuple2Game = namedtuple('Game', ['env_name', 'time_factor', 'body_size', 'augment_mode', 'input_size', 'output_size', 'layers', 'activation', 'noise_bias', 'output_noise'])3games = {}4augment_ant = Game(env_name='AugmentAnt-v1',5 body_size=36,6 augment_mode="bounded",7 input_size=28,8 output_size=8,9 layers=[64, 32],10 time_factor=1000,11 activation='tanh',12 noise_bias=0.0,13 output_noise=[False, False, True],14)15games['augment_ant'] = augment_ant16augment_ant_lognormal = Game(env_name='AugmentAnt-v1',17 body_size=36,18 augment_mode="lognormal",19 input_size=28,20 output_size=8,21 layers=[64, 32],22 time_factor=1000,23 activation='tanh',24 noise_bias=0.0,25 output_noise=[False, False, True],26)27games['augment_ant_lognormal'] = augment_ant_lognormal28augment_hopper = Game(env_name='AugmentHopper-v1',29 body_size=9,30 augment_mode="bounded",31 input_size=15,32 output_size=3,33 layers=[75, 15],34 time_factor=1000,35 activation='passthru',36 noise_bias=0.0,37 output_noise=[False, False, True],38)39games['augment_hopper'] = augment_hopper40augment_hopper_lognormal = Game(env_name='AugmentHopper-v1',41 body_size=9,42 augment_mode="lognormal",43 input_size=15,44 output_size=3,45 layers=[75, 15],46 time_factor=1000,47 activation='passthru',48 noise_bias=0.0,49 output_noise=[False, False, True],50)51games['augment_hopper_lognormal'] = augment_hopper_lognormal52augmentbipedsmalllegs = Game(env_name='AugmentBipedalWalkerSmallLegs-v2',53 body_size=8,54 augment_mode="bounded",55 input_size=24,56 output_size=4,57 time_factor=0,58 layers=[40, 40],59 activation='tanh',60 noise_bias=0.0,61 output_noise=[False, False, False],62)63games['augmentbipedsmalllegs'] = augmentbipedsmalllegs64augmentbipedhardsmalllegs = Game(env_name='AugmentBipedalWalkerHardcoreSmallLegs-v2',65 body_size=8,66 augment_mode="bounded",67 input_size=24,68 output_size=4,69 time_factor=0,70 layers=[40, 40],71 activation='tanh',72 noise_bias=0.0,73 output_noise=[False, False, False],74)75games['augmentbipedhardsmalllegs'] = augmentbipedhardsmalllegs76augmentbipedsmalllegs_lognormal = Game(env_name='AugmentBipedalWalkerSmallLegs-v2',77 body_size=8,78 augment_mode="lognormal",79 input_size=24,80 output_size=4,81 time_factor=0,82 layers=[40, 40],83 activation='tanh',84 noise_bias=0.0,85 output_noise=[False, False, False],86)87games['augmentbipedsmalllegs_lognormal'] = augmentbipedsmalllegs_lognormal88augmentbipedtalllegs = Game(env_name='AugmentBipedalWalkerTallLegs-v2',89 body_size=8,90 augment_mode="bounded",91 input_size=24,92 output_size=4,93 time_factor=0,94 layers=[40, 40],95 activation='tanh',96 noise_bias=0.0,97 output_noise=[False, False, False],98)99games['augmentbipedtalllegs'] = augmentbipedtalllegs100augmentbipedtalllegs_lognormal = Game(env_name='AugmentBipedalWalkerTallLegs-v2',101 body_size=8,102 augment_mode="lognormal",103 input_size=24,104 output_size=4,105 time_factor=0,106 layers=[40, 40],107 activation='tanh',108 noise_bias=0.0,109 output_noise=[False, False, False],110)111games['augmentbipedtalllegs_lognormal'] = augmentbipedtalllegs_lognormal112augmentbipedhard = Game(env_name='AugmentBipedalWalkerHardcore-v2',113 body_size=8,114 augment_mode="bounded",115 input_size=24,116 output_size=4,117 time_factor=0,118 layers=[40, 40],119 activation='tanh',120 noise_bias=0.0,121 output_noise=[False, False, False],122)123games['augmentbipedhard'] = augmentbipedhard124augmentbipedhard_lognormal = Game(env_name='AugmentBipedalWalkerHardcore-v2',125 body_size=8,126 augment_mode="lognormal",127 input_size=24,128 output_size=4,129 time_factor=0,130 layers=[40, 40],131 activation='tanh',132 noise_bias=0.0,133 output_noise=[False, False, False],134)135games['augmentbipedhard_lognormal'] = augmentbipedhard_lognormal136augmentbiped = Game(env_name='AugmentBipedalWalker-v2',137 body_size=8,138 augment_mode="bounded",139 input_size=24,140 output_size=4,141 time_factor=0,142 layers=[40, 40],143 activation='tanh',144 noise_bias=0.0,145 output_noise=[False, False, False],146)147games['augmentbiped'] = augmentbiped148augmentbiped_lognormal = Game(env_name='AugmentBipedalWalker-v2',149 body_size=8,150 augment_mode="lognormal",151 input_size=24,152 output_size=4,153 time_factor=0,154 layers=[40, 40],155 activation='tanh',156 noise_bias=0.0,157 output_noise=[False, False, False],158)...
Using AI Code Generation
1var redwood = require('redwood');2var test = {3};4redwood.augment(test, {5 c: function() {6 return this.a + this.b;7 }8});9var redwood = require('redwood');10var test = {11};12redwood.augment(test, {13 c: function() {14 return this.a + this.b;15 }16});17var redwood = require('redwood');18var test = {19};20redwood.augment(test, {21 c: function() {22 return this.a + this.b;23 }24});25var redwood = require('redwood');26var test = {27};28redwood.augment(test, {29 c: function() {30 return this.a + this.b;31 }32});33var redwood = require('redwood');34var test = {35};36redwood.augment(test, {37 c: function() {38 return this.a + this.b;39 }40});41var redwood = require('redwood');42var test = {43};44redwood.augment(test, {45 c: function() {46 return this.a + this.b;47 }48});49var redwood = require('redwood');50var test = {51};52redwood.augment(test, {53 c: function() {
Using AI Code Generation
1var redwood = require('redwood');2var test = redwood('test');3var test2 = redwood('test2');4test.augment('test', function() {5 console.log('test');6});7test2.augment('test', function() {8 console.log('test2');9});10var redwood = require('redwood');11var test = redwood('test');12var test2 = redwood('test2');13test2.augment('test', function() {14 console.log('test2');15});16test.augment('test', function() {17 console.log('test');18});19### Redwood#extend(name, fn)20var redwood = require('redwood');21var test = redwood('test');22var test2 = redwood('test2');23test.extend('test', function() {24 console.log('test');25});26### Redwood#remove(name)27var redwood = require('redwood');28var test = redwood('test');29test.augment('test', function() {30 console.log('test');31});32test.remove('test');33### Redwood#removeAll()34var redwood = require('redwood');35var test = redwood('test');36test.augment('test', function() {37 console.log('test');38});39test.removeAll();40### Redwood#has(name)41var redwood = require('redwood');42var test = redwood('test');43test.augment('test', function() {44 console.log('test');45});46### Redwood#list()
Using AI Code Generation
1var redwood = require('redwoodjs');2var app = redwood.app;3var TestController = {4 index: function (req, res) {5 res.render('index', { title: 'Redwood JS' });6 }7};8app.augment('test', TestController);9app.mapRoute('test', 'index');10app.start();
Using AI Code Generation
1var redwood = require('redwood');2var app = redwood.app;3var config = {4};5redwood.augment('render', function (view, options, callback) {6 var self = this;7 self._render(view, options, function (err, str) {8 if (err) {9 return callback(err);10 }11 var html = '<html><head><title>' + options.title + '</title></head><body>' + str + '</body></html>';12 callback(null, html);13 });14});15app.get('/', function (req, res) {16 res.render('index', { title: 'Redwood' });17});18app.listen(config.port, config.host, function () {19 console.log('Listening on port: ' + config.port);20});21{22 "dependencies": {23 }24}
Using AI Code Generation
1var redwood = require("redwoodjs");2var red = redwood();3var obj = {x: 1};4red.augment(obj, {5 z: function(){6 return this.x + this.y;7 }8});9console.log(obj.z());10console.log(obj.x);11console.log(obj.y);12console.log(obj.z());13console.log(obj.x);14console.log(obj.y);15console.log(obj.z());16console.log(obj.x);17console.log(obj.y);18console.log(obj.z());19console.log(obj.x);20console.log(obj.y);21console.log(obj.z());22console.log(obj.x);23console.log(obj.y);24console.log(obj.z());25console.log(obj.x);26console.log(obj.y);27console.log(obj.z());
Using AI Code Generation
1var redwood = require('redwood');2var test = redwood.augment({3 test: function() {4 console.log('test');5 }6});7[MIT](LICENSE)
Using AI Code Generation
1var redwood = require('redwood');2redwood.augment({3 obj: {4 add: function (a, b) {5 return a + b;6 }7 },8 before: function (a, b) {9 console.log('before');10 },11 after: function (a, b) {12 console.log('after');13 }14});15var obj = {16 add: function (a, b) {17 return a + b;18 }19};20var name = 'add';21var before = function (a, b) {22 console.log('before');23};24var after = function (a, b) {25 console.log('after');26};27var instead = function (a, b) {28 console.log('instead');29};30var instead2 = function (a, b) {31 console.log('instead2');32};33var instead3 = function (a, b) {34 console.log('instead3');35};36var instead4 = function (a, b) {37 console.log('instead4');38};39var instead5 = function (a, b) {40 console.log('instead5');41};42var instead6 = function (a, b) {43 console.log('instead6');44};45var instead7 = function (a, b) {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!