Compare commits

..
6 Commits
Author SHA1 Message Date
Kam 7a1b4c20cf A 2026-02-05 20:31:18 -05:00
Kam fff0bfd63b Dialog System 2026-02-05 19:35:43 -05:00
Kam e010408257 Update ModernSoundSelector.java 2026-02-05 17:27:22 -05:00
Kam 3e28c3cace Fixes 2026-02-05 17:27:13 -05:00
Kam fb45a79e22 Add MD Files 2026-02-05 17:07:59 -05:00
Kam 5417cf8126 Dialog Graph Editor 2026-02-05 17:07:47 -05:00
850 changed files with 34157 additions and 88933 deletions

No files matched your search

-44
View File
@@ -1,44 +0,0 @@
<script>
(function() {
// Fix uppercase text in table cells
// Javadoc 11: method names are in th[scope="row"] a, not td a
function fixCase() {
document.querySelectorAll("th[scope='row'] a, td a, .memberNameLink a").forEach(function(el) {
var t = el.textContent.trim();
if (t.length > 2 && t === t.toUpperCase() && t.indexOf(" ") === -1) {
el.textContent = t.toLowerCase();
}
});
}
// Correct navPadding = topNav height + subNav height
// Uses !important to override jQuery's inline style
function fixPadding() {
var topNav = document.querySelector(".topNav");
var subNav = document.querySelector(".subNav");
var pad = document.querySelector(".navPadding");
if (!pad) return;
var h = (topNav ? topNav.offsetHeight : 0) + (subNav ? subNav.offsetHeight : 0);
if (h > 0) {
pad.style.setProperty("padding-top", h + "px", "important");
}
}
document.addEventListener("DOMContentLoaded", function() {
fixCase();
// Run fixPadding after jQuery has had its chance
setTimeout(fixPadding, 0);
setTimeout(fixPadding, 50);
setTimeout(fixPadding, 200);
// Use MutationObserver to permanently override any further jQuery writes
var pad = document.querySelector(".navPadding");
if (pad) {
var observer = new MutationObserver(function() {
fixPadding();
});
observer.observe(pad, { attributes: true, attributeFilter: ["style"] });
}
});
})();
</script>
-11
View File
@@ -1,11 +0,0 @@
<div id="javadoc-header">
<a href="/CustomNPC-Plus/" class="header-brand">
<div class="header-title">
CustomNPC+
<span>Javadoc Reference</span>
</div>
</a>
<a href="/CustomNPC-Plus/" class="header-back">
Back to Index
</a>
</div>
-954
View File
@@ -1,954 +0,0 @@
/* ============================================================
CustomNPC+ — Javadoc Theme (Javadoc 11)
Tokyo Night — Styled Edition
============================================================ */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap');
:root {
/* ── Tokyo Night palette ── */
--bg: #1a1b26;
--bg2: #1f2335;
--bg3: #24283b;
--bg-elevated: #292e42;
--border: #3b4261;
--border2: #414868;
--text: #c0caf5;
--text-mid: #a9b1d6;
--text-dim: #565f89;
--green: #9ece6a;
--green-dim: rgba(158, 206, 106, 0.12);
--blue: #7aa2f7;
--blue-dim: rgba(122, 162, 247, 0.12);
--amber: #e0af68;
--amber-dim: rgba(224, 175, 104, 0.10);
--purple: #bb9af7;
--purple-dim: rgba(187, 154, 247, 0.10);
--cyan: #7dcfff;
--cyan-dim: rgba(125, 207, 255, 0.10);
--red: #f7768e;
--highlight-bg: rgba(122, 162, 247, 0.08);
--hover-bg: rgba(187, 154, 247, 0.08);
--nav-h: 44px;
--subnav-h: 36px;
/* ── Font stacks ── */
--font-ui: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
--font-mono: 'JetBrains Mono', 'Cascadia Code', 'Fira Code', monospace;
}
* { box-sizing: border-box !important; }
html, body {
height: 100%;
}
body {
background: var(--bg) !important;
color: var(--text) !important;
font-family: var(--font-mono) !important;
font-size: 13px !important;
line-height: 1.6 !important;
margin: 0 !important;
padding: 0 !important;
min-height: 100vh !important;
display: flex !important;
flex-direction: column !important;
}
.skipNav { display: none !important; }
/* ══════════════════════════════════════════════
NAVIGATION
══════════════════════════════════════════════ */
.fixedNav {
position: fixed !important;
top: 0 !important; left: 0 !important; right: 0 !important;
z-index: 100 !important;
}
/* Top bar — gradient accent stripe on top */
.topNav {
position: relative !important;
background: var(--bg2) !important;
border-bottom: 1px solid var(--border) !important;
height: var(--nav-h) !important;
margin: 0 !important; padding: 0 !important;
display: flex !important;
align-items: stretch !important;
overflow: visible !important;
}
/* Gradient accent line across the very top */
.topNav::before {
content: '' !important;
position: absolute !important;
top: 0 !important; left: 0 !important; right: 0 !important;
height: 2px !important;
background: linear-gradient(90deg, var(--blue), var(--purple), var(--cyan)) !important;
z-index: 10 !important;
}
/* Nav list — leave room on right for brand */
.topNav > ul.navList {
list-style: none !important;
margin: 0 !important;
padding: 2px 0 0 8px !important;
padding-right: 320px !important;
display: flex !important;
align-items: stretch !important;
flex-shrink: 0 !important;
}
.topNav > ul.navList > li {
display: flex !important;
align-items: center !important;
margin: 0 !important;
padding: 0 16px !important;
height: var(--nav-h) !important;
font-family: var(--font-ui) !important;
font-size: 12px !important;
font-weight: 500 !important;
white-space: nowrap !important;
text-transform: none !important;
letter-spacing: 0.01em !important;
color: var(--text-dim) !important;
border-bottom: 2px solid transparent !important;
transition: color 0.2s !important;
}
.topNav > ul.navList > li > a {
display: flex !important;
align-items: center !important;
height: var(--nav-h) !important;
margin: 0 -16px !important;
padding: 0 16px !important;
color: var(--text-dim) !important;
font-family: var(--font-ui) !important;
font-size: 12px !important;
font-weight: 500 !important;
text-decoration: none !important;
text-transform: none !important;
letter-spacing: 0.01em !important;
white-space: nowrap !important;
border-bottom: 2px solid transparent !important;
transition: color 0.2s, border-color 0.2s !important;
}
.topNav > ul.navList > li > a:hover {
color: var(--text) !important;
border-bottom-color: var(--purple) !important;
background: transparent !important;
text-shadow: none !important;
text-decoration: none !important;
}
/* Active item — gradient underline */
.topNav > ul.navList > li.navBarCell1Rev {
color: var(--text) !important;
border-image: linear-gradient(90deg, var(--blue), var(--purple)) 1 !important;
border-bottom-width: 2px !important;
border-bottom-style: solid !important;
}
/* ── Brand — pinned to far right of topNav ── */
.topNav > .aboutLanguage {
position: absolute !important;
top: 0 !important; right: 0 !important;
height: var(--nav-h) !important;
display: flex !important;
align-items: center !important;
gap: 12px !important;
padding: 0 16px !important;
background: var(--bg2) !important;
border-left: 1px solid var(--border) !important;
z-index: 5 !important;
}
/* Hide the duplicate in bottom nav */
.bottomNav > .aboutLanguage,
.bottomNav .aboutLanguage {
display: none !important;
}
#javadoc-header {
display: flex !important;
align-items: center !important;
gap: 12px !important;
}
.header-brand { text-decoration: none !important; }
/* Brand title — gradient text */
.header-title {
font-family: var(--font-ui) !important;
font-size: 14px !important;
font-weight: 700 !important;
background: linear-gradient(135deg, var(--blue), var(--purple)) !important;
-webkit-background-clip: text !important;
-webkit-text-fill-color: transparent !important;
background-clip: text !important;
line-height: 1.4 !important;
white-space: nowrap !important;
}
.header-title span {
display: block !important;
font-family: var(--font-mono) !important;
font-size: 9px !important;
font-weight: 400 !important;
background: none !important;
-webkit-text-fill-color: var(--text-dim) !important;
color: var(--text-dim) !important;
margin-top: 1px !important;
letter-spacing: 0.1em !important;
text-transform: uppercase !important;
}
.header-back {
display: inline-flex !important;
align-items: center !important;
text-decoration: none !important;
color: var(--text-dim) !important;
font-family: var(--font-ui) !important;
font-size: 11px !important;
font-weight: 500 !important;
padding: 5px 12px !important;
border: 1px solid var(--border2) !important;
border-radius: 6px !important;
white-space: nowrap !important;
transition: all 0.2s !important;
}
.header-back:hover {
color: var(--text) !important;
border-color: var(--purple) !important;
background: var(--purple-dim) !important;
text-decoration: none !important;
text-shadow: none !important;
}
/* ── Sub nav ── */
.subNav {
background: var(--bg3) !important;
border-bottom: 1px solid var(--border) !important;
height: var(--subnav-h) !important;
margin: 0 !important;
padding: 0 14px !important;
display: flex !important;
align-items: center !important;
gap: 12px !important;
overflow: hidden !important;
}
/* Search first */
.subNav > ul.navListSearch {
order: -1 !important;
}
.subNav ul,
.subNav ul.navList,
.subNav ul.subNavList,
.subNav ul.navListSearch {
list-style: none !important;
margin: 0 !important;
padding: 0 !important;
display: flex !important;
align-items: center !important;
gap: 0 !important;
}
.subNav li {
display: flex !important;
align-items: center !important;
font-family: var(--font-ui) !important;
font-size: 11px !important;
color: var(--text-dim) !important;
padding: 0 6px !important;
white-space: nowrap !important;
border: none !important;
height: auto !important;
text-transform: none !important;
}
.subNav a {
color: var(--blue) !important;
text-decoration: none !important;
font-size: 11px !important;
font-family: var(--font-ui) !important;
transition: color 0.15s !important;
}
.subNav a:hover { color: var(--purple) !important; text-shadow: none !important; }
.subNav label {
font-family: var(--font-ui) !important;
font-size: 11px !important;
color: var(--text-dim) !important;
text-transform: none !important;
margin-right: 4px !important;
}
/* ══════════════════════════════════════════════
CONTENT
══════════════════════════════════════════════ */
main {
background: var(--bg) !important;
padding: 28px !important;
flex: 1 0 auto !important;
}
.contentContainer, div.contentContainer {
background: var(--bg) !important;
padding: 0 28px 0px !important;
}
.header {
padding: 0 28px 0 !important;
margin-bottom: 20px !important;
}
/* Subtitle under h1 on help/overview pages */
.header .subTitle,
div.subTitle {
color: var(--text-mid) !important;
font-family: var(--font-ui) !important;
font-size: 13px !important;
line-height: 1.7 !important;
margin-top: 8px !important;
}
.packageLabelInType {
font-family: var(--font-mono) !important;
font-size: 11px !important;
color: var(--text-dim) !important;
}
/* ── Headings ── */
h1, h2, h3, h4, h5, h6 {
font-family: var(--font-ui) !important;
font-weight: 600 !important;
line-height: 1.5 !important;
text-transform: none !important;
letter-spacing: -0.01em !important;
}
/* Page title — gradient accent bar */
h1.title, h2.title {
font-size: 22px !important;
font-weight: 700 !important;
color: var(--text) !important;
border-bottom: none !important;
padding-bottom: 16px !important;
padding-left: 16px !important;
margin-bottom: 24px !important;
margin-top: 0 !important;
border-left: 4px solid transparent !important;
border-image: linear-gradient(180deg, var(--blue), var(--purple)) 1 !important;
}
/* Section h2 — colored panel */
section > h2,
li.blockList > section > h2 {
font-size: 14px !important;
color: var(--green) !important;
border-left: 3px solid var(--green) !important;
border-bottom: none !important;
padding: 10px 14px !important;
margin: 0 !important;
background: var(--green-dim) !important;
}
/* Generic h2 (table section headers like "Method Summary") */
h2 {
font-size: 14px !important;
color: var(--amber) !important;
border-bottom: none !important;
border-left: 3px solid var(--amber) !important;
padding: 8px 12px !important;
margin-top: 28px !important;
margin-bottom: 12px !important;
background: var(--amber-dim) !important;
}
/* h3 — table section headers inside blockList */
h3 {
font-size: 12px !important;
color: var(--text-mid) !important;
margin: 0 !important;
padding: 10px 14px !important;
background: var(--bg3) !important;
border-bottom: 1px solid var(--border) !important;
}
/* h4 — method detail names */
h4 {
font-size: 13px !important;
font-weight: 600 !important;
color: var(--cyan) !important;
margin: 0 !important;
padding: 10px 14px !important;
background: var(--bg3) !important;
border-bottom: 1px solid var(--border) !important;
border-left: 3px solid var(--cyan) !important;
}
/* ── blockList sections — card-like containers ── */
ul.blockList > li.blockList,
ul.blockListLast > li.blockList {
border: 1px solid var(--border) !important;
border-radius: 6px !important;
margin-bottom: 14px !important;
padding: 0 !important;
background: var(--bg2) !important;
overflow: hidden !important;
}
/* Help page: section cards with padding around their content */
ul.blockList > li.blockList > section {
padding: 0 !important;
}
ul.blockList > li.blockList > section > p,
ul.blockList > li.blockList > section > ul:not(.blockList):not(.blockListLast) {
padding: 14px 18px !important;
margin: 0 !important;
color: var(--text-mid) !important;
font-family: var(--font-ui) !important;
font-size: 13px !important;
line-height: 1.7 !important;
}
/* Nested lists inside section content */
ul.blockList > li.blockList > section > ul:not(.blockList):not(.blockListLast) > li {
color: var(--text-mid) !important;
font-family: var(--font-ui) !important;
font-size: 13px !important;
padding: 3px 0 !important;
list-style: none !important;
}
ul.blockList > li.blockList > section > ul:not(.blockList):not(.blockListLast) > li::before {
content: '\203A' !important;
color: var(--purple) !important;
margin-right: 8px !important;
font-weight: 700 !important;
}
/* ── Inherited methods block ── */
ul.blockList > li.blockList > h3,
ul.blockList > li.blockList > ul.blockList > li.blockList > h3 {
font-size: 11px !important;
color: var(--text-dim) !important;
padding: 8px 14px !important;
background: var(--bg3) !important;
border-bottom: 1px solid var(--border) !important;
margin: 0 !important;
}
/* The comma-separated code block of inherited method names */
ul.blockList > li.blockList > code,
li.blockList > code {
display: block !important;
padding: 10px 16px !important;
color: var(--text-dim) !important;
font-family: var(--font-mono) !important;
font-size: 12px !important;
background: var(--bg) !important;
border: none !important;
line-height: 1.8 !important;
}
/* ── Inheritance chain ── */
ul.inheritance {
list-style: none !important;
padding: 0 !important;
margin: 0 0 16px !important;
font-size: 12px !important;
color: var(--text-dim) !important;
}
ul.inheritance li { padding-left: 16px !important; }
ul.inheritance li:first-child { padding-left: 0 !important; }
/* ── General content lists (help page) ── */
main ul:not(.blockList):not(.blockListLast):not(.navList):not(.subNavList):not(.navListSearch):not(.inheritance) {
padding-left: 0 !important;
margin: 4px 0 4px 12px !important;
list-style: none !important;
}
main ul:not(.blockList):not(.blockListLast):not(.navList):not(.subNavList):not(.navListSearch):not(.inheritance) > li {
color: var(--text-mid) !important;
font-family: var(--font-ui) !important;
font-size: 13px !important;
padding: 3px 0 !important;
line-height: 1.7 !important;
}
main ul:not(.blockList):not(.blockListLast):not(.navList):not(.subNavList):not(.navListSearch):not(.inheritance) > li::before {
content: '\203A' !important;
color: var(--purple) !important;
margin-right: 8px !important;
font-weight: 700 !important;
}
/* General paragraphs in content */
main > div p, .contentContainer p {
color: var(--text-mid) !important;
font-family: var(--font-ui) !important;
font-size: 13px !important;
line-height: 1.7 !important;
margin: 8px 0 !important;
}
/* Emphasized phrase */
.emphasizedPhrase {
display: block !important;
color: var(--text-dim) !important;
font-family: var(--font-mono) !important;
font-size: 12px !important;
font-style: italic !important;
border-left: 2px solid var(--purple) !important;
padding: 8px 14px !important;
margin-top: 16px !important;
background: var(--purple-dim) !important;
border-radius: 0 4px 4px 0 !important;
}
/* Bottom footer subNav */
footer {
/*margin-top: auto;*/
}
footer .subNav {
background: var(--bg3) !important;
border-top: 1px solid var(--border) !important;
border-bottom: none !important;
height: var(--subnav-h) !important;
padding: 0 14px !important;
display: flex !important;
align-items: center !important;
gap: 12px !important;
overflow: hidden !important;
}
/* ══════════════════════════════════════════════
TABLES
══════════════════════════════════════════════ */
table {
width: 100% !important;
border-collapse: collapse !important;
border: 1px solid var(--border) !important;
border-radius: 6px !important;
margin: 16px 0 !important;
font-size: 13px !important;
overflow: hidden !important;
}
caption {
background: var(--bg3) !important;
padding: 8px 14px !important;
text-align: left !important;
border-bottom: 1px solid var(--border2) !important;
caption-side: top !important;
}
/* Table tabs — pill style */
.activeTableTab, .tableTab {
font-family: var(--font-ui) !important;
font-size: 11px !important;
font-weight: 500 !important;
text-transform: none !important;
padding: 4px 12px !important;
border: 1px solid var(--border2) !important;
border-radius: 20px !important;
display: inline-block !important;
margin-right: 6px !important;
cursor: pointer !important;
transition: all 0.2s !important;
}
.activeTableTab {
color: var(--text) !important;
border-color: var(--blue) !important;
background: var(--blue-dim) !important;
}
.tableTab { color: var(--text-dim) !important; background: var(--bg3) !important; }
.tableTab a { color: var(--text-dim) !important; text-decoration: none !important; }
.tableTab a:hover { color: var(--text) !important; text-shadow: none !important; }
/* Column headers */
th[scope="col"] {
background: var(--bg-elevated) !important;
color: var(--text-dim) !important;
font-family: var(--font-ui) !important;
font-size: 10px !important;
font-weight: 600 !important;
letter-spacing: 0.06em !important;
text-transform: uppercase !important;
padding: 10px 14px !important;
border-bottom: 2px solid var(--border2) !important;
text-align: left !important;
}
/* Data cells */
th[scope="row"], td {
background: var(--bg2) !important;
color: var(--text) !important;
padding: 10px 14px !important;
border-bottom: 1px solid var(--border) !important;
vertical-align: top !important;
text-align: left !important;
font-family: var(--font-mono) !important;
font-size: 12px !important;
font-weight: 400 !important;
text-transform: none !important;
letter-spacing: 0 !important;
transition: background 0.15s !important;
}
/* Stronger alternating row contrast */
tr.altColor > td, tr.altColor > th[scope="row"] { background: var(--bg) !important; }
tr.rowColor > td, tr.rowColor > th[scope="row"] { background: var(--bg2) !important; }
tr:hover > td, tr:hover > th[scope="row"] {
background: var(--purple-dim) !important;
border-bottom-color: rgba(187, 154, 247, 0.25) !important;
}
tr:hover > td a, tr:hover > th[scope="row"] a {
color: var(--purple) !important;
}
/* ── Links ── */
a, a:visited { color: var(--blue) !important; text-decoration: none !important; transition: color 0.15s !important; }
a:hover { color: var(--purple) !important; text-decoration: none !important; }
.memberNameLink a { color: var(--cyan) !important; font-weight: 500 !important; }
.memberNameLink a:hover { color: var(--purple) !important; }
.externalLink { color: var(--blue) !important; }
/* ── Description blocks ── */
div.block {
color: var(--text-mid) !important;
font-family: var(--font-ui) !important;
font-size: 13px !important;
line-height: 1.7 !important;
padding: 4px 0 !important;
}
ul.blockList > li.blockList > div.block{ padding: 12px 16px !important; margin: 0 !important; }
/* ── Method detail ── */
ul.blockList, ul.blockListLast { list-style: none !important; padding: 0 !important; margin: 0 !important; }
ul.blockList > li.blockList, ul.blockListLast > li.blockList {
border: 1px solid var(--border) !important;
border-radius: 6px !important;
margin-bottom: 12px !important;
padding: 0 !important;
overflow: hidden !important;
}
/* Method/type signatures — accent left bar */
pre.methodSignature, pre.typeSignature {
background: var(--bg2) !important;
border: none !important;
border-bottom: 1px solid var(--border) !important;
border-left: 3px solid var(--cyan) !important;
margin: 0 !important;
padding: 14px 18px !important;
font-family: var(--font-mono) !important;
font-size: 12px !important;
color: var(--text) !important;
overflow-x: auto !important;
white-space: pre-wrap !important;
}
pre {
background: var(--bg2) !important;
border: 1px solid var(--border) !important;
border-left: 3px solid var(--blue) !important;
border-radius: 6px !important;
padding: 14px 18px !important;
font-family: var(--font-mono) !important;
font-size: 12px !important;
color: var(--text) !important;
overflow-x: auto !important;
margin: 0 !important;
white-space: pre-wrap !important;
}
code {
font-family: var(--font-mono) !important;
font-size: 12px !important;
color: var(--cyan) !important;
background: var(--bg3) !important;
padding: 2px 6px !important;
border-radius: 4px !important;
}
dl { padding: 12px 16px !important; margin: 0 !important; }
dt { margin-bottom: 4px !important; }
dd { margin: 0 0 8px 16px !important; color: var(--text-mid) !important; font-size: 12px !important; }
.paramLabel, .returnLabel, .throwsLabel, .seeLabel, .simpleTagLabel {
font-family: var(--font-ui) !important;
font-size: 10px !important;
font-weight: 600 !important;
color: var(--purple) !important;
text-transform: uppercase !important;
letter-spacing: 0.06em !important;
}
.typeNameLabel { color: var(--cyan) !important; }
.deprecationBlock {
background: var(--amber-dim) !important;
border-left: 3px solid var(--amber) !important;
border-radius: 0 6px 6px 0 !important;
padding: 10px 14px !important;
color: var(--amber) !important;
font-size: 12px !important;
}
/* ── Inputs ── */
input[type="text"] {
background: var(--bg) !important;
border: 1px solid var(--border2) !important;
color: var(--text) !important;
font-family: var(--font-mono) !important;
font-size: 12px !important;
padding: 5px 12px !important;
outline: none !important;
border-radius: 6px !important;
transition: border-color 0.2s, box-shadow 0.2s !important;
}
input[type="text"]:focus {
border-color: var(--blue) !important;
box-shadow: 0 0 0 2px var(--blue-dim) !important;
}
input[type="reset"] {
background: var(--bg3) !important;
border: 1px solid var(--border2) !important;
color: var(--text-dim) !important;
font-family: var(--font-ui) !important;
font-size: 11px !important;
padding: 5px 12px !important;
cursor: pointer !important;
border-radius: 6px !important;
transition: all 0.2s !important;
}
input[type="reset"]:hover {
border-color: var(--text-dim) !important;
color: var(--text-mid) !important;
}
/* ══════════════════════════════════════════════
BOTTOM NAV
══════════════════════════════════════════════ */
.bottomNav {
background: var(--bg2) !important;
border-top: 1px solid var(--border) !important;
min-height: var(--nav-h) !important;
padding: 0 !important;
margin-top: 32px !important;
overflow: hidden !important;
position: relative !important;
}
/* Gradient accent line on bottom nav too */
.bottomNav::after {
content: '' !important;
position: absolute !important;
bottom: 0 !important; left: 0 !important; right: 0 !important;
height: 2px !important;
background: linear-gradient(90deg, var(--blue), var(--purple), var(--cyan)) !important;
}
.bottomNav ul.navList[title="Navigation"] {
list-style: none !important;
margin: 0 !important;
padding: 0 0 0 8px !important;
display: flex !important;
align-items: stretch !important;
height: var(--nav-h) !important;
}
.bottomNav ul.navList[title="Navigation"] li {
display: flex !important;
align-items: center !important;
margin: 0 !important;
padding: 0 16px !important;
height: var(--nav-h) !important;
font-family: var(--font-ui) !important;
font-size: 12px !important;
font-weight: 500 !important;
white-space: nowrap !important;
text-transform: none !important;
letter-spacing: 0.01em !important;
color: var(--text-dim) !important;
border-top: 2px solid transparent !important;
transition: color 0.2s !important;
}
.bottomNav ul.navList[title="Navigation"] li > a {
display: flex !important;
align-items: center !important;
height: var(--nav-h) !important;
margin: 0 -16px !important;
padding: 0 16px !important;
color: var(--text-dim) !important;
text-decoration: none !important;
font-family: var(--font-ui) !important;
font-size: 12px !important;
font-weight: 500 !important;
transition: color 0.2s !important;
}
.bottomNav ul.navList[title="Navigation"] li > a:hover {
color: var(--text) !important;
text-shadow: none !important;
}
.bottomNav ul.navList[title="Navigation"] li.navBarCell1Rev {
color: var(--text) !important;
border-image: linear-gradient(90deg, var(--blue), var(--purple)) 1 !important;
border-top-width: 2px !important;
border-top-style: solid !important;
}
.bottomNav .aboutLanguage {
display: none !important;
}
.legalCopy {
background: var(--bg2) !important;
color: var(--text-dim) !important;
font-size: 11px !important;
font-family: var(--font-ui) !important;
padding: 14px 18px !important;
text-align: center !important;
border-top: 1px solid var(--border) !important;
}
/* ══════════════════════════════════════════════
SEARCH RESULTS DROPDOWN (jQuery UI Autocomplete)
══════════════════════════════════════════════ */
.ui-autocomplete {
background: var(--bg2) !important;
border: 1px solid var(--border2) !important;
border-radius: 8px !important;
max-height: 400px !important;
overflow-y: auto !important;
overflow-x: hidden !important;
z-index: 9999 !important;
list-style: none !important;
padding: 4px 0 !important;
margin: 4px 0 0 !important;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(122, 162, 247, 0.05) !important;
}
/* Category headers */
.ui-autocomplete .ui-autocomplete-category {
background: var(--bg-elevated) !important;
color: var(--text-dim) !important;
font-family: var(--font-ui) !important;
font-size: 10px !important;
font-weight: 600 !important;
text-transform: uppercase !important;
letter-spacing: 0.06em !important;
padding: 6px 14px !important;
border-bottom: 1px solid var(--border) !important;
border-top: 1px solid var(--border) !important;
cursor: default !important;
}
/* Individual result items */
.ui-autocomplete .ui-menu-item {
background: var(--bg2) !important;
margin: 0 !important;
list-style: none !important;
}
.ui-autocomplete .ui-menu-item > div,
.ui-autocomplete .ui-menu-item-wrapper {
background: var(--bg2) !important;
color: var(--text) !important;
font-family: var(--font-mono) !important;
font-size: 12px !important;
padding: 7px 14px !important;
border: none !important;
border-left: 2px solid transparent !important;
cursor: pointer !important;
line-height: 1.5 !important;
transition: all 0.1s !important;
}
/* Hover / focus state */
.ui-autocomplete .ui-menu-item > div.ui-state-active,
.ui-autocomplete .ui-menu-item > div.ui-state-focus,
.ui-autocomplete .ui-menu-item-wrapper.ui-state-active,
.ui-autocomplete .ui-menu-item-wrapper.ui-state-focus,
.ui-autocomplete .ui-state-active,
.ui-autocomplete .ui-state-focus {
background: var(--purple-dim) !important;
color: var(--text) !important;
border: none !important;
border-left: 2px solid var(--purple) !important;
margin: 0 !important;
}
/* Highlighted matching text */
.resultHighlight {
color: var(--cyan) !important;
font-weight: 600 !important;
}
/* Search tag result extras */
.searchTagHolderResult {
color: var(--text-dim) !important;
font-size: 11px !important;
}
.searchTagDescResult {
color: var(--text-dim) !important;
font-size: 11px !important;
font-style: italic !important;
}
/* "No results found" */
.ui-autocomplete .ui-menu-item:only-child > div {
color: var(--text-dim) !important;
font-style: italic !important;
}
/* Override jQuery UI defaults */
.ui-widget {
font-family: var(--font-mono) !important;
}
.ui-widget-content {
background: var(--bg2) !important;
color: var(--text) !important;
border-color: var(--border2) !important;
}
.ui-menu .ui-menu-item {
padding: 0 !important;
}
/* Watermark style for search input placeholder */
.watermark {
color: var(--text-dim) !important;
}
/* ══════════════════════════════════════════════
MISC
══════════════════════════════════════════════ */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: var(--bg); }
::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-dim); }
::selection { background: rgba(187, 154, 247, 0.25); color: var(--text); }
hr { border: none !important; border-top: 1px solid var(--border) !important; margin: 24px 0 !important; }
-14
View File
@@ -1,14 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Javadoc Index</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600&family=IBM+Plex+Sans:ital,wght@0,300;0,600;1,300&display=swap" rel="stylesheet">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
-1679
View File
File diff suppressed because it is too large. Load diff
-19
View File
@@ -1,19 +0,0 @@
{
"name": "javadoc-index",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.2.1",
"vite": "^7.3.1"
}
}
-64
View File
@@ -1,64 +0,0 @@
import styles from './App.module.css'
import { useDocs } from './useDocs'
import TerminalHeader from './components/TerminalHeader'
import Section from './components/Section'
import { ReleaseCard, ExperimentalCard } from './components/Card'
import { LoadingState, ErrorState, EmptyState } from './components/States'
import Footer from './components/Footer'
export default function App() {
const { data, loading, error } = useDocs()
const releases = data?.releases || []
const experimental = data?.experimental || []
return (
<div className={styles.root}>
<TerminalHeader />
{/* ── Releases ── */}
<Section
label="Release"
variant="releases"
count={loading ? undefined : releases.length}
>
{loading ? (
<LoadingState />
) : error ? (
<ErrorState message={error} />
) : releases.length === 0 ? (
<EmptyState label="releases" />
) : (
<div className={styles.grid}>
{releases.map((r, i) => (
<ReleaseCard key={r.id} release={r} index={i} />
))}
</div>
)}
</Section>
{/* ── Experimental ── */}
<Section
label="Experimental"
variant="experimental"
count={loading ? undefined : experimental.length}
>
{loading ? (
<LoadingState />
) : error ? null : experimental.length === 0 ? (
<EmptyState label="experimental branches" />
) : (
<div className={styles.grid}>
{experimental.map((b, i) => (
<ExperimentalCard key={b.id} branch={b} index={i} />
))}
</div>
)}
</Section>
{!loading && !error && (
<Footer source={data?.source} />
)}
</div>
)
}
-16
View File
@@ -1,16 +0,0 @@
.root {
max-width: 1100px;
margin: 0 auto;
padding: 48px 32px 96px;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 10px;
}
@media (max-width: 600px) {
.root { padding: 24px 16px 64px; }
.grid { grid-template-columns: 1fr; }
}
-97
View File
@@ -1,97 +0,0 @@
import styles from './Card.module.css'
import { REPO_NAME } from '../config'
const BASE_PATH = `/${REPO_NAME}`
function formatDate(iso) {
if (!iso) return null
try {
return new Intl.DateTimeFormat('en-GB', {
day: '2-digit', month: 'short', year: 'numeric'
}).format(new Date(iso))
} catch (e) { return null }
}
export function ReleaseCard({ release, index }) {
const isLatest = release.isLatest
const date = formatDate(release.date)
const cardClass = isLatest
? styles.card + ' ' + styles.latest
: styles.card + ' ' + styles.release
return (
<a
href={BASE_PATH + '/' + release.path + '/'}
className={cardClass}
style={{ animationDelay: (index * 50) + 'ms' }}
>
<div className={styles.header}>
<div className={styles.badges}>
{isLatest && (
<span className={styles.badge + ' ' + styles.badgeLatest}>● latest</span>
)}
<span className={styles.badge + ' ' + styles.badgeRelease}>release</span>
</div>
<span className={styles.arrow}>→</span>
</div>
<div className={styles.version}>
v{release.version}
</div>
<div className={styles.meta}>
{date && (
<div className={styles.metaRow}>
<span className={styles.metaKey}>date</span>
<span className={styles.metaVal}>{date}</span>
</div>
)}
<div className={styles.metaRow}>
<span className={styles.metaKey}>path</span>
<span className={styles.metaVal}>{release.path}/</span>
</div>
</div>
</a>
)
}
export function ExperimentalCard({ branch, index }) {
const date = formatDate(branch.date)
return (
<a
href={BASE_PATH + '/' + branch.path + '/'}
className={styles.card + ' ' + styles.experimental}
style={{ animationDelay: (index * 50) + 'ms' }}
>
<div className={styles.header}>
<span className={styles.badge + ' ' + styles.badgeExperimental}>
experimental
</span>
<span className={styles.arrow}>→</span>
</div>
<div className={styles.version + ' ' + styles.versionBranch}>
{branch.branch}
</div>
<div className={styles.meta}>
{date && (
<div className={styles.metaRow}>
<span className={styles.metaKey}>date</span>
<span className={styles.metaVal}>{date}</span>
</div>
)}
{branch.hash && (
<div className={styles.metaRow}>
<span className={styles.metaKey}>sha</span>
<span className={styles.metaVal + ' ' + styles.hash}>{branch.hash}</span>
</div>
)}
<div className={styles.metaRow}>
<span className={styles.metaKey}>path</span>
<span className={styles.metaVal}>{branch.path}/</span>
</div>
</div>
</a>
)
}
@@ -1,143 +0,0 @@
.card {
display: block;
text-decoration: none;
background: var(--bg2);
border: 1px solid var(--border);
border-radius: 6px;
padding: 20px 22px;
transition: border-color 0.15s, background 0.15s, transform 0.15s;
position: relative;
overflow: hidden;
animation: fadeUp 0.35s ease both;
}
.card::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0;
height: 2px;
opacity: 0;
transition: opacity 0.15s;
}
.release::before { background: var(--green); }
.latest::before { background: linear-gradient(90deg, var(--green), var(--blue)); }
.experimental::before { background: var(--amber); }
.card:hover {
border-color: var(--border2);
background: var(--bg3);
transform: translateY(-2px);
}
.card:hover::before { opacity: 1; }
/* ── Header ── */
.header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
}
.badges {
display: flex;
align-items: center;
gap: 6px;
}
.badge {
font-size: 9px;
font-weight: 600;
letter-spacing: 0.12em;
text-transform: uppercase;
padding: 2px 8px;
border-radius: 2px;
border: 1px solid;
}
.badgeLatest {
color: var(--green);
border-color: var(--green-dim);
background: rgba(57, 211, 83, 0.08);
animation: pulseBorder 2s ease infinite;
}
.badgeRelease {
color: var(--text-dim);
border-color: var(--border2);
background: transparent;
}
.badgeExperimental {
color: var(--amber);
border-color: var(--amber-dim);
background: rgba(240, 160, 48, 0.08);
}
.arrow {
font-size: 14px;
color: var(--border2);
transition: color 0.15s, transform 0.15s;
}
.card:hover .arrow {
color: var(--text-mid);
transform: translateX(3px);
}
/* ── Version ── */
.version {
font-size: 20px;
font-weight: 500;
color: var(--text);
margin-bottom: 4px;
letter-spacing: -0.01em;
}
.latest .version { color: var(--green); }
.versionBranch { font-size: 16px; color: var(--amber); }
/* ── Meta ── */
.meta {
display: flex;
flex-direction: column;
gap: 3px;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.metaRow {
display: flex;
align-items: center;
gap: 8px;
font-size: 10px;
color: var(--text-dim);
}
.metaKey {
min-width: 36px;
color: var(--text-dim);
}
.metaVal {
color: var(--text-mid);
font-family: 'IBM Plex Mono', monospace;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.hash { color: var(--blue); }
/* ── Animations ── */
@keyframes fadeUp {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes pulseBorder {
0%, 100% { border-color: var(--green-dim); }
50% { border-color: var(--green); }
}
-29
View File
@@ -1,29 +0,0 @@
import styles from './Footer.module.css'
import { REPO_OWNER, REPO_NAME } from '../useDocs'
export default function Footer({ source }) {
const now = new Intl.DateTimeFormat('en-GB', {
day: '2-digit', month: 'short', year: 'numeric',
hour: '2-digit', minute: '2-digit', timeZoneName: 'short'
}).format(new Date())
return (
<footer className={styles.footer}>
<span>
<span className={styles.dot} />
Auto-generated · {source === 'manifest' ? 'manifest.json' : 'GitHub API'}
</span>
<span>{now}</span>
<span>Template by:&nbsp;
<a
href={`https://github.com/somehussar/`}
target="_blank"
rel="noopener noreferrer"
className={styles.link}
>
github.com/somehussar
</a>
</span>
</footer>
)
}
@@ -1,36 +0,0 @@
.footer {
margin-top: 64px;
padding-top: 20px;
border-top: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 8px;
font-size: 11px;
color: var(--text-dim);
}
.dot {
display: inline-block;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--green);
margin-right: 6px;
animation: blink 2s ease infinite;
}
.link {
color: var(--blue);
text-decoration: none;
}
.link:hover {
text-decoration: underline;
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
-18
View File
@@ -1,18 +0,0 @@
import styles from './Section.module.css'
export default function Section({ label, count, variant, children }) {
return (
<section className={styles.section}>
<div className={styles.header}>
<span className={`${styles.tag} ${styles[variant]}`}>{label}</span>
<div className={styles.line} />
{count !== undefined && (
<span className={styles.count}>
{count} {label.toLowerCase()}{count !== 1 ? 's' : ''}
</span>
)}
</div>
{children}
</section>
)
}
@@ -1,46 +0,0 @@
.section {
margin-top: 40px;
margin-bottom: 8px;
}
.header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 16px;
}
.tag {
font-size: 10px;
font-weight: 600;
letter-spacing: 0.15em;
text-transform: uppercase;
padding: 3px 10px;
border-radius: 3px;
border: 1px solid;
white-space: nowrap;
}
.releases {
color: var(--green);
border-color: var(--green-dim);
background: rgba(57, 211, 83, 0.06);
}
.experimental {
color: var(--amber);
border-color: var(--amber-dim);
background: rgba(240, 160, 48, 0.06);
}
.line {
flex: 1;
height: 1px;
background: var(--border);
}
.count {
font-size: 11px;
color: var(--text-dim);
white-space: nowrap;
}
-30
View File
@@ -1,30 +0,0 @@
import styles from './States.module.css'
export function LoadingState() {
return (
<div className={styles.box}>
<div className={styles.spinner} />
<p className={styles.label}>Fetching documentation index...</p>
</div>
)
}
export function ErrorState({ message }) {
return (
<div className={styles.box}>
<div className={styles.errorIcon}>⚠</div>
<p className={styles.errorMsg}>{message}</p>
<p className={styles.errorSub}>
Check that the gh-pages branch exists and is publicly accessible.
</p>
</div>
)
}
export function EmptyState({ label }) {
return (
<div className={`${styles.box} ${styles.empty}`}>
<p className={styles.label}>No {label} found.</p>
</div>
)
}
@@ -1,47 +0,0 @@
.box {
border: 1px solid var(--border);
border-radius: 6px;
padding: 48px;
text-align: center;
background: var(--bg2);
}
.empty {
padding: 24px;
}
.spinner {
width: 22px;
height: 22px;
border: 2px solid var(--border2);
border-top-color: var(--green);
border-radius: 50%;
animation: spin 0.75s linear infinite;
margin: 0 auto 14px;
}
.label {
font-size: 12px;
color: var(--text-dim);
}
.errorIcon {
font-size: 22px;
margin-bottom: 10px;
color: var(--red);
}
.errorMsg {
font-size: 13px;
color: var(--red);
margin-bottom: 6px;
}
.errorSub {
font-size: 11px;
color: var(--text-dim);
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@@ -1,186 +0,0 @@
import { useState, useEffect } from 'react'
import styles from './TerminalHeader.module.css'
import { PROJECT_NAME, REPO_NAME, LINKS, AUTHORS } from '../config'
function useGitHubProfile(username) {
const [profile, setProfile] = useState(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const cacheKey = 'gh-profile-' + username
// Check sessionStorage first — avoids hammering the API on every render
try {
const cached = sessionStorage.getItem(cacheKey)
if (cached) {
setProfile(JSON.parse(cached))
setLoading(false)
return
}
} catch (e) {}
fetch('https://api.github.com/users/' + username)
.then(r => {
if (!r.ok) throw new Error('HTTP ' + r.status)
return r.json()
})
.then(d => {
// Don't cache error responses like rate limit messages
if (!d.message) {
try { sessionStorage.setItem(cacheKey, JSON.stringify(d)) } catch (e) {}
}
setProfile(d)
setLoading(false)
})
.catch(() => setLoading(false))
}, [username])
return { profile, loading }
}
function AuthorTile({ username, active }) {
const { profile, loading } = useGitHubProfile(username)
const tileClass = styles.authorTile + (active ? ' ' + styles.authorTileActive : '')
if (loading) {
return (
<div className={tileClass}>
<div className={styles.authorAvatarSkeleton} />
<div className={styles.authorInfo}>
<div className={styles.authorSkeleton} style={{ width: '60px' }} />
<div className={styles.authorSkeleton} style={{ width: '80px', marginTop: '4px' }} />
<div className={styles.authorBioPlaceholder} />
</div>
</div>
)
}
if (!profile || profile.message) {
return (
<a
href={'https://github.com/' + username}
target="_blank"
rel="noopener noreferrer"
className={tileClass}
>
<div className={styles.authorAvatarSkeleton} />
<div className={styles.authorInfo}>
<span className={styles.authorName}>{username}</span>
<span className={styles.authorLogin}>@{username}</span>
<div className={styles.authorBioPlaceholder} />
</div>
</a>
)
}
return (
<a
href={profile.html_url}
target="_blank"
rel="noopener noreferrer"
className={tileClass}
>
<img
src={profile.avatar_url}
alt={profile.login}
className={styles.authorAvatar}
/>
<div className={styles.authorInfo}>
<span className={styles.authorName}>{profile.name || profile.login}</span>
<span className={styles.authorLogin}>@{profile.login}</span>
{profile.bio
? <span className={styles.authorBio}>{profile.bio}</span>
: <div className={styles.authorBioPlaceholder} />
}
</div>
</a>
)
}
function AuthorsTiles() {
const [active, setActive] = useState(0)
useEffect(() => {
if (AUTHORS.length <= 1) return
const t = setInterval(() => {
setActive(i => (i + 1) % AUTHORS.length)
}, 4000)
return () => clearInterval(t)
}, [])
return (
<div className={styles.authors}>
<div className={styles.outputLine}>
<span className={styles.chevron}>›</span> Authors:
</div>
<div className={styles.authorRow}>
{AUTHORS.map((username, i) => (
<AuthorTile
key={username}
username={username}
active={i === active}
/>
))}
</div>
</div>
)
}
export default function TerminalHeader() {
return (
<div className={styles.wrap}>
<div className={styles.bar}>
<div className={styles.dot + ' ' + styles.red} />
<div className={styles.dot + ' ' + styles.amber} />
<div className={styles.dot + ' ' + styles.green} />
<span className={styles.title}>javadoc-index — bash</span>
</div>
<div className={styles.body}>
<h1 className={styles.heading}>
{PROJECT_NAME}
</h1>
<div className={styles.promptLine}>
<span className={styles.prompt}>$</span>
<span className={styles.cmd}>browse-docs</span>
<span className={styles.arg}>{REPO_NAME}</span>
<span className={styles.flag}>--all-versions</span>
</div>
<div className={styles.outputLine}>
<span className={styles.chevron}>›</span> Fetching available documentation builds...
</div>
<div className={styles.outputLine}>
<span className={styles.chevron}>›</span> Found project links:
</div>
<div className={styles.links}>
{LINKS.map(function(l) {
return (
<a
key={l.tag}
href={l.href}
target="_blank"
rel="noopener noreferrer"
className={styles.link}
>
<span className={styles.linkTag} style={{ color: l.color, borderColor: l.color }}>
{l.tag}
</span>
<span className={styles.linkLabel}>{l.label}</span>
<span className={styles.linkArrow} style={{ color: l.color }}>↗</span>
</a>
)
})}
</div>
<AuthorsTiles />
<div className={styles.promptLine} style={{ marginTop: '16px' }}>
<span className={styles.prompt}>$</span>
<span className={styles.cursor} />
</div>
</div>
</div>
)
}
@@ -1,303 +0,0 @@
.wrap {
margin-bottom: 48px;
}
.bar {
display: flex;
align-items: center;
gap: 6px;
background: var(--bg3);
border: 1px solid var(--border2);
border-bottom: none;
border-radius: 8px 8px 0 0;
padding: 10px 16px;
}
.dot {
width: 12px;
height: 12px;
border-radius: 50%;
}
.red { background: #ff5f57; }
.amber { background: #febc2e; }
.green { background: #28c840; }
.title {
margin-left: 8px;
font-size: 11px;
color: var(--text-dim);
letter-spacing: 0.05em;
}
.body {
background: var(--bg2);
border: 1px solid var(--border2);
border-radius: 0 0 8px 8px;
padding: 16px 36px 36px;
}
/* ── Heading ── */
.heading {
font-family: 'IBM Plex Sans', sans-serif;
font-size: clamp(28px, 5vw, 52px);
font-weight: 300;
letter-spacing: -0.02em;
color: var(--text);
line-height: 1.05;
margin-bottom: 20px;
}
.heading strong {
font-weight: 600;
color: var(--green);
}
/* ── Prompt ── */
.promptLine {
display: flex;
align-items: baseline;
gap: 10px;
margin-bottom: 6px;
font-size: 13px;
flex-wrap: wrap;
}
.prompt { color: var(--green); font-weight: 600; }
.cmd { color: var(--text); }
.arg { color: var(--blue); }
.flag { color: var(--amber); }
/* ── Output lines ── */
.outputLine {
font-size: 12px;
color: var(--text-dim);
line-height: 1.8;
padding-left: 20px;
}
.chevron {
color: var(--text-mid);
margin-right: 4px;
}
/* ── Links ── */
.links {
display: flex;
flex-direction: column;
gap: 4px;
padding-left: 36px;
margin-top: 4px;
margin-bottom: 12px;
}
.link {
display: inline-flex;
align-items: center;
gap: 10px;
text-decoration: none;
padding: 3px 0;
width: fit-content;
transition: opacity 0.15s;
}
.link:hover { opacity: 0.8; }
.link:hover .linkLabel {
text-decoration: underline;
text-underline-offset: 3px;
}
.linkTag {
font-size: 9px;
font-weight: 600;
letter-spacing: 0.1em;
border: 1px solid;
border-radius: 2px;
padding: 1px 5px;
min-width: 28px;
text-align: center;
opacity: 0.9;
font-family: 'IBM Plex Mono', monospace;
}
.linkLabel {
font-size: 12px;
color: var(--text-mid);
font-family: 'IBM Plex Mono', monospace;
}
.linkArrow {
font-size: 11px;
opacity: 0.6;
transition: opacity 0.15s, transform 0.15s;
}
.link:hover .linkArrow {
opacity: 1;
transform: translate(2px, -2px);
}
/* ── Authors ── */
.authors {
margin-bottom: 8px;
}
.authorRow {
display: flex;
flex-direction: row;
gap: 8px;
padding-left: 36px;
margin-top: 6px;
flex-wrap: wrap;
}
/* ── Author tile ── */
.authorTile {
display: flex;
align-items: center;
gap: 10px;
background: var(--bg3);
border: 1px solid var(--border);
border-radius: 6px;
padding: 8px 12px;
text-decoration: none;
cursor: pointer;
/* width is dynamic — grows with content */
width: max-content;
min-width: 140px;
position: relative;
overflow: hidden;
transition: border-color 0.2s, background 0.2s, transform 0.2s;
}
.authorTile::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0;
height: 2px;
background: var(--green);
opacity: 0;
transition: opacity 0.2s;
}
.authorTileActive::before,
.authorTile:hover::before {
opacity: 1;
}
.authorTileActive {
border-color: var(--green-dim);
background: rgba(57, 211, 83, 0.04);
}
.authorTile:hover {
border-color: var(--border2);
background: #161b22;
transform: translateY(-1px);
}
/* ── Author content ── */
.authorAvatar {
width: 32px;
height: 32px;
border-radius: 50%;
border: 1px solid var(--border2);
flex-shrink: 0;
}
.authorAvatarSkeleton {
width: 32px;
height: 32px;
border-radius: 50%;
background: var(--border2);
flex-shrink: 0;
animation: shimmer 1.5s ease infinite;
}
.authorInfo {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.authorName {
font-size: 12px;
font-weight: 500;
color: var(--text);
font-family: 'IBM Plex Sans', sans-serif;
white-space: nowrap;
}
.authorLogin {
font-size: 10px;
color: var(--blue);
font-family: 'IBM Plex Mono', monospace;
white-space: nowrap;
}
/* Bio — always reserves vertical height, width animates open */
.authorBio {
display: block;
font-size: 10px;
color: var(--text-dim);
font-family: 'IBM Plex Sans', sans-serif;
margin-top: 2px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
/* always reserve vertical space */
height: 14px;
/* collapsed horizontally */
width: 0;
opacity: 0;
transition: opacity 0.25s ease, width 0.3s ease;
}
.authorTileActive .authorBio,
.authorTile:hover .authorBio {
width: 200px;
opacity: 1;
}
/* Placeholder for loading/no-profile/no-bio states */
.authorBioPlaceholder {
height: 14px;
margin-top: 2px;
width: 0; /* never takes horizontal space, never expands */
}
.authorSkeleton {
height: 9px;
border-radius: 4px;
background: var(--border2);
animation: shimmer 1.5s ease infinite;
}
/* ── Cursor ── */
.cursor {
display: inline-block;
width: 8px;
height: 13px;
background: var(--green);
margin-left: 2px;
vertical-align: text-bottom;
animation: blink 1s step-end infinite;
}
/* ── Animations ── */
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
@keyframes shimmer {
0%, 100% { opacity: 0.4; }
50% { opacity: 0.8; }
}
@media (max-width: 600px) {
.body { padding: 20px; }
.links { padding-left: 20px; }
.authorRow { padding-left: 20px; }
}
-38
View File
@@ -1,38 +0,0 @@
// ─── Project Configuration ───────────────────────────────────
// This is the ONLY file that should differ between projects.
// Everything else in the pages app is generic.
// ─────────────────────────────────────────────────────────────
export const PROJECT_NAME = 'CustomNPC+'
export const REPO_OWNER = 'KAMKEEL'
export const REPO_NAME = 'CustomNPC-Plus'
export const LINKS = [
{
tag: 'GH',
label: 'github.com/KAMKEEL/CustomNPC-Plus',
href: 'https://github.com/KAMKEEL/CustomNPC-Plus',
color: '#e6edf3',
},
{
tag: 'DC',
label: 'discord.gg/94qmjEDxkp',
href: 'https://discord.gg/94qmjEDxkp',
color: '#5865f2',
},
{
tag: 'CF',
label: 'curseforge.com/minecraft/mc-mods/customnpc-plus',
href: 'https://www.curseforge.com/minecraft/mc-mods/customnpc-plus',
color: '#f16436',
},
{
tag: 'MR',
label: 'modrinth.com/mod/customnpc-plus',
href: 'https://modrinth.com/mod/customnpc-plus/',
color: '#1bd96a',
},
]
// GitHub usernames — profiles are fetched at runtime
export const AUTHORS = ['kamkeel', 'c0508383', 'bigguy345', 'somehussar']
-50
View File
@@ -1,50 +0,0 @@
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #080b0f;
--bg2: #0d1117;
--bg3: #131920;
--border: #1e2936;
--border2: #253040;
--green: #39d353;
--green-dim: #1a6b2a;
--amber: #f0a030;
--amber-dim: #7a4e10;
--blue: #58a6ff;
--blue-dim: #1a3a6b;
--text: #cdd9e5;
--text-dim: #636e7b;
--text-mid: #8b949e;
--red: #f85149;
}
html, body {
height: 100%;
background: var(--bg);
color: var(--text);
font-family: 'IBM Plex Mono', monospace;
overflow-x: hidden;
}
/* Scanlines */
body::after {
content: '';
position: fixed;
inset: 0;
background: repeating-linear-gradient(
0deg,
transparent,
transparent 2px,
rgba(0,0,0,0.025) 2px,
rgba(0,0,0,0.025) 4px
);
pointer-events: none;
z-index: 9999;
}
a { color: inherit; text-decoration: none; }
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: var(--bg2); }
::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-dim); }
-13
View File
@@ -1,13 +0,0 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { PROJECT_NAME } from './config'
import './index.css'
document.title = `${PROJECT_NAME} — Javadoc Index`
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
-94
View File
@@ -1,94 +0,0 @@
import { useState, useEffect } from 'react'
import { REPO_OWNER, REPO_NAME } from './config'
const BASE_PATH = `/${REPO_NAME}`
const API_BASE = `https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}`
// Cache bust on every page load — appends current timestamp to manifest URL
// so the browser never serves a stale manifest.json
async function fetchFromManifest() {
const bust = `?t=${Date.now()}`
const res = await fetch(`${BASE_PATH}/manifest.json${bust}`, {
cache: 'no-store', // tells browser not to cache this request at all
})
if (!res.ok) throw new Error('No manifest')
return res.json()
}
async function fetchFromGitHubAPI() {
const refRes = await fetch(`${API_BASE}/git/ref/heads/gh-pages`)
if (!refRes.ok) throw new Error('gh-pages branch not found')
const refData = await refRes.json()
const sha = refData.object.sha
const treeRes = await fetch(`${API_BASE}/git/trees/${sha}?recursive=1`)
if (!treeRes.ok) throw new Error('Could not fetch tree')
const treeData = await treeRes.json()
const commitsRes = await fetch(`${API_BASE}/commits?sha=gh-pages&per_page=100`)
const commits = commitsRes.ok ? await commitsRes.json() : []
const commitMap = {}
commits.forEach(c => {
const date = c.commit?.committer?.date || c.commit?.author?.date || ''
const hash = c.sha?.slice(0, 7) || ''
const msg = c.commit?.message || ''
const vMatch = msg.match(/releases\/([\d.]+)/)
if (vMatch) commitMap[`releases/${vMatch[1]}`] = { date, hash }
const eMatch = msg.match(/experimental\/([\w-]+)/)
if (eMatch) commitMap[`experimental/${eMatch[1]}`] = { date, hash }
})
const releaseDirs = new Set()
const experimentalDirs = new Set()
treeData.tree.forEach(item => {
if (item.type !== 'tree') return
const parts = item.path.split('/')
if (parts[0] === 'releases' && parts.length === 2) releaseDirs.add(parts[1])
if (parts[0] === 'experimental' && parts.length === 2) experimentalDirs.add(parts[1])
})
// Sort releases newest first, mark first as latest
const sortedReleases = [...releaseDirs]
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
const releases = sortedReleases.map((v, i) => {
const c = commitMap[`releases/${v}`] || {}
return {
id: v,
version: v,
path: `releases/${v}`,
date: c.date,
hash: c.hash,
isLatest: i === 0, // newest version is always latest
}
})
const experimental = [...experimentalDirs].sort().map(b => {
const c = commitMap[`experimental/${b}`] || {}
return { id: b, branch: b, path: `experimental/${b}`, date: c.date, hash: c.hash }
})
return { releases, experimental, source: 'api' }
}
export function useDocs() {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState(null)
useEffect(() => {
fetchFromManifest()
.then(d => { setData(d); setLoading(false) })
.catch(() =>
fetchFromGitHubAPI()
.then(d => { setData(d); setLoading(false) })
.catch(e => { setError(e.message); setLoading(false) })
)
}, [])
return { data, loading, error }
}
export { BASE_PATH, REPO_OWNER, REPO_NAME }
-12
View File
@@ -1,12 +0,0 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { REPO_NAME } from './src/config.js'
export default defineConfig({
plugins: [react()],
base: `/${REPO_NAME}/`,
build: {
outDir: '../../.github/pages-dist',
emptyOutDir: true,
}
})
-18
View File
@@ -1,18 +0,0 @@
#!/bin/bash
# -----------------------------------------------
# doc-config.sh — shared config for javadoc deploy
#
# Sourced by:
# - resolve-doc-path.sh
# - javadoc.yml (via sanity-check job)
#
# ADD WHITELISTED BRANCHES HERE AND NOWHERE ELSE.
# main is always handled automatically.
# -----------------------------------------------
MAIN_BRANCH_NAME="master"
EXPERIMENTAL_WHITELIST=(
"dev"
# "new-branch"
)
-107
View File
@@ -1,107 +0,0 @@
#!/bin/bash
set -e
RELEASES=()
EXPERIMENTAL=()
# Collect releases
if [ -d "./releases" ]; then
for dir in ./releases/*/; do
[ -d "$dir" ] || continue
name=$(basename "$dir")
RELEASES+=("$name")
done
fi
# Collect experimental branches
if [ -d "./experimental" ]; then
for dir in ./experimental/*/; do
[ -d "$dir" ] || continue
name=$(basename "$dir")
EXPERIMENTAL+=("$name")
done
fi
# Sort releases in reverse semver order (newest first)
if [ ${#RELEASES[@]} -gt 0 ]; then
IFS=$'\n' RELEASES=($(sort -rV <<< "${RELEASES[*]}")); unset IFS
fi
# ── Store source commit metadata for this deploy ───────────────
# DEPLOY_PATH, SOURCE_HASH, SOURCE_DATE are passed in as env vars from the workflow
if [ -n "$DEPLOY_PATH" ] && [ -n "$SOURCE_HASH" ]; then
mkdir -p ".doc-meta"
META_KEY="${DEPLOY_PATH//\//_}"
cat > ".doc-meta/${META_KEY}.json" << JSON
{"hash":"${SOURCE_HASH}","date":"${SOURCE_DATE}"}
JSON
echo "Stored source metadata for $DEPLOY_PATH → $SOURCE_HASH @ $SOURCE_DATE"
fi
# ── Helper: get source commit hash + date for a path ──────────
get_commit_info() {
local path="$1"
# If this is the path we just deployed, use the injected source commit
if [ "$path" = "$DEPLOY_PATH" ] && [ -n "$SOURCE_HASH" ]; then
echo "${SOURCE_HASH} ${SOURCE_DATE}"
return
fi
# Try reading from stored metadata file (set by previous deploys)
local meta=".doc-meta/${path//\//_}.json"
if [ -f "$meta" ]; then
local hash date
hash=$(python3 -c "import json,sys; d=json.load(open('$meta')); print(d.get('hash',''))" 2>/dev/null || grep -o '"hash":"[^"]*"' "$meta" | cut -d'"' -f4)
date=$(python3 -c "import json,sys; d=json.load(open('$meta')); print(d.get('date',''))" 2>/dev/null || grep -o '"date":"[^"]*"' "$meta" | cut -d'"' -f4)
echo "${hash:-} ${date:-}"
return
fi
# Last resort: gh-pages git log (hash will be wrong but better than empty)
local hash date
hash=$(git log --oneline -1 -- "$path" 2>/dev/null | awk '{print $1}')
date=$(git log --format="%cI" -1 -- "$path" 2>/dev/null)
echo "${hash:-} ${date:-}"
}
# ── Build releases JSON ────────────────────────────────────────
RELEASES_JSON="["
for i in "${!RELEASES[@]}"; do
version="${RELEASES[$i]}"
read -r HASH DATE <<< "$(get_commit_info "releases/$version")"
if [ "$i" -eq 0 ]; then
IS_LATEST="true"
else
IS_LATEST="false"
fi
RELEASES_JSON+="{\"id\":\"${version}\",\"version\":\"${version}\",\"path\":\"releases/${version}\",\"date\":\"${DATE}\",\"isLatest\":${IS_LATEST}},"
done
RELEASES_JSON="${RELEASES_JSON%,}]"
# ── Build experimental JSON ────────────────────────────────────
EXPERIMENTAL_JSON="["
for branch in "${EXPERIMENTAL[@]}"; do
read -r HASH DATE <<< "$(get_commit_info "experimental/$branch")"
EXPERIMENTAL_JSON+="{\"id\":\"${branch}\",\"branch\":\"${branch}\",\"path\":\"experimental/${branch}\",\"hash\":\"${HASH}\",\"date\":\"${DATE}\"},"
done
EXPERIMENTAL_JSON="${EXPERIMENTAL_JSON%,}]"
# ── Write manifest.json ────────────────────────────────────────
cat > manifest.json << JSON
{
"releases": ${RELEASES_JSON},
"experimental": ${EXPERIMENTAL_JSON},
"generated": "$(date -u '+%Y-%m-%dT%H:%M:%SZ')",
"source": "manifest"
}
JSON
echo "manifest.json generated:"
cat manifest.json
echo ""
echo "Done."
-52
View File
@@ -1,52 +0,0 @@
#!/bin/bash
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/doc-config.sh"
BRANCH="${GITHUB_REF#refs/heads/}"
SAFE_BRANCH="${BRANCH//\//-}"
if [ "$BRANCH" = "$MAIN_BRANCH_NAME" ]; then
# Version resolution order:
# -> check if gradle.properties has a `modVersion` tag. If it does, just grab it.
# -> check if it has the `version` tag. Grab it if it does
# -> check build.gradle for the version tag.
if [ -f "gradle.properties" ] && grep -q "^modVersion=" gradle.properties; then
VERSION=$(grep "^modVersion=" gradle.properties | cut -d'=' -f2 | tr -d '[:space:]')
elif [ -f "gradle.properties" ] && grep -q "^version=" gradle.properties; then
VERSION=$(grep "^version=" gradle.properties | cut -d'=' -f2 | tr -d '[:space:]')
elif [ -f "build.gradle" ]; then
VERSION=$(grep "^version" build.gradle | head -1 | sed "s/version\s*=\s*['\"]//;s/['\"].*//;s/\s//g")
elif [ -f "build.gradle.kts" ]; then
VERSION=$(grep "^version" build.gradle.kts | head -1 | sed "s/version\s*=\s*\"//;s/\".*//;s/\s//g")
else
echo "Could not find version. Defaulting to 'unknown'."
VERSION="unknown"
fi
echo "Resolved version: $VERSION"
# Only deploy to releases/<version> — isLatest is handled by generate-index.sh
echo "path=releases/$VERSION" >> $GITHUB_OUTPUT
echo "extra_path=" >> $GITHUB_OUTPUT
else
MATCHED=false
for ALLOWED in "${EXPERIMENTAL_WHITELIST[@]}"; do
if [ "$BRANCH" = "$ALLOWED" ]; then
MATCHED=true
break
fi
done
if [ "$MATCHED" = true ]; then
echo "path=experimental/$SAFE_BRANCH" >> $GITHUB_OUTPUT
echo "extra_path=" >> $GITHUB_OUTPUT
echo "Branch '$BRANCH' is whitelisted, deploying to experimental/$SAFE_BRANCH"
else
echo "path=" >> $GITHUB_OUTPUT
echo "extra_path=" >> $GITHUB_OUTPUT
echo "Branch '$BRANCH' is not whitelisted. Skipping deploy."
fi
fi
+2 -2
View File
@@ -24,8 +24,8 @@ jobs:
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Initialize submodules - name: Initialize CNPC+ API submodule
run: git submodule update --init --recursive run: git submodule update --init --recursive src/api
- name: Checkout workflows repo - name: Checkout workflows repo
uses: actions/checkout@v4 uses: actions/checkout@v4
-224
View File
@@ -1,224 +0,0 @@
name: Generate and Deploy Javadoc
on:
push:
branches:
- master
- '**'
delete:
workflow_dispatch:
inputs:
force_deploy:
description: 'Force redeploy Javadocs without a new commit'
required: false
default: 'true'
jobs:
sanity-check:
runs-on: ubuntu-latest
outputs:
should_deploy: ${{ steps.deploy_check.outputs.should_deploy }}
steps:
- uses: actions/checkout@v4
- name: Check for deploy tag
id: deploy_check
run: |
source .github/scripts/doc-config.sh
BRANCH="${GITHUB_REF#refs/heads/}"
# Always deploy on manual trigger
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "should_deploy=true" >> $GITHUB_OUTPUT
echo "Reason: workflow_dispatch"
exit 0
fi
# Main branch: only deploy if commit message contains [deploy-docs]
if [ "$BRANCH" = "$MAIN_BRANCH_NAME" ]; then
if echo "${{ github.event.head_commit.message }}" | grep -q "\[deploy-docs\]"; then
echo "should_deploy=true" >> $GITHUB_OUTPUT
echo "Reason: master branch with [deploy-docs] tag"
else
echo "should_deploy=false" >> $GITHUB_OUTPUT
echo "Reason: master branch without [deploy-docs] tag, skipping"
fi
exit 0
fi
# Experimental branches: only deploy if whitelisted
for ALLOWED in "${EXPERIMENTAL_WHITELIST[@]}"; do
if [ "$BRANCH" = "$ALLOWED" ]; then
echo "should_deploy=true" >> $GITHUB_OUTPUT
echo "Reason: branch '$BRANCH' is whitelisted"
exit 0
fi
done
echo "should_deploy=false" >> $GITHUB_OUTPUT
echo "Reason: branch '$BRANCH' is not whitelisted, skipping"
build-and-deploy-javadoc:
needs: sanity-check
if: needs.sanity-check.outputs.should_deploy == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout source branch
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Initialize submodules
run: git submodule update --init --recursive
- name: Setup JDK 8 (compile)
uses: actions/setup-java@v4
with:
java-version: '8'
distribution: 'temurin'
- name: Set up JDK 8 (Zulu)
uses: actions/setup-java@v4
with:
java-version: '8'
distribution: 'zulu'
- name: Setup JDK 11 (javadoc)
uses: actions/setup-java@v4
with:
java-version: '11'
distribution: 'temurin'
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Extract convention plugin version
id: convention
run: |
VERSION=$(grep "id 'com.gtnewhorizons.gtnhsettingsconvention'" settings.gradle settings.gradle.kts 2>/dev/null | grep -o "version '[0-9]\+\.[0-9]\+\.[0-9]\+'" | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+')
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "Detected convention version: $VERSION"
- name: Get source commit info
id: source_commit
run: |
echo "hash=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
echo "date=$(git log -1 --format='%cI')" >> $GITHUB_OUTPUT
- name: Cache Gradle wrapper
uses: actions/cache@v4
with:
path: ~/.gradle/wrapper
key: gradle-wrapper-${{ hashFiles('**/gradle-wrapper.properties') }}
- name: Cache Gradle dependencies
uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/caches/modules-*
~/.gradle/caches/jars-*
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', '**/gradle.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Cache RFG
uses: actions/cache@v4
with:
path: |
build/rfg
build/tmp/.cache/expanded
build/tmp/deobfuscateMergedJarToSrg
key: ${{ runner.os }}-rfg-convention${{ steps.convention.outputs.version }}
restore-keys: |
${{ runner.os }}-rfg-
- name: Cache Node modules
uses: actions/cache@v4
with:
path: .github/pages/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('.github/pages/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Generate Javadoc
run: ./gradlew javadoc
- name: Get deploy path
id: deploy_path
run: bash .github/scripts/resolve-doc-path.sh
- name: Deploy to gh-pages
if: steps.deploy_path.outputs.path != ''
uses: peaceiris/actions-gh-pages@v4
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./build/docs/javadoc
destination_dir: ${{ steps.deploy_path.outputs.path }}
keep_files: true
# Give GitHub a moment to settle after the peaceiris push
- name: Wait for gh-pages to settle
run: sleep 10
- name: Checkout gh-pages
uses: actions/checkout@v4
with:
ref: gh-pages
path: gh-pages-index
- name: Generate manifest
run: |
cd gh-pages-index
SOURCE_HASH="${{ steps.source_commit.outputs.hash }}" \
SOURCE_DATE="${{ steps.source_commit.outputs.date }}" \
DEPLOY_PATH="${{ steps.deploy_path.outputs.path }}" \
bash ../.github/scripts/generate-index.sh
- name: Install page dependencies
run: npm ci --prefix .github/pages
- name: Build index page
run: |
mkdir -p .github/pages/public
cp gh-pages-index/manifest.json .github/pages/public/manifest.json
npm run build --prefix .github/pages
- name: Deploy index to gh-pages
run: |
cp -r .github/pages-dist/* gh-pages-index/
cd gh-pages-index
git config user.name "github-actions"
git config user.email "[email protected]"
git add -A
git commit -m "Regenerate index and manifest [skip ci]" || echo "Unchanged"
git push
cleanup-on-delete:
if: github.event_name == 'delete' && github.event.ref_type == 'branch'
runs-on: ubuntu-latest
steps:
- name: Checkout gh-pages
uses: actions/checkout@v4
with:
ref: 'gh-pages'
- name: Remove deleted branch docs
run: |
BRANCH="${{ github.event.ref }}"
SAFE="experimental/${BRANCH//\//-}"
if [ -d "./$SAFE" ]; then
rm -rf "./$SAFE"
META_KEY="${SAFE//\//_}"
rm -f ".doc-meta/${META_KEY}.json"
git config user.name "github-actions"
git config user.email "[email protected]"
git add -A
git commit -m "Remove docs for deleted branch: $BRANCH"
git push
else
echo "No docs found for $SAFE, skipping."
fi
-2
View File
@@ -45,6 +45,4 @@ src/main/resources/assets/customnpcs/api
df/ df/
tmp/ tmp/
src/test src/test
node_modules
.github/pages-dist
+58
View File
@@ -0,0 +1,58 @@
# CNPC+ 1.11 Beta - The Scripting Update
🟡 **In Testing**
## Scripting:
- **Syntax Highlighting:**
> Full color-coded script editor. Keywords, types, variables, methods, strings, and comments are all distinct. Scope-aware coloring distinguishes local fields from globals and chained method calls.
- **Autocomplete:**
> Smart suggestions as you type. Context-aware for static vs instance access, shows method parameters, resolves chained calls, and suggests auto imports for classes. Frequently used members prioritized.
- **Error Detection:**
> Catch mistakes before running. Type mismatches, wrong arguments, missing methods, unused imports, duplicate definitions, and more -- all underlined with hover messages explaining the issue.
- **Hover Information:**
> Hover any symbol to see its type, documentation, and declaration. Works on methods, fields, classes, and even generics. Click to pin tooltips in place.
- **Script Editor Overhaul:**
> - **Line Numbers** - Gutter with current line highlighting.
> - **Go To Line** - CTRL+G to jump to any line.
> - **Search & Replace** - CTRL+F / CTRL+H with real-time highlighting.
> - **Go To Definition** - CTRL+Click to jump to any symbol.
> - **Smart Undo/Redo** - Word-level instead of character-level.
> - **Line Operations** - Duplicate, delete, move up/down.
> - **Comment Toggle** - CTRL+/ for selected lines.
> - **Rename** - Rename a symbol across all occurrences.
> - **Smooth Scrolling** - Eased scroll animation.
> - **Indent Guides** - Scope-highlighted vertical indent lines.
> - **Brace Matching** - Highlighted pairs, red for unclosed.
> - **Smart Brackets** - Auto-pairing for `{}`, `()`, `[]`, `""`, `''`.
> - **Fullscreen Mode** - Expand editor to fill the game window.
> - **Shortcut Overlay** - View all keyboard shortcuts at a glance.
- **Java Scripting (Janino):**
> Write scripts in real Java compiled at runtime. Name methods after hooks for automatic wiring. Language selector per tab to switch between Java and JavaScript. External `.java` file support.
- **Client-Side Scripting:**
> Run scripts on the client for responsive experiences. Server-controlled -- off by default, must be explicitly enabled. Script files sync automatically on login and reload.
- **Cloner Tab Overhaul:**
> Folder-based organization for saved NPCs, items, and entries. Full-width directory browser for large collections. Improved tab navigation.
- **Animation Improvements:**
> Data store for passing data across animation events and frames. New consumer-based task system for animation lifecycle. Expanded scripting API for animation control.
**Extras**
- Player Dialog Events now work like NPC Dialog Events.
- Attack speed configuration for linked items.
- Client-side balance prediction during Trader interactions.
- Right-click cycling on multi-option NPC buttons (Hair, Eyes, Fur, etc.).
- Fixed quest cooldown for MC Custom and RL Custom timer types.
- Fixed Bard music restarting when opening dialogs.
- Fixed NPC biome spawn settings not saving after editing.
- Fixed block waypoint issues.
- Fixed script config syncing between server and client.
+118
View File
@@ -0,0 +1,118 @@
# ✏️ CustomNPC+ 1.11 - The Scripting Update ✏️
---
The **Scripting Update** completely transforms how you write scripts in CNPC+! A brand new **Script Editor** with **syntax highlighting**, **autocomplete**, and **error detection** makes scripting feel like a real IDE. Write scripts in **Java** with the new Janino engine, enable **client-side scripting** for responsive experiences, and organize your Cloner with **folders**!
---
## Script Editor 📝
The script editor has been rebuilt from the ground up into a **full-featured code editor** right inside Minecraft.
### Writing Code
- **Syntax Highlighting** - Keywords, types, variables, methods, strings, and comments are all color-coded automatically. The editor understands your code -- local variables, global fields, and chained method calls each get their own color
- **Autocomplete** - Start typing and get smart suggestions for methods, fields, and classes. Suggestions know whether you're in a static or instance context, and frequently used members appear first
- **Auto Imports** - Type a class name and the editor suggests the correct import for you
- **Error Detection** - Catch mistakes before you even run your script! Wrong argument types, missing methods, type mismatches, unused imports, and more are all underlined with detailed error messages on hover
> Hover over any symbol to see its **full type information**, documentation, and declaration -- just like a desktop IDE.
---
### Navigation
- **Go To Line** - `CTRL+G` jumps to any line instantly
- **Search & Replace** - `CTRL+F` to search, `CTRL+H` to replace. All matches highlight in real-time
- **Go To Definition** - `CTRL+Click` any method, field, or type to jump straight to its definition
- **Fullscreen Mode** - Expand the editor to fill your entire game window for maximum workspace
### Editing
- **Undo/Redo** - Smart undo that works on whole words at a time, not individual characters
- **Line Operations** - Duplicate lines with `CTRL+D`, delete lines, and move lines up or down with shortcuts
- **Comment Toggle** - `CTRL+/` to comment or uncomment selected lines
- **Rename** - Rename a variable or method and every occurrence updates at once
- **Copy Whole Line** - Copy with nothing selected grabs the entire line
- **Triple Click** - Select an entire line instantly
### Visual Polish
- **Line Numbers** - A clean gutter with line numbers and current line highlighting
- **Smooth Scrolling** - Eased scroll animations for a polished feel
- **Indent Guides** - Vertical lines show your code's nesting depth, with the current scope highlighted in green
- **Brace Matching** - Matching `{}` braces light up, and unclosed braces turn red
- **Smart Brackets** - Typing `{` automatically creates the closing `}` with correct indentation. Same for `()`, `[]`, `""`, and `''`
- **Keyboard Shortcut Overlay** - Press a button to see all available shortcuts at a glance
---
## Java Scripting ☕
Write scripts in **real Java** instead of JavaScript! Powered by the **Janino** compiler, your Java code is compiled and runs natively.
- **Full Java Language** - Use classes, interfaces, enums, generics, lambdas, and everything you know from Java
- **Automatic Hook Resolution** - Just name your methods after the hook you want (e.g., `init`, `tick`, `interact`) and they're wired up automatically
- **Language Selector** - Each script tab has a dropdown to choose between JavaScript and Java. Mix and match across tabs
- **External Files** - Write `.java` scripts in an external editor and they're loaded automatically
> Java and JavaScript scripts coexist side by side. Pick whichever language fits your workflow!
---
## Client-Side Scripting 🖥️
Scripts can now run **on the client** for responsive, visual experiences!
- **Server Controlled** - Server owners decide whether client scripting is allowed. Players can't enable it on their own
- **Automatic Sync** - Script files are sent from the server to all connected clients on login, and re-synced whenever scripts are reloaded
- **Safe by Default** - Client scripting is off by default and must be explicitly enabled in the server config
> Client-side scripts open the door to custom UI effects, visual feedback, and client-only hooks -- all while the server stays in full control.
---
## Cloner Tab Overhaul 📂
The Cloner now supports **folders** for organizing your saved NPCs, items, and entries!
- **Folder System** - Create folders and subfolders to keep your cloner organized however you like
- **Full Screen Browser** - A new full-width directory view makes browsing large collections much easier
- **Improved Tabs** - Better tab navigation for switching between cloner categories
---
## Addon API Support 📘
Addon developers can now ship **type definitions** alongside their mods, giving scripters full autocomplete and documentation for addon APIs!
- **Automatic Loading** - Any mod can include API definitions and they'll appear in the script editor automatically
- **Patch Support** - Addons can extend existing CNPC+ types with new methods (e.g., a DBC addon adding `getDBCPlayer()` to the Player type)
- **Full Documentation** - Parameter names, return types, and descriptions all show up in autocomplete and hover info
> If you're a scripter using addons, you get autocomplete for their APIs with zero setup. If you're an addon developer, just include your definitions and everything works.
---
## Animation Improvements 🎬
- **Data Store** - Animations can now store and pass data across events and frames for more complex animation logic
- **Task System** - A new consumer-based system for reacting to animation lifecycle events, replacing the old approach
- **Expanded API** - More animation control exposed to the scripting API
---
## Additional Changes 🔧
- **Player Dialog Events** - Now work the same way as NPC Dialog Events for consistency
- **Linked Item Attack Speed** - Added attack speed configuration to linked items
- **Trader Balance Preview** - Client-side balance prediction shows your expected balance during trades
- **Right-Click Cycling** - Multi-option NPC buttons (Hair, Eyes, Fur, etc.) can now be right-clicked to cycle backwards
- **Quest Cooldown Fix** - Fixed cooldown not working for MC Custom and RL Custom timer types
- **Bard Music Fix** - Fixed music restarting or duplicating when opening dialogs
- **Biome Spawn Fix** - Fixed NPC biome spawn settings not saving after editing
- **Block Waypoint Fix** - Fixed issues with block waypoints
- **Script Config Fix** - Fixed script configuration not syncing properly between server and client
---
+81
View File
@@ -0,0 +1,81 @@
# CNPC+ 1.11 Ability System Beta
🟡 **In Testing**
## Ability Update: ⚒️
- **Phase-Based Execution:**
> All abilities follow a Wind-up → Active → Completion flow. Wind-up lets players react, Active deals the effect.
- **Melee Abilities:**
> - **Slam** - Leap and AOE on impact.
> - **Heavy Hit** - Single powerful strike with bonus knockback.
> - **Cutter** - Slashing cone arc attack.
> - **Shockwave** - AOE burst radiating from the caster.
- **Energy Orbs:**
> - **Orb** - Homing energy sphere.
> - **Dual Orb** - Two simultaneous homing orbs.
> - **Orb Barrage** - Rapid volley of orbs in sequence.
- **Energy Discs:**
> - **Disc** - Spinning flat projectile with optional boomerang.
> - **Dual Disc** - Two simultaneous discs.
- **Energy Beams:**
> - **Beam** - Sustained homing beam from caster to target.
> - **Dual Beam** - Two simultaneous beams.
- **Laser Shot:**
> Instant-fire projectile with no homing. Pure aim.
- **Projectile:**
> Standard projectile using classic Minecraft physics.
- **Movement Abilities:**
> - **Charge** - Rush forward in a line, damaging everything in path.
> - **Dash** - Quick directional movement without damage.
> - **Teleport** - Instant relocation to the target.
- **AOE Abilities:**
> - **Sweeper** - Wide rotational sweep around the caster.
> - **Vortex** - Pulls entities inward while dealing damage.
- **Telegraph System:**
> Visual ground indicators during wind-up. Supports Circle, Ring, Line, Cone, and Point shapes with color customization and warning phase transitions.
- **Energy Projectile Customization:**
> Modular data system for all energy projectiles: Anchor Point, Display Colors, Homing, Combat Stats, and Lifespan.
- **Ability Effects:**
> Abilities can apply potion effects on hit: Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue.
- **Ability Conditions:**
> Condition system controlling when abilities can execute based on target state and custom predicates.
- **Interruptible Wind-ups:**
> Abilities can be interrupted by damage during wind-up, forcing a configurable Dazed recovery state.
- **Movement & Rotation Locking:**
> Lock caster movement, rotation, or both during Wind-up, Active, or both phases.
- **Animation & Sound Integration:**
> Wind-up and Active animations with optional duration sync. Custom sound events per phase.
- **Player Abilities:**
> Players can unlock abilities, select one at a time, and share a universal cooldown.
- **Ability Preview:**
> Live preview in the ability editor GUI. Test telegraphs, animations, and projectiles on a dummy NPC.
- **Scripting API:**
> Full event support: Start, Execute, Interrupt, Complete, Hit (modifiable damage/knockback), and Tick events. Start, Execute, and Hit are cancelable.
- **Ability Commands:**
> `/kam ability list`, `types`, `info`, `delete`, `reload` for managing custom abilities.
**Extras**
- Global ability presets that update everywhere when edited.
- Weighted ability selection for NPC random usage.
- Configurable min/max range per ability.
- Reusable telegraph presets shared across abilities.
+199
View File
@@ -0,0 +1,199 @@
# ⚔️ CustomNPC+ 1.11 - Abilities ⚔️
---
The **Ability Update** introduces a full combat ability system to CNPC+! Give your NPCs powerful attacks with **visual telegraphs**, launch **energy projectiles** that home in on targets, and let players unlock abilities of their own!
---
## How Abilities Work 🎯
Every ability follows a **phase-based execution flow** that gives combat a readable, strategic feel.
**Phases:**
- **Wind-up** - The ability charges. Telegraphs appear, animations play, and observant players can react
- **Active** - The ability fires. Damage is dealt, projectiles launch, effects apply
- **Dazed** - Optional recovery state if the ability is interrupted during wind-up
**Core Configuration:**
- **Cooldown** - Time before the ability can be used again
- **Targeting Mode** - Aggro Target, Self, AOE on Self, or AOE on Target
- **Range** - Configurable min and max range for activation
- **Lock Movement** - Lock the caster's movement, rotation, or both during any phase
- **Interruptible** - Allow damage to interrupt wind-up and force a dazed state
- **Weight** - Priority weighting for NPC random ability selection
> Abilities support both **inline configuration** on individual NPCs and **global presets** that update everywhere when edited.
---
## Melee Abilities 🗡️
Close-range attacks that hit hard and punish positioning.
- **Slam** - Leap toward the target in an arc, dealing AOE damage on impact. Configurable radius, knockback, and leap height
- **Heavy Hit** - A single powerful melee strike with bonus knockback
- **Cutter** - A slashing arc attack in a cone. Configurable angle and reach
- **Shockwave** - An AOE burst radiating outward from the caster
> All melee abilities support configurable **damage**, **knockback**, and **potion effects** on hit.
---
## Energy Projectiles ✨
A brand new projectile system built from the ground up with full visual customization.
### Orbs
Homing energy spheres that track their target through the air.
- **Orb** - A single homing projectile
- **Dual Orb** - Fires two orbs simultaneously
- **Orb Barrage** - Fires a volley of orbs in rapid sequence
### Discs
Flat spinning projectiles with optional **boomerang** behavior.
- **Disc** - A single spinning disc with configurable radius and thickness
- **Dual Disc** - Fires two discs simultaneously
### Beams
Sustained energy beams that connect the caster to their target.
- **Beam** - A homing beam with configurable width and head size. Locks the caster in place during channeling
- **Dual Beam** - Fires two beams simultaneously
### Laser Shot
An **instant-fire** projectile with configurable width and speed. No homing — pure aim.
### Projectile
A standard projectile using classic Minecraft physics for a more traditional ranged attack.
### Energy Configuration
Every energy projectile shares a **modular data system** for deep customization:
- **Anchor Point** - Choose where the projectile spawns: Right Hand, Left Hand, Front, Center, Chest, or Above Head
- **Display** - Set core color, edge color, glow effect, transparency, and size
- **Homing** - Toggle homing, adjust turn rate and max tracking range
- **Combat** - Damage, knockback, vertical knockback, hit cooldown, and optional AOE splash
- **Lifespan** - Projectile speed, max age, and max travel distance
---
## Movement Abilities 💨
Abilities that reposition the caster in combat.
- **Charge** - Rush forward in a line, damaging all entities in the path. Configurable speed, hit width, and knockback
- **Dash** - A quick directional movement without dealing damage
- **Teleport** - Instantly relocate to the target's position
> **Charge** locks direction during wind-up, so the telegraph accurately shows the attack path.
---
## AOE Abilities 🌀
Area control abilities that dominate space.
- **Sweeper** - A wide rotational sweep attack around the caster with configurable radius and rotation speed
- **Vortex** - Creates a pulling force that drags nearby entities toward the center while dealing damage
---
## Telegraph System 📍
**Telegraphs** are visual ground indicators that warn players before an ability lands. They appear during the wind-up phase and disappear when the ability fires.
**Shapes:**
- **Circle** - Filled circle with configurable radius
- **Ring** - Donut shape with inner and outer radius
- **Line** - Rectangle along the attack direction
- **Cone** - Fan/wedge shape with configurable angle
- **Point** - Single point indicator
**Features:**
- **Color Customization** - Set ARGB colors for both the telegraph and its warning phase
- **Warning Phase** - Color shifts in the final ticks before the ability fires
- **Entity Tracking** - Telegraphs can follow a moving entity or stay at a fixed position
- **Smooth Interpolation** - Position updates are interpolated for clean visuals
> Telegraphs are saved as **reusable presets** and can be shared across multiple abilities.
---
## Animations & Sound 🎬
Abilities integrate directly with the animation and sound systems.
- **Wind-up Animation** - Plays during the charging phase
- **Active Animation** - Plays when the ability fires
- **Animation Sync** - Optionally sync wind-up duration to match animation length exactly
- **Sound Events** - Assign custom sounds to both wind-up and active phases
- **Phase Colors** - Visual color feedback on the caster during wind-up and active
> Many ability types include **built-in animation names** that work automatically when matching animations exist.
---
## Effects & Conditions ⚡
### Potion Effects
Abilities can apply **potion effects** to any entity they hit. Each effect has configurable type, duration, and amplifier.
**Available Effects:**
Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue
### Conditions
Abilities support a **condition system** that controls when they can be used. Conditions are evaluated before execution and can require specific target states, ranges, or custom predicates.
---
## Player Abilities 🧑
Players can unlock and use abilities too!
- **Unlock System** - Players receive abilities via scripting or commands
- **Ability Selection** - Choose one ability at a time from your unlocked list
- **Universal Cooldown** - Shared cooldown across all player abilities
---
## Scripting API 📜
Full scripting support for ability lifecycle events:
- **StartEvent** *(Cancelable)* - Fired when wind-up begins
- **ExecuteEvent** *(Cancelable)* - Fired when the ability activates
- **InterruptEvent** - Fired when wind-up is interrupted by damage
- **CompleteEvent** - Fired when the ability finishes
- **HitEvent** *(Cancelable)* - Fired on each entity hit. Damage and knockback values can be modified
- **TickEvent** - Fired every tick with current phase and tick count
> Scripts can cancel, modify damage, and react to every phase of ability execution.
---
## Ability Preview 🔎
The ability editor includes a **live preview system**. Test your telegraph shapes, animations, and projectile visuals directly in the GUI on a dummy NPC — no world effects applied.
---
## Ability Commands 💬
- `/kam ability list` - List all custom abilities
- `/kam ability types` - List all registered ability types
- `/kam ability info <name|uuid>` - View ability details
- `/kam ability delete <uuid>` - Delete a custom ability
- `/kam ability reload` - Reload abilities from disk
---
+54
View File
@@ -0,0 +1,54 @@
# CNPC+ 1.11 Beta - Market Update
## Auction Features: ⚒️
- **Built-in Currency System:**
> Fully configurable economy currency used across all Market features. Profile persistent across character slots with Vault support for Bukkit-compatible plugins.
- **Auction House:**
> Global player marketplace for listing items, bidding, and instant buyouts. Auctions last 24 hours by default.
- **Auction Bidding & Snipe Protection:**
> Competitive bidding with a 5% minimum bid increment. Snipe Protection extends auctions on last-second bids. Outbid players are automatically refunded.
- **Buyout System:**
> Instant purchase at the seller's Buyout Price. Highest bidder only pays the difference between their bid and the buyout.
- **My Trades:**
> Single screen for managing Active Listings, Active Bids, and Pending Claims. Players can cancel listings with a 10% penalty if bids exist.
- **Auction Notifications:**
> Real-time notifications for sales, outbids, and wins. Offline players receive a claim summary on login.
- **Trade Slots:**
> Limited slots (default 8, max 45) shared across listings, bids, and claims. Configurable via permissions.
- **Claim Expiration:**
> Uncollected claims expire after 20 days.
- **Item Blacklist:**
> Block items by registry name, wildcard pattern, mod, or NBT tag. Soulbound and Profile-Slotbound items are always blocked automatically.
- **Listing Fee & Sales Tax:**
> Configurable listing fee charged on creation and sales tax taken from successful sales.
- **Search & Sorting:**
> Search by item name or seller. Sort by newest, ending soon, price, or most bids.
- **Trader Stock System:**
> Limited stock with Global or Per-Player modes. Restock timers for MC Daily/Weekly, RL Daily/Weekly, or Custom intervals.
- **Trader Currency Trades:**
> Trades can require currency on top of item costs.
- **Auctioneer NPC Role:**
> New role that opens the Auction House on interaction. No configuration needed.
- **Auction Commands:**
> `/kam auction open` for players. Admin commands for listing view and player activity inspection.
**Extras**
- Auction logging for server admins (tracks creates, bids, buyouts, sales, expirations, cancellations, claims).
- Lifetime currency tracking per player (total earned and spent).
- Configurable starting balance and max balance cap.
- Blacklist bypass permission for admins.
+121
View File
@@ -0,0 +1,121 @@
# 🏪 CustomNPC+ 1.11 - Market Update 🏪
---
The **Market Update** brings a complete economy system to CNPC+! Create bustling marketplaces with **Traders** that have limited stock, or let players trade with each other through the brand new **Auction House**!
---
## Currency System 💰
CNPC+ now has a **built-in currency** used across all Market features!
- **Fully Configurable** - Name it Coins, Gold, Credits, whatever fits your world. Set a starting balance and max balance cap to shape your economy
- **Profile Persistent** - Currency carries across all your character slots
- **Vault Support** - Integrates seamlessly with Bukkit-compatible economy plugins if Vault is installed. Falls back to built-in currency otherwise
- **Lifetime Tracking** - Tracks total earned and spent per player
> Full Scripting API support for currency operations on players.
---
## Auction House 🏛️
A **global player marketplace** where players can list items, bid against each other, and purchase instantly! Search for items by name or seller, and sort by newest, ending soon, price, or most bids.
### Selling
List any item with a **Starting Price** for competitive bidding. Set an optional **Buyout Price** for players who want to skip the wait and buy immediately. Auctions last **24 hours** by default.
> A configurable **Listing Fee** is charged when creating auctions, and a **Sales Tax** is taken from successful sales.
### Bidding
Compete for items by placing bids! Each bid must be at least **5%** higher than the current bid. **Snipe Protection** extends auctions when last-second bids come in, giving everyone a fair shot. If you get outbid, your currency is **automatically refunded**.
### Buyout
See something you need right now? Hit **Buy Now** to purchase instantly at the seller's Buyout Price. If you're currently the highest bidder on an item, you only pay the **difference** between your bid and the buyout.
### My Trades
One screen to manage all your auction activity:
- **Active Listings** - Items you're currently selling
- **Active Bids** - Auctions you're competing in
- **Ready to Claim** - Won items and currency waiting for pickup
Players can **cancel** their own listings -- items are returned as a claim. If there are active bids on the listing, a **10% cancellation penalty** is charged.
> Claims expire after **20 days**. Make sure to collect your items and currency before they're gone!
### Notifications
Get notified immediately when your item sells, when you're outbid, or when you win an auction. Offline? You'll get a full **claim summary** when you log back in showing exactly what's waiting for you.
### Trade Slots
Every player gets a limited number of **Trade Slots** (default 8). Slots are shared across Active Listings, Active Bids, **and** Pending Claims -- so uncollected claims take up space. Pick up your claims to free slots for new listings and bids!
> Server owners can grant players more slots via permissions up to a maximum of 45.
---
## Item Blacklist 🚫
Server owners have full control over what items can be listed on the Auction House.
**Block by:**
- **Item** - Specific registry names like `minecraft:diamond_sword`
- **Wildcard** - Patterns like `minecraft:diamond*` to block all diamond items
- **Mod** - Block all items from a specific mod
- **NBT Tag** - Block items containing certain NBT data
> **Soulbound** and **Profile-Slotbound** items are always blocked automatically, regardless of blacklist settings. Bound items cannot be traded!
Manage the blacklist in-game with `/kam auction blacklist` commands, or configure it directly in the config file.
---
## Trader Enhancements 🛒
### Stock System
Traders now support **limited stock** with automatic restocking!
**Stock Modes:**
- **Global** - All players share the same stock pool
- **Per-Player** - Each player has their own purchase limits
**Restock Timers:**
- **MC Daily / Weekly** - Restock based on Minecraft time
- **RL Daily / Weekly** - Restock based on real-life time
- **Custom** - Set your own interval in MC ticks or real-time
Stock counts, out-of-stock status, and restock timers are all visible directly in the trade interface.
> Admins can manually reset stock or cooldowns via the Trader GUI.
### Currency Trades
Trades can now require **currency on top of items**. Combine material costs with coin costs for balanced economy progression!
---
## Auctioneer Role 🧑‍💼
New NPC role for the Auction House! Set the role on any NPC and players can access the full Auction House by interacting with them -- no extra configuration needed. The role respects the global Auction Enabled setting.
### Auction Commands
Players can also access the Auction House via command:
- `/kam auction open` - Opens the Auction House GUI
**Admin Commands:**
- `/kam auction list [page]` - View active auctions in chat
- `/kam auction view <player>` - View a player's auction activity
> Server owners can enable **auction logging** to track all auction activity (creates, bids, buyouts, sales, expirations, cancellations, and claims).
---
-98
View File
@@ -1,98 +0,0 @@
# CustomNPC+ 1.11 Changelog
## Ability System
- Phase-based abilities (Wind-up, Active, Dazed) with configurable cooldowns, targeting, range, interrupts, invulnerability, and magic damage
- **Melee:** Slam, Heavy Hit, Cutter
- **Energy Projectiles:** Orb, Disc, Beam, Laser Shot with variant system, homing, hit types (Single/Pierce/Multi), size interpolation, explosions
- **Barriers:** Dome, Wall, Shield with HP, reflection, damage absorption
- **Defensive:** Guard, Counter, Dodge
- **Movement:** Charge, Dash, Teleport
- **AOE:** Shockwave, Sweeper, Vortex
- **Hazards & Traps:** Persistent zones and proximity triggers with visual presets
- **Effect:** Healing, buffs, debuffs with target filtering (Allies/Enemies/All)
- **Custom Ability:** Blank-slate type with full script hooks and toggle modes
- Burst system, chained ability combos with concurrency, telegraph system (6 shapes)
- Per-phase animations and sound events
- Ability conditions: HP Threshold, Hit Count, Has Item, Quest Completed, Has Effect
- 12-slot player ability hotbar with HUD editor
- Full scripting API for ability and energy projectile lifecycle events
- Ability Extender system for custom hooks
- Live preview in editor
- Commands: `/kam ability list|types|prebuilts|info|delete|reload|give|remove|giveChain|removeChain|player`
## Auction House
- Global marketplace with bidding, buyout, and snipe protection
- Built-in currency system (configurable, profile-persistent, Vault support)
- Listing fees, sales tax, minimum prices
- My Trades panel with claim management (20-day expiry)
- Search/sort, notifications (online + offline summary)
- Trade slots (default 8, expandable via permissions)
- Item blacklist (by item, wildcard, mod, NBT; soulbound always blocked)
- Auctioneer NPC role
- Admin GUI and logging
- Cancelable scripting events: Create, Bid, Buyout, Cancel, Claim
## Script Editor
- Full code editor with syntax highlighting, autocomplete, error detection, and hover tooltips
- Go to Line, Search/Replace, Go to Definition, Fullscreen
- Undo/Redo, Duplicate Line, Comment Toggle, Rename, Move Lines
- Line numbers, smooth scrolling, indent guides, brace matching, smart brackets
## Java Scripting
- Write scripts in Java via Janino compiler with automatic hook resolution
- Per-tab language selector (mix Java and JavaScript)
- External `.java` file support
## Client-Side Scripting
- Server-controlled client script execution with auto-sync (off by default)
## Addon API Support
- Ship `.d.ts` type definitions for automatic script editor autocomplete
- Patch support for extending CNPC+ types, hot reload
## Traders
- Stock system: Global or Per-Player modes with configurable restock timers
- Currency trades (items + coins)
- Client-side balance preview
## Cloner
- Folder and subfolder organization for all categories
- Full-width directory browser, improved tabs, tag-based filtering
## Animations
- Data store for passing data across events/frames
- Consumer-based task system
- Expanded scripting API
## Animated Textures
- Frame-based animation for items, effect icons, ability hotbar, scripted GUIs
## NPC API
- `IHitboxData` (width/height scaling), `ITintData` (hurt tint, persistent tints)
- Scriptable behavior: sprint, swim, doors, fire reactions, tactical chance, walking range
- `ISound` (volume, pitch, repeat, position)
- Skin overlay `getColor()`/`setColor()`, knockback API
- Six overlays in singleplayer, script error reporting to console
## NPC Combat & Behavior
- Attack speed enforcement, passive faction protection
- Improved track speed, invalid texture fallback
## Other Changes
- Player Dialog Events match NPC Dialog Events
- Linked Item attack speed and scripting API
- Right-click cycling on multi-option buttons
- Legacy quest import (1.6.4), fullscreen/pannable GUIs, unified menu background
- Textfield CTRL shortcuts, `java.lang.reflect` banned in scripts
- Entity packet loss fix (invisible NPCs)
- Natural spawn GUI, runtime control, and despawn improvements
## Bug Fixes
- Script config sync, Bukkit integration
- Quest cooldown for MC/RL Custom timers, quest/dialog saving and categories
- Bard music restart on dialog open
- Spawner yaw, biome spawn persistence, NPC invisibility
- Track speed, set speed edge cases, spawn data, block waypoints, job spawner
- Hitbox scaling and collision
- Animation offsets, lookup failures, syncing, resync on teleport, registration names, double loading
- Mount movement jitter, dismount edge cases
+65 -402
View File
@@ -1,432 +1,95 @@
![CustomNPC+ Banner](images/logo_banner.png)
# CustomNPC+ ## 👋 Welcome to the CustomNPC+ Repository.
![](images/logo_banner.png)
**CustomNPC+** is a Minecraft 1.7.10 Forge mod that lets you create fully customizable NPCs with advanced AI, combat abilities, quests, dialogs, scripting, an economy system, and much more. Built for creative and storytelling players who want to transform their worlds into living RPG experiences. > CustomNPC+ is a [Minecraft](https://minecraft.net/) mod that allows you to add custom NPCs to your world. It is developed for creative and storytelling players who want to make their Minecraft worlds more in-depth and unique. CustomNPC+ is only a branch version of the **1.7.10** Forge version of the original (down below) and has no plans to add or update any other version. This is not an official version of CustomNPC.
> CustomNPC+ is a branch version of the original [CustomNPC](https://www.curseforge.com/minecraft/mc-mods/custom-npcs) by [Noppes](https://github.com/Noppes), developed with permission. This is not an official version of CustomNPC. ----------------
--- <a href="https://discord.gg/pQqRTvFeJ5"> <img src="https://img.shields.io/badge/KAMKEEL_Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white" width="400" height="60"> </a>
<a href="https://ko-fi.com/kamkeel"> <img src="https://img.shields.io/badge/Support_Me_|_Ko--fi-F16061?style=for-the-badge&logo=ko-fi&logoColor=white" alt="Support Me" width="400" height="60"> </a>
<a href="https://discord.gg/pQqRTvFeJ5"> <img src="images/Discord.png" width="400" height="60"> </a>
[![Download CustomNPC+](https://img.shields.io/badge/CustomNPC+-0081CB?style=for-the-badge&logo=material-ui&logoColor=white)](https://modrinth.com/mod/customnpc-plus) [![Download CustomNPC+](https://img.shields.io/badge/CustomNPC+-0081CB?style=for-the-badge&logo=material-ui&logoColor=white)](https://modrinth.com/mod/customnpc-plus)
[![Download MPM+](https://img.shields.io/badge/MorePlayerModels+-0081CB?style=for-the-badge&logo=material-ui&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/moreplayermodels-plus) [![Download MPM+](https://img.shields.io/badge/MorePlayerModels+-0081CB?style=for-the-badge&logo=material-ui&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/moreplayermodels-plus)
[![Download PluginMod](https://img.shields.io/badge/Plugin_Mod-0081CB?style=for-the-badge&logo=material-ui&logoColor=white)](https://github.com/KAMKEEL/Plugin-Mod) [![Download PluginMod](https://img.shields.io/badge/Plugin_Mod-0081CB?style=for-the-badge&logo=material-ui&logoColor=white)](https://github.com/KAMKEEL/Plugin-Mod)
--- ----------------
## Installation ### ❗ Notice
I am not the original creator of CustomNPC. The original creator is @[Noppes](https://github.com/Noppes). I have been permitted to update and develop my own branch version for 1.7.10. The original mod that is updated to the latest versions of Minecraft can be found on these links: [CurseForge](https://www.curseforge.com/minecraft/mc-mods/custom-npcs), [kodevelopment](http://www.kodevelopment.nl/minecraft/customnpcs)
CustomNPC+ is a **replacement** for the original CustomNPC — not an add-on. Do not install both together. Simply drop CustomNPC+ into your client or server mods folder. All original CustomNPC features are preserved and expanded upon. ### ⬇️ Downloads
> Please **backup your world** before installing. Report any bugs on the [issue tracker](https://github.com/KAMKEEL/CustomNPC-Plus/issues).
### Downloads
- **Modrinth**: [Download](https://modrinth.com/mod/customnpc-plus) - **Modrinth**: [Download](https://modrinth.com/mod/customnpc-plus)
- **CurseForge**: [Download](https://www.curseforge.com/minecraft/mc-mods/customnpc-plus) - **CurseForge**: [Download](https://www.curseforge.com/minecraft/mc-mods/customnpc-plus)
--- ### 🔹 Installation
This mod is an ***update*** to CustomNPC and not an add-on. Do not install CustomNPC with CustomNPC-Plus. CustomNPC-Plus does not remove any functional features from the original mod. It expands upon CustomNPC with original features and backported features from newer versions. Simply drag CustomNPC-Plus into any client/server mods folder to utilize. Please **backup** before using as this could still have unforeseen errors. Report any bugs if found, thank you and enjoy.
<a href="https://ko-fi.com/kamkeel"> <img src="images/Kofi.png" width="400" height="60"> </a> ### ❓ Features:
- Flying NPC (Smart Pathfinding)
- 1.8 Skin Support (64x64) (Alex/Steve64)
- Full URL64 Selector (Downloads FULL Size Images for Custom Mob Skins)
- Additional Parts: [Wings, Fins, Capes, Horns, Tail]
- Hide Body Parts [Arms, Legs, Head, Body]
- Custom Overlays
- Animation Maker
- Enhanced Cloner GUI (More Tabs, Filters, Tags)
- Markov Name Generator
- Dark Mode GUI (Link Below)
- 1.12 Scripting Features (Details below)
- Profile System (Multiple Character Slots)
- Quest Party System
- Item and Armor Attributes
- Magic System with Elemental Cycles
- Custom Effect Engine
- Scripted Blocks & Particles
- Compass Marks for Waypoints
- Custom Model Support
- Gecko & Dragon Block C Addons
> More betas with new features will continue to be released to supporters for **Early Access** to new content! #### Scripting:
- CustomNPC+ Api: [API](https://github.com/KAMKEEL/CustomNPC-Plus-API)
- Java Doc: [kamkeel.github.io/CustomNPC-Plus](https://kamkeel.github.io/CustomNPC-Plus/)
- Scripted Items
- Player Overlays
- Script Timers
- Global Scripts
- Script Logging
- GUI Overlays
- Event Scripting
(We never remove script functionality, only add on existing functions)
--- ## 🔰 Skin Model Feature:
###### **Majority of these cape designs are taken from the internet with fair-usage.*
## Feature Overview ##### ❔ Please note all *local* skins in this version of CustomNPC, must match the model selected.
<img src="images/skinAnimation.gif" width="474" height="260"/>
### NPC Creation & Customization
Create NPCs with deep visual customization and lifelike behavior.
<img src="images/NPCEditor.gif" width="474" height="260"/>
- **Skin System** - 1.8 skin support (64x64), Alex & Steve64 models, full URL64 selector that downloads full-size images for custom skins
- **Body Parts** - Wings, fins, capes, horns, tails. Hide individual body parts (arms, legs, head, body)
- **Skin Overlays** - Layer additional textures on top of the base skin with color tinting and alpha control
- **Custom Models** - Support for custom model formats, plus Gecko and DBC addon model integration
- **Hitbox Scaling** - Independently scale NPC hitbox width and height
- **Tint System** - Control hurt flash color and apply persistent color tints
---
### NPC AI & Behavior
NPCs have a full AI system for combat, pathing, and interaction.
- **Flying NPCs** - Smart pathfinding in 3D space for flying entities
- **Combat AI** - Multiple tactical behaviors: attack, ranged attack, ambush, pounce, dodge-shoot, zigzag, stalk, orbit, sprint-to-target, and leap attacks
- **Movement Types** - Standing, wandering, and moving path modes
- **Pathfinding** - Ground, flying, and water navigation
- **Door Interaction** - NPCs can break, open, or ignore doors
- **Behavior Controls** - Configurable sprinting, swimming, fire reactions, tactical chance, and walking range
- **Attack Speed** - NPCs respect attack speed timing when dealing damage
- **Faction Awareness** - NPCs respond to faction standings. Passive faction NPCs are protected from damage
#### Flying NPCs:
<img src="images/FlyingNPC.gif" width="474" height="260"/> <img src="images/FlyingNPC.gif" width="474" height="260"/>
--- #### Url64:
<img src="images/Url64Example.gif" width="474" height="260"/>
### NPC Roles & Jobs #### DarkMode + Cloner GUI:
<img src="images/ClonerGUI-DarkMode.png" width="474" height="260"/>
**Roles** give NPCs interactive functions — Trader, Follower, Bank, Transporter, Postman, Companion, Mount, and Auctioneer. **Jobs** give NPCs background tasks — Bard, Healer, Guard, Item Giver, Follower, Spawner, Conversation, and Chunk Loader. ## 🔗 Want to check out my other projects?
[Plugin Mod](https://github.com/KAMKEEL/Plugin-Mod) is a mod designed to add more aesthetic items for RPG and storytelling. It is compatible with CustomNPC+ and has many items intended to be used and wielded by created NPCs.
--- [RPG Messenger](https://github.com/KAMKEEL/RPGMessenger) is a bukkit plugin designed to allow operators to create messagable NPCs for RPG Servers. Allows a 'RPG Controller' to reply quickly as NPCs, form groupchats, and messagable parties.
### Dialog System [CustomNPC+ Dark Mode](https://github.com/KAMKEEL/CustomNPC-Plus-Dark-Mode) is a resource pack for CustomNPC+ that alters all GUIs within the mod to a dark variant that is both clean and pleasing to look at.
Create branching dialog trees for storytelling and player interaction. ## Cloning / Compiling / Building
<img src="images/Dialog.png" width="474" height="260"/> git clone call `git submodule update --init --recursive`
- **Dialog Trees** - Multi-level branching conversations with unlimited depth Using IntelliJ, take the following steps:
- **Dialog Options** - Player choices that affect outcomes, trigger quests, or change faction standings 1. Run `setupDecompWorkspace` under the `forgegradle` tab.
- **Dialog Images** - Display images alongside dialog text 2. Refresh Gradle.
- **Dialog Colors** - Customizable text and background colors 3. Run `genIntellijRuns` under the `other` tab to set up your Minecraft runs.
- **Categories** - Organize dialogs into categories for large projects
- **Availability Conditions** - Show or hide dialogs based on quests, factions, items, or custom conditions
- **Script Hooks** - Full scripting support for dialog open, close, and option events
--- or for Eclipse, run `gradlew setupDecompWorkspace eclipse` then import the project.
### Quest System Mixin code will not work if you do not add `--tweakClass org.spongepowered.asm.launch.MixinTweaker --mixin customnpcs.mixins.json` to your program arguments.
A complete quest framework for RPG progression.
<img src="images/QuestMarks.png" width="474" height="260"/>
- **Quest Types** - Item collection, dialog completion, kill targets, reach locations, area kills, and fully manual (script-driven) quests
- **Quest Tracking** - On-screen HUD overlay showing active quest objectives
- **Categories** - Organize quests into categories
- **Rewards** - Configure item, XP, and currency rewards
- **Cooldowns** - Repeatable quests with MC time, real-time, or custom cooldown intervals
- **Party Quests** - Share quest objectives across party members with configurable sharing modes
- **Availability** - Control quest visibility based on completed quests, faction standing, dialogs, and more
- **Script Hooks** - Events for quest start, completion, turn-in, and custom quest objectives
---
### Ability System
A full combat ability system for both NPCs and players.
<img src="images/NPCAbilities.gif" width="474" height="260"/>
<img src="images/PlayerAbilities.gif" width="474" height="260"/>
**Melee Abilities** - Slam, Heavy Hit, Cutter
**Energy Projectiles** - Orbs, Discs, Beams, Laser Shots with full visual customization, homing, and hit types
**Energy Barriers** - Domes, Walls, Shields with HP, reflection, and damage absorption
**Defensive** - Guard, Counter, Dodge with configurable damage reduction and counter-attacks
**Movement** - Charge, Dash, Teleport
**AOE** - Shockwave, Sweeper, Vortex
**Hazards & Traps** - Persistent damage zones and proximity-triggered traps with visual presets
**Support** - Ability Effect for healing, buffs, and debuffs
**Key Features:**
- Phase-based execution (Wind-up, Active, Dazed) with visual telegraphs
- Burst system for rapid multi-fire
- Chained abilities for sequential combos
- Player ability hotbar (12 slots) with unlock system
- Full scripting API for every lifecycle event
- Live preview in the ability editor
---
### Auction House & Economy
A complete marketplace and economy system.
<img src="images/Auction.png" width="474" height="260"/>
- **Built-in Currency** - Configurable currency with starting balance, max cap, and Vault plugin integration
- **Auction House** - Global player marketplace with bidding, buyout, snipe protection, and notifications
- **Trade Slots** - Configurable per-player slot limits via permissions
- **Item Blacklist** - Block items by name, wildcard, mod, or NBT tag from being listed
- **Admin Tools** - Dedicated admin GUI for managing listings and creating server auctions
- **Scripting API** - Cancelable events for creates, bids, buyouts, cancels, and claims
**Trader Enhancements:**
- Limited stock with automatic restocking (MC time, real-time, or custom intervals)
- Global or per-player stock modes
- Currency costs on top of item trades
- Client-side balance preview
---
### Script Editor
A full-featured code editor built right into Minecraft.
<img src="images/ScriptEditor.gif" width="474" height="260"/>
- **Syntax Highlighting** - Color-coded keywords, types, variables, methods, strings, and comments
- **Autocomplete** - Smart suggestions with type awareness, static vs instance context, and auto-imports
- **Error Detection** - Real-time underlining of wrong argument types, missing methods, type mismatches, and unused imports
- **Hover Info** - Full type information, documentation, and JSDoc rendering on hover
- **Navigation** - Go to line, search & replace, go to definition, and fullscreen mode
- **Editing** - Smart undo/redo, duplicate lines, comment toggle, rename refactoring, smart bracket pairing
- **Visual** - Line numbers, smooth scrolling, indent guides, brace matching, resizable panels
---
### Scripting
Write scripts in **JavaScript** or **Java** to control every aspect of the mod.
- **Java Scripting** - Write real Java code compiled by the Janino engine. Full support for classes, generics, lambdas, and method references
- **JavaScript** - Full Nashorn-based JavaScript with ECMAScript 5.1 globals (Math, JSON, Date, Number)
- **Client-Side Scripting** - Run scripts on the client for responsive visual experiences (server-controlled)
- **154+ Script Hooks** - Events for NPCs, players, blocks, items, quests, dialogs, factions, abilities, auction, animations, and more
- **Script Types** - NPC, Player, Global, Block, Item, Linked Item, Effect, Ability, Recipe, and Forge Event scripts
- **Scripted Blocks** - Blocks with full script hooks for click, redstone, neighbor changes, and more
- **Scripted Items** - Items with use, attack, toss, pickup, and durability hooks
- **Custom GUIs** - Build custom interfaces with buttons, text fields, scroll panels, and slots via scripting
- **GUI Overlays** - Persistent on-screen overlays with labels, lines, and textured rectangles
- **Addon API** - Mods can ship `.d.ts` type definitions for full autocomplete in the editor
**Resources:**
- API Repository: [CustomNPC+ API](https://github.com/KAMKEEL/CustomNPC-Plus-API)
- Java Docs: [kamkeel.github.io/CustomNPC-Plus](https://kamkeel.github.io/CustomNPC-Plus/)
<img src="images/ScriptedBlock.png" width="474" height="260"/>
<img src="images/ScriptedParticle.png" width="474" height="260"/>
---
### Animation System
Create custom animations for NPCs directly in-game.
- **Animation Maker** - Visual editor for creating frame-based animations
- **Animation Parts** - Animate individual body parts with rotation, position, and scaling
- **Frame Events** - Script hooks for animation start, end, frame enter, and frame exit
- **Data Store** - Animations can store and pass data across events and frames
- **Task System** - Consumer-based callbacks for animation lifecycle
- **Built-in Animations** - Pre-made animations for abilities that work automatically
- **Multiple Registrations** - Register multiple animations under one common name
- **Animated Textures** - Frame-based animated textures for items, effects, and ability icons
<img src="images/AnimationMaker.gif" width="474" height="260"/>
---
### Custom Effects
Create custom status effects beyond vanilla potions.
- **Custom Icons** - Each effect gets its own texture, with support for animated icons
- **Script Hooks** - Events for effect apply, tick, and removal
- **Ability Integration** - Abilities can apply custom effects to targets
- **Condition System** - Check if entities have specific effects for ability or availability conditions
---
### Profile System
Multiple character slots on a single account.
- **Profile Slots** - Each slot stores separate quest progress, dialogs, factions, currency, abilities, and effects
- **Region Locking** - Lock profiles to specific areas
- **Soulbound Items** - Bind items to a specific player by UUID
- **Profile-Slotbound Items** - Bind items to a specific profile slot
---
### Party System
Group up with other players for cooperative gameplay.
- **Party Management** - Invite, kick, leave, disband, and transfer leadership
- **Quest Sharing** - Share quest objectives across party members
- **Ability Integration** - Party members are treated as allies for AOE ability targeting
- **Script Hooks** - Events for invites, kicks, leaves, disbands, and quest completion
<img src="images/PartySystem.png" width="474" height="260"/>
<img src="images/QuestParty.png" width="474" height="260"/>
---
### Faction System
Create factions to control NPC relationships and player reputation.
- **Faction Points** - Players earn or lose standing with factions through quests, combat, and scripting
- **Availability Conditions** - Gate dialogs, quests, and content behind faction thresholds
- **NPC Behavior** - NPCs react to players based on faction standing (friendly, neutral, hostile)
- **Passive Factions** - Passive faction NPCs are protected from damage
---
### HUD System
Customizable on-screen elements.
- **HUD Editor** - Drag and position HUD components to fit your screen
- **Ability Hotbar** - 12-slot bar with horizontal/vertical layout and configurable visible slots
- **Quest Tracking** - On-screen quest objective tracker
- **Compass** - Directional compass with quest and waypoint markers
- **Effect Bar** - Display active custom effects
<img src="images/HudSystem.png" width="474" height="260"/>
---
### Cloner & Organization
Save, organize, and reuse NPCs and content.
- **Cloner Tabs** - Save and load NPCs, items, and other content
- **Folder System** - Organize with folders and subfolders for animations, abilities, forms, auras, outlines, effects, and linked items
- **Quick Tags** - Tag-based filtering for fast searching
- **Full Screen Browser** - Wide directory view for large collections
<img src="images/ClonerTabs.png" width="474" height="260"/>
---
### Items & Blocks
A large library of custom items and decorative blocks.
**Weapons:** Battle Axe, Broadsword, Claw, Crossbow, Dagger, Staff, Glaive, Gun, Kunai, Scythe, Spear, Wand, Warhammer, Musket, and more
**Linked Items:** Create custom items with configurable attack speed, scripted behavior, animated textures, and item versioning
**Blocks:** Banners, barrels, beams, signs, campfires, candles, chairs, couches, crates, crystals, lanterns, mailboxes, pedestals, redstone blocks, and scripted blocks
**Crafting:** Carpentry Bench and Anvil with custom recipe support
<img src="images/VariousWeapons.png" width="474" height="260"/>
<img src="images/JappaTextures.png" width="474" height="260"/>
---
### Custom Models
Support for custom NPC models beyond the default humanoid. Import Blockbench models using the **Gecko Addon** (GeckoLib integration) or use **Armorer's Workshop** skins with the AW Addon.
<img src="images/GeckoAddon1.png" width="474" height="260"/>
<img src="images/GeckoAddon2.png" width="474" height="260"/>
---
### Addon Compatibility
CustomNPC+ has official addons that extend its functionality with other mods. Vault and Pixelmon are also supported natively for economy and scripting integration.
---
## Official CNPC+ Addons
### DBC Addon
Adds full compatibility between [Dragon Block C](https://www.curseforge.com/minecraft/mc-mods/dragon-block-c) and CustomNPC+. Extends abilities with ki-based attacks, adds DBC stat integration to conditions, and enables DBC model/animation support on NPCs.
[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/cnpc-dbc-addon)
[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/customnpc-plus-dbc-addon)
[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/CustomNPC-DBC-Addon)
### Gecko Addon
Adds [GeckoLib](https://www.curseforge.com/minecraft/mc-mods/geckolib) support to CustomNPC+. Import Blockbench models directly into the mod and use them as custom NPC models with full animation support.
[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/cnpc-custom-model-addon)
[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/customnpc-plus-gecko-addon)
[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/CustomNPC-Gecko-Addon)
### Armorer's Workshop Addon
Adds compatibility between [Armorer's Workshop](https://www.curseforge.com/minecraft/mc-mods/armorers-workshop) and CustomNPC+. Use Armorer's Workshop skins and equipment on NPCs with custom rotation, scaling, and animation support. Requires UniMixins.
[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/cnpc-armorers-workshop-addon)
[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/customnpc-plus-aw-addon)
---
## Other Projects
### MorePlayerModels+
An updated continuation of MorePlayerModels for 1.7.10 with backported GUIs, original parts and customizations, and permission support. Works alongside CustomNPC+. This is a replacement — do not install alongside the original MorePlayerModels.
[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/moreplayermodels-plus)
[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/moreplayermodels+)
[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/MorePlayerModels-Plus)
### The Plugin Mod
Adds aesthetic weapons, artifacts, blocks, and apples for RPG and storytelling servers. Designed to pair with CustomNPC+ — use the included swords, spears, axes, medpacks, and decorative blocks to make your NPCs and worlds more diverse.
[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/the-plugin-mod)
[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/the-plugin-mod)
[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/Plugin-Mod)
### HexText
Upgrades Minecraft's font renderer with full RGB hex color support, nested color spans, and animated text effects (glow, shake, wave). Works in signs, anvils, and chat. Requires UniMixins.
[![CurseForge](https://img.shields.io/badge/CurseForge-F16436?style=flat-square&logo=curseforge&logoColor=white)](https://www.curseforge.com/minecraft/mc-mods/hex-text)
[![Modrinth](https://img.shields.io/badge/Modrinth-00AF5C?style=flat-square&logo=modrinth&logoColor=white)](https://modrinth.com/mod/hex-text)
[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/HexText)
### RPG Messenger
A Bukkit plugin for messageable NPCs, group chats, and RPG controller tools. Allows operators to create NPCs that players can message, and lets RPG controllers reply as NPCs in real-time.
[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/RPGMessenger)
### CustomNPC+ Dark Mode
A resource pack that applies a clean dark theme to all CustomNPC+ GUIs.
[![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat-square&logo=github&logoColor=white)](https://github.com/KAMKEEL/CustomNPC-Plus-Dark-Mode)
---
## Configuration
CustomNPC+ has a modular configuration system:
| Config | Purpose |
|--------|---------|
| **Main** | Core mod settings |
| **Client** | Client-side display and UI preferences |
| **Script** | Scripting engine settings and client script toggle |
| **Market** | Currency, auction house, trader, and economy settings |
| **Energy** | Energy projectile settings (explosion block damage, dome item blacklist) |
| **Item** | Item and gun configuration |
| **Debug** | Debug logging and diagnostics |
| **Experimental** | Experimental features toggle |
---
## Building from Source
This project uses the [GTNH Gradle Convention](https://github.com/GTNewHorizons/ExampleMod1.7.10) build system with [RetroFuturaGradle](https://github.com/GTNewHorizons/RetroFuturaGradle).
```bash
git clone <repo-url>
git submodule update --init --recursive
./gradlew build
```
That's it. Submodules pull in the API sources, and `build` handles decompilation, compilation, and mixin embedding automatically.
**Run the game:**
```bash
./gradlew runClient # Launch client
./gradlew runServer # Launch server
```
**IDE Setup (IntelliJ):**
1. Import the project as a Gradle project
2. Run `./gradlew genIntellijRuns`
3. Add program arguments: `--tweakClass org.spongepowered.asm.launch.MixinTweaker --mixin customnpcs.mixins.json`
---
## Notice
I am not the original creator of CustomNPC. The original creator is [Noppes](https://github.com/Noppes). I have been permitted to update and develop my own branch version for 1.7.10. The original mod updated to the latest Minecraft versions can be found on [CurseForge](https://www.curseforge.com/minecraft/mc-mods/custom-npcs) and [kodevelopment](http://www.kodevelopment.nl/minecraft/customnpcs).
+2 -78
View File
@@ -6,7 +6,7 @@ plugins {
id "dts.typescript-generator" id "dts.typescript-generator"
} }
version = "1.11.2" version = "1.11-beta1"
group= "kamkeel.customnpc-plus" group= "kamkeel.customnpc-plus"
archivesBaseName = "CustomNPC-Plus" archivesBaseName = "CustomNPC-Plus"
@@ -57,43 +57,6 @@ sourceSets.main.java {
srcDirs += apiDir srcDirs += apiDir
} }
// ============================================================================
// Scribe fixtures -- an offline generator for CustomNPC+ save data.
//
// Its own source set, so nothing here reaches the mod jar. It runs CustomNPC+'s
// own writeToNBT/writeNBT methods against a bootstrapped-but-unlaunched
// Minecraft, and writes the results into a world layout copied from each
// controller. See src/fixtures/README.md.
// ============================================================================
sourceSets {
fixtures {
java.srcDirs = ['src/fixtures/java']
compileClasspath += sourceSets.main.output + sourceSets.main.compileClasspath
runtimeClasspath += sourceSets.main.output + sourceSets.main.runtimeClasspath
}
}
tasks.register('scribeFixtures', JavaExec) {
group 'CustomNPC+'
description 'Generates CustomNPC+ save fixtures for Scribe. -Pout=<dir>, -Pworlds=<a,b>'
dependsOn 'fixturesClasses'
classpath = sourceSets.fixtures.runtimeClasspath
mainClass = 'kamkeel.npcs.fixtures.FixtureGenerator'
// Off the project dir, because CustomNpcs.getWorldSaveDirectory() resolves "." and
// a stray relative write would land in the repo root.
workingDir = project.buildDir
doFirst {
// Resolved against the project directory, not workingDir, so -Pout=build/x means what it
// looks like rather than build/build/x.
def out = project.hasProperty('out') ? project.file(project.property('out'))
: new File(project.buildDir, 'scribe-fixtures')
args = [out.absolutePath]
if (project.hasProperty('worlds')) {
args += ['--worlds', project.property('worlds')]
}
}
}
// ============================================================================ // ============================================================================
// TypeScript Definition Generation Task // TypeScript Definition Generation Task
// Generates .d.ts files from Java API sources for scripting IDE support // Generates .d.ts files from Java API sources for scripting IDE support
@@ -101,50 +64,11 @@ tasks.register('scribeFixtures', JavaExec) {
// TypeScript plugin is applied above in the main plugins block // TypeScript plugin is applied above in the main plugins block
tasks.named("generateTypeScriptDefinitions").configure { tasks.named("generateTypeScriptDefinitions").configure {
sourceDirectories = ['src/api/java', 'src/main/java'] sourceDirectories = ['src/api/java']
outputDirectory = "src/main/resources/assets/${project.property("modId")}/api" outputDirectory = "src/main/resources/assets/${project.property("modId")}/api"
apiPackages = ['noppes.npcs.api', 'net.minecraft'] as Set apiPackages = ['noppes.npcs.api', 'net.minecraft'] as Set
cleanOutputFirst = true // Clean old generated files before regenerating cleanOutputFirst = true // Clean old generated files before regenerating
patchesDirectory = "dts-patches"
implementationPackages = [
'noppes.npcs.scripted',
'noppes.npcs.controllers.data',
'noppes.npcs.entity.data',
'noppes.npcs.quests',
'kamkeel.npcs.controllers.data'
] as Set
} }
processResources.dependsOn generateTypeScriptDefinitions processResources.dependsOn generateTypeScriptDefinitions
sourcesJar.dependsOn generateTypeScriptDefinitions sourcesJar.dependsOn generateTypeScriptDefinitions
// Javadoc configuration
javadoc {
options.encoding = 'UTF-8'
options.charSet = 'UTF-8'
options.docEncoding = 'UTF-8'
options.tags = [
'hookName:a:Hook Name:'
]
options.stylesheetFile = file('.github/javadoc/javadoc-theme.css')
options.header = file('.github/javadoc/javadoc-header.html').text.replaceAll('\\s+', ' ').trim()
options.addBooleanOption('-allow-script-in-comments', true)
options.footer = file('.github/javadoc/javadoc-footer.html').text.replaceAll('\\s+', ' ').trim()
// Only document the public API, not net.minecraft stubs
include 'noppes/npcs/api/**'
options.links(
'https://docs.oracle.com/en/java/javase/11/docs/api/'
)
javadocTool = javaToolchains.javadocToolFor {
languageVersion = JavaLanguageVersion.of(11)
}
}
// Modify the existing 'build' task to depend on 'updateAPI'
//tasks.apiClasses.dependsOn 'updateAPI'
+3 -3
View File
@@ -35,7 +35,7 @@
*/ */
def embedMixin = !project.hasProperty("nomixin"); def embedMixin = !project.hasProperty("nomixin");
dependencies { dependencies {
runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.8.44-GTNH:dev") runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.5.4-GTNH:dev")
if (!project.hasProperty("noNashorn")) { if (!project.hasProperty("noNashorn")) {
runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946") runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946")
} }
@@ -43,8 +43,8 @@ dependencies {
// compileOnly(files("./tools/bukkit-api/spigot-api-ONLY.jar")) // compileOnly(files("./tools/bukkit-api/spigot-api-ONLY.jar"))
// compileOnly(files("./tools/bukkit-api/Vault-1.4.1.jar")) // compileOnly(files("./tools/bukkit-api/Vault-1.4.1.jar"))
shadowImplementation(project.files("tools/standalone-JaninoLoader-1.0.2.jar")) shadowImplementation(project.files("tools/standalone-JaninoLoader-1.0.1-ALPHA.jar"))
annotationProcessor(project.files("tools/standalone-JaninoLoader-1.0.2.jar")) annotationProcessor(project.files("tools/standalone-JaninoLoader-1.0.1-ALPHA.jar"))
testImplementation("junit:junit:4.13.2") testImplementation("junit:junit:4.13.2")
-126
View File
@@ -1,126 +0,0 @@
/**
* ECMAScript 5.1 - Array type for working with ordered collections of elements.
* Supports static methods like Array.isArray() and instance methods like push(), map(), filter().
*
* ## How to Use
*
* ### Creating Arrays
* ```js
* var empty = []; // Empty array
* var nums = [1, 2, 3]; // Array with values
* var mixed = ["hello", 42, true]; // Mixed types
* var nested = [[1, 2], [3, 4]]; // Nested arrays
* ```
*
* ### Static Methods
* ```js
* Array.isArray([1, 2, 3]); // true
* Array.isArray("hello"); // false
* Array.isArray({length: 3}); // false
* ```
*
* ### Adding & Removing Elements
* ```js
* var arr = [1, 2, 3];
* arr.push(4); // [1, 2, 3, 4] — add to end
* arr.pop(); // [1, 2, 3] — remove from end
* arr.unshift(0); // [0, 1, 2, 3] — add to start
* arr.shift(); // [1, 2, 3] — remove from start
* arr.splice(1, 1, 99); // [1, 99, 3] — replace at index 1
* ```
*
* ### Searching & Iterating
* ```js
* var arr = [10, 20, 30, 20];
* arr.indexOf(20); // 1 (first match)
* arr.lastIndexOf(20); // 3 (last match)
* arr.forEach(function(val) { log(val); });
* var doubled = arr.map(function(v) { return v * 2; }); // [20, 40, 60, 40]
* var big = arr.filter(function(v) { return v > 15; }); // [20, 30, 20]
* ```
*
* ### Reducing & Testing
* ```js
* var sum = [1, 2, 3].reduce(function(acc, v) { return acc + v; }, 0); // 6
* var allPositive = [1, 2, 3].every(function(v) { return v > 0; }); // true
* var hasNeg = [1, -2, 3].some(function(v) { return v < 0; }); // true
* ```
*
* ### ❌ Common Mistakes
* ```js
* Array.push(1); // TypeError — push is an instance method
* var a = [3,1,2]; a.sort(); // Sorts as strings! Use compareFn for numbers
* a.sort(function(a, b) { return a - b; }); // Correct numeric sort: [1, 2, 3]
* ```
*/
export interface Array<T> {
/** Returns true if the given object is an array, false otherwise */
static isArray(arg: any): boolean;
/** The number of elements in the array */
length: number;
/** Combines two or more arrays and returns a new array without modifying the original */
concat(...items: T[]): T[];
/** Tests whether all elements in the array pass the provided test function */
every(callback: Java.java.util.function.Function<T, boolean>): boolean;
/** Creates a new array with all elements that pass the test implemented by the provided function */
filter(callback: Java.java.util.function.Function<T, boolean>): T[];
/** Executes a provided function once for each array element. Returns undefined */
forEach(callback: Java.java.util.function.Consumer<T>): void;
/** Returns the first index at which an element is found, or -1 if not present */
indexOf(searchElement: T): number;
indexOf(searchElement: T, fromIndex: number): number;
/** Joins all elements of an array into a string separated by the given separator */
join(separator: string): string;
/** Returns the last index at which an element is found, or -1 if not present */
lastIndexOf(searchElement: T): number;
lastIndexOf(searchElement: T, fromIndex: number): number;
/** Creates a new array with the results of calling a function on every element */
map(callback: Java.java.util.function.Function<T, any>): any[];
/** Removes and returns the last element from the array, modifying the original array */
pop(): T;
/** Adds one or more elements to the end of an array and returns the new length */
push(...items: T[]): number;
/** Applies a function against an accumulator and each element to reduce the array to a single value */
reduce(callback: Java.java.util.function.BiFunction<any, T, any>): any;
reduce(callback: Java.java.util.function.BiFunction<any, T, any>, initialValue: any): any;
/** Same as reduce() but processes the array from right to left */
reduceRight(callback: Java.java.util.function.BiFunction<any, T, any>): any;
reduceRight(callback: Java.java.util.function.BiFunction<any, T, any>, initialValue: any): any;
/** Reverses an array in place. The first element becomes the last, and vice versa */
reverse(): T[];
/** Removes and returns the first element from the array, modifying the original array */
shift(): T;
/** Returns a shallow copy of a portion of an array as a new array object */
slice(start: number, end: number): T[];
/** Tests whether at least one element in the array passes the test implemented by the provided function */
some(callback: Java.java.util.function.Function<T, boolean>): boolean;
/** Sorts the elements of an array in place and returns the sorted array */
sort(compareFn: Java.java.util.function.BiFunction<T, T, number>): T[];
/** Changes the contents of an array by removing or replacing existing elements and/or adding new ones */
splice(start: number, deleteCount: number, ...items: T[]): T[];
/** Returns a string representation of the array */
toString(): string;
/** Adds one or more elements to the beginning of an array and returns the new length */
unshift(...items: T[]): number;
}
-36
View File
@@ -1,36 +0,0 @@
/**
* ECMAScript 5.1 - Boolean type for true/false values.
* Booleans are the result of comparison and logical operations.
*
* ## How to Use
*
* ### Creating Booleans
* ```js
* var yes = true; // Boolean literal
* var no = false; // Boolean literal
* var fromExpr = (5 > 3); // true (comparison result)
* ```
*
* ### Boolean Methods
* ```js
* var b = true;
* b.toString(); // "true"
* b.valueOf(); // true (primitive value)
* ```
*
* ### Truthy & Falsy Values
* ```js
* // These are FALSY (evaluate to false):
* // false, 0, "", null, undefined, NaN
*
* // These are TRUTHY (evaluate to true):
* // true, any non-zero number, any non-empty string, objects, arrays
*
*/
export interface Boolean {
/** Returns the string "true" or "false" */
toString(): string;
/** Returns the primitive boolean value */
valueOf(): boolean;
}
-168
View File
@@ -1,168 +0,0 @@
/**
* ECMAScript 5.1 - Date type for working with dates and times.
* Create with `new Date()` or use static methods like Date.now() to get current timestamp.
*
* ## How to Use
*
* ### Creating Dates
* ```js
* var now = new Date(); // Current date & time
* var epoch = new Date(0); // Jan 1, 1970
* var specific = new Date(2024, 0, 15); // Jan 15, 2024 (months are 0-based!)
* var full = new Date(2024, 5, 15, 10, 30, 0); // Jun 15, 2024 10:30:00
* var fromStr = new Date("2024-01-15"); // Parse from ISO string
* ```
*
* ### Static Methods (no `new` needed)
* ```js
* var timestamp = Date.now(); // Current time in milliseconds
* var parsed = Date.parse("2024-01-15"); // Parse string to timestamp
* var utc = Date.UTC(2024, 0, 15); // UTC timestamp for Jan 15, 2024
* ```
*
* ### Common Mistakes
* ```js
* Date.now; // Returns the function, not the timestamp!
* Date.getMinutes(); // TypeError — instance method, not static
* new Date(2024, 1, 1); // Feb 1, not Jan 1 — months are 0-based!
* ```
*/
export interface Date {
/** Returns the current time as the number of milliseconds since 1970-01-01 00:00:00 UTC */
static now(): number;
/** Parses a date string and returns the number of milliseconds since 1970-01-01 00:00:00 UTC */
static parse(s: string): number;
/** Returns the number of milliseconds since 1970-01-01 00:00:00 UTC for the given UTC date/time components */
static UTC(year: number, month: number, date: number, hours: number, minutes: number, seconds: number, ms: number): number;
/** Returns the day of the month (1-31) in local time */
getDate(): number;
/** Returns the day of the week (0=Sunday, 6=Saturday) in local time */
getDay(): number;
/** Returns the year in local time */
getFullYear(): number;
/** Returns the hour (0-23) in local time */
getHours(): number;
/** Returns the milliseconds (0-999) in local time */
getMilliseconds(): number;
/** Returns the minutes (0-59) in local time */
getMinutes(): number;
/** Returns the month (0=January, 11=December) in local time */
getMonth(): number;
/** Returns the seconds (0-59) in local time */
getSeconds(): number;
/** Returns the number of milliseconds since 1970-01-01 00:00:00 UTC */
getTime(): number;
/** Returns the time zone offset in minutes between local time and UTC */
getTimezoneOffset(): number;
/** Returns the day of the month (1-31) in UTC */
getUTCDate(): number;
/** Returns the day of the week (0=Sunday, 6=Saturday) in UTC */
getUTCDay(): number;
/** Returns the year in UTC */
getUTCFullYear(): number;
/** Returns the hour (0-23) in UTC */
getUTCHours(): number;
/** Returns the milliseconds (0-999) in UTC */
getUTCMilliseconds(): number;
/** Returns the minutes (0-59) in UTC */
getUTCMinutes(): number;
/** Returns the month (0=January, 11=December) in UTC */
getUTCMonth(): number;
/** Returns the seconds (0-59) in UTC */
getUTCSeconds(): number;
/** Sets the day of the month and returns the new timestamp */
setDate(date: number): number;
/** Sets the year, and optionally month and date, then returns the new timestamp */
setFullYear(year: number, month: number, date: number): number;
/** Sets the hour, minutes, seconds, and milliseconds, then returns the new timestamp */
setHours(hour: number, min: number, sec: number, ms: number): number;
/** Sets the milliseconds and returns the new timestamp */
setMilliseconds(ms: number): number;
/** Sets the minutes, seconds, and milliseconds, then returns the new timestamp */
setMinutes(min: number, sec: number, ms: number): number;
/** Sets the month, and optionally date, then returns the new timestamp */
setMonth(month: number, date: number): number;
/** Sets the seconds and milliseconds, then returns the new timestamp */
setSeconds(sec: number, ms: number): number;
/** Sets the timestamp (milliseconds since epoch) and returns it */
setTime(time: number): number;
/** Sets the day of the month (UTC) and returns the new timestamp */
setUTCDate(date: number): number;
/** Sets the year, month, and date (UTC), then returns the new timestamp */
setUTCFullYear(year: number, month: number, date: number): number;
/** Sets the hour, minutes, seconds, and milliseconds (UTC), then returns the new timestamp */
setUTCHours(hour: number, min: number, sec: number, ms: number): number;
/** Sets the milliseconds (UTC) and returns the new timestamp */
setUTCMilliseconds(ms: number): number;
/** Sets the minutes, seconds, and milliseconds (UTC), then returns the new timestamp */
setUTCMinutes(min: number, sec: number, ms: number): number;
/** Sets the month and date (UTC), then returns the new timestamp */
setUTCMonth(month: number, date: number): number;
/** Sets the seconds and milliseconds (UTC), then returns the new timestamp */
setUTCSeconds(sec: number, ms: number): number;
/** Returns a string representation of the date portion in local time (e.g., "Mon Jan 01 2024") */
toDateString(): string;
/** Returns the date as an ISO 8601 string (e.g., "2024-01-01T00:00:00.000Z") */
toISOString(): string;
/** Returns a JSON representation of the date (typically an ISO 8601 string) */
toJSON(key: any): string;
/** Returns a localized string for the date portion (format depends on locale) */
toLocaleDateString(): string;
/** Returns a localized string for the entire date and time (format depends on locale) */
toLocaleString(): string;
/** Returns a localized string for the time portion (format depends on locale) */
toLocaleTimeString(): string;
/** Returns a string representation of the date and time in local time */
toString(): string;
/** Returns a string representation of the time portion in local time (e.g., "00:00:00 GMT+0000") */
toTimeString(): string;
/** Returns a string representation of the date and time in UTC (e.g., "Mon, 01 Jan 2024 00:00:00 GMT") */
toUTCString(): string;
/** Returns the primitive value of the date object (milliseconds since 1970-01-01 00:00:00 UTC) */
valueOf(): number;
}
-81
View File
@@ -1,81 +0,0 @@
/**
* ECMAScript 5.1 - Error base type for runtime errors.
* Throw Error objects to indicate failure conditions in your code.
*
* ## How to Use
*
* ### Creating & Throwing Errors
* ```js
* throw new Error("Something went wrong");
* throw new TypeError("Expected a string");
* throw new RangeError("Value out of range");
* ```
*
* ### Catching Errors
* ```js
* try {
* var result = riskyOperation();
* } catch (e) {
* log(e.name); // "Error", "TypeError", etc.
* log(e.message); // "Something went wrong"
* log(e.toString()); // "Error: Something went wrong"
* }
* ```
*
* ### Custom Error Messages
* ```js
* function divide(a, b) {
* if (b === 0) {
* throw new Error("Cannot divide by zero");
* }
* return a / b;
* }
* ```
*
* ### ❌ Common Mistakes
* ```js
* throw "Something went wrong"; // Works but no .name or .message properties
* Error("oops"); // Creates error but doesn't throw it!
* throw Error("oops"); // ✅ Works (with or without `new`)
* ```
*/
export interface Error {
/** The name of the error type (e.g., "Error", "TypeError", "RangeError") */
name: string;
/** A human-readable description of what went wrong */
message: string;
/** Returns a string representation of the error (typically "name: message") */
toString(): string;
}
/**
* EvalError - Thrown when eval() function is misused (rarely used in modern JavaScript)
*/
export interface EvalError extends Error {}
/**
* RangeError - Thrown when a numeric value is out of the acceptable range (e.g., array length < 0)
*/
export interface RangeError extends Error {}
/**
* ReferenceError - Thrown when trying to reference a variable that does not exist or is not in scope
*/
export interface ReferenceError extends Error {}
/**
* SyntaxError - Thrown when parsing invalid syntax (usually caught during compile/parse, not runtime)
*/
export interface SyntaxError extends Error {}
/**
* TypeError - Thrown when an operation is performed on a value of the wrong type (e.g., calling a non-function)
*/
export interface TypeError extends Error {}
/**
* URIError - Thrown by URI encoding/decoding functions when given invalid characters or sequences
*/
export interface URIError extends Error {}
-75
View File
@@ -1,75 +0,0 @@
/**
* ECMAScript 5.1 - Global functions available in the global scope.
* These are not on any specific object - call them directly (e.g., parseInt("42")).
*
* ## How to Use
*
* ### Parsing Numbers
* ```js
* parseInt("42"); // 42
* parseInt("42px"); // 42 (stops at non-digit)
* parseInt("0xFF", 16); // 255 (hexadecimal)
* parseInt("111", 2); // 7 (binary)
* parseFloat("3.14"); // 3.14
* parseFloat("3.14abc"); // 3.14 (stops at invalid char)
* ```
*
* ### Checking Special Values
* ```js
* isNaN(NaN); // true
* isNaN(42); // false
* isNaN("hello"); // true (cannot parse as number)
* isNaN("42"); // false (can parse as number)
* isFinite(42); // true
* isFinite(Infinity); // false
* isFinite(NaN); // false
* ```
*
* ### URI Encoding/Decoding
* ```js
* encodeURI("hello world"); // "hello%20world"
* decodeURI("hello%20world"); // "hello world"
* encodeURIComponent("a=1&b=2"); // "a%3D1%26b%3D2" (encodes & and =)
* decodeURIComponent("a%3D1%26b%3D2"); // "a=1&b=2"
* ```
*
* ### ❌ Common Mistakes
* ```js
* parseInt("08"); // Some engines treat as octal! Always specify radix
* parseInt("08", 10); // 8 ✅ — explicitly base-10
* parseInt(""); // NaN — empty string returns NaN, not 0
* parseFloat(""); // NaN
* isNaN(undefined); // true — coerces to NaN first
* ```
*/
export interface GlobalFunctions {
/** Evaluates JavaScript code in a string (use with caution - slow and potential security issues) */
static eval(x: any): any;
/** Parses a string and returns an integer. Stops parsing at the first non-digit character */
static parseInt(string: string): number;
/** Parses a string and returns an integer using the specified radix (base). Stops parsing at the first non-digit character */
static parseInt(string: string, radix: number): number;
/** Parses a string and returns a floating-point number. Stops parsing at the first invalid character */
static parseFloat(string: string): number;
/** Determines whether a value is NaN (not-a-number). The value is first coerced to a number before testing */
static isNaN(value: any): boolean;
/** Determines whether a value is a finite number. The value is first coerced to a number. Returns false for Infinity, -Infinity, and NaN */
static isFinite(value: any): boolean;
/** Decodes a URI by replacing encoded sequences like %20 with their original characters */
static decodeURI(encodedURI: string): string;
/** Decodes URI component by replacing ALL encoded sequences including those for reserved URI characters */
static decodeURIComponent(encodedURIComponent: string): string;
/** Encodes a URI by replacing special characters with %HH sequences (but preserves reserved characters like / : ?) */
static encodeURI(uri: string): string;
/** Encodes URI component by replacing ALL special characters including reserved ones with %HH sequences */
static encodeURIComponent(uriComponent: string): string;
}
-100
View File
@@ -1,100 +0,0 @@
/**
* ECMAScript 5.1 - JSON built-in object for parsing and serializing JSON data.
*
* ## How to Use
*
* JSON is a **static object** — use its methods directly, never with `new`.
*
* ### Parsing JSON Strings to Objects
* ```js
* var obj = JSON.parse('{"name": "Steve", "level": 5}');
* log(obj.name); // "Steve"
* log(obj.level); // 5
*
* var arr = JSON.parse('[1, 2, 3]');
* log(arr[0]); // 1
* ```
*
* ### Converting Objects to JSON Strings
* ```js
* var data = { name: "Steve", hp: 100 };
* var json = JSON.stringify(data); // '{"name":"Steve","hp":100}'
*
* // Pretty-printed with 2-space indent:
* var pretty = JSON.stringify(data, null, 2);
* // '{
* // "name": "Steve",
* // "hp": 100
* // }'
* ```
*
* ### Storing & Loading Data
* ```js
* // Save to NPC stored data:
* var inventory = { sword: 1, potion: 5 };
* npc.getStoredData().put("inv", JSON.stringify(inventory));
*
* // Load from NPC stored data:
* var raw = npc.getStoredData().get("inv");
* var loaded = JSON.parse(raw);
* log(loaded.potion); // 5
* ```
*
* ### ❌ Common Mistakes
* ```js
* new JSON(); // TypeError — JSON is not a constructor
* JSON.parse('{name: "Steve"}'); // SyntaxError — keys must be quoted
* JSON.parse("{'name': 'Steve'}"); // SyntaxError — must use double quotes
* JSON.parse('{"name": "Steve"}'); // ✅ Correct — double-quoted keys & values
* ```
*/
export interface JSON {
/**
* Parses a JSON string and returns the parsed value (object, array, string, number, boolean, or null).
* @param text - A valid JSON string to parse
* @returns The parsed JavaScript value
*/
static parse(text: string): any;
/**
* Parses a JSON string with a reviver function that transforms each parsed key-value pair.
* @param text - A valid JSON string to parse
* @param reviver - Function called for each key-value pair; receives the key and parsed value, returns the transformed value
* @returns The parsed JavaScript value after applying the reviver
*/
static parse(text: string, reviver: Java.java.util.function.BiFunction<string, any, any>): any;
/**
* Converts a JavaScript value to a JSON string.
* @param value - The value to serialize (object, array, string, number, boolean, or null)
* @returns A JSON-formatted string representation of the value
*/
static stringify(value: any): string;
/**
* Converts a JavaScript value to a JSON string, using a replacer function to filter or transform properties.
* @param value - The value to serialize
* @param replacer - Function called for each key-value pair; receives the key and value, returns the value to include (or undefined to omit)
* @param space - Optional indentation: a number of spaces (up to 10), or a string prefix per level
* @returns A JSON-formatted string representation of the value
*/
static stringify(value: any, replacer: Java.java.util.function.BiFunction<string, any, any>, space?: any): string;
/**
* Converts a JavaScript value to a JSON string, including only the specified properties.
* @param value - The value to serialize
* @param replacer - Array of property names to include in the output
* @param space - Optional indentation: a number of spaces (up to 10), or a string prefix per level
* @returns A JSON-formatted string representation of the value
*/
static stringify(value: any, replacer: string[], space?: any): string;
/**
* Converts a JavaScript value to a JSON string with optional pretty-printing.
* @param value - The value to serialize
* @param replacer - Pass null to include all properties
* @param space - Indentation: a number of spaces (up to 10), or a string prefix per level
* @returns A JSON-formatted string representation of the value
*/
static stringify(value: any, replacer: null, space: any): string;
}
-128
View File
@@ -1,128 +0,0 @@
/**
* ECMAScript 5.1 - Math built-in object providing mathematical constants and functions.
* All methods are static and called as Math.methodName(). No constructor.
*
* ## How to Use
*
* Math is a **static object** — use its methods directly, never with `new`.
*
* ### Basic Math Operations
* ```js
* var rounded = Math.floor(3.7); // 3
* var ceiling = Math.ceil(3.2); // 4
* var nearest = Math.round(3.5); // 4
* var absolute = Math.abs(-42); // 42
* ```
*
* ### Powers, Roots & Logarithms
* ```js
* var squared = Math.pow(2, 3); // 8
* var root = Math.sqrt(16); // 4
* var natural = Math.log(Math.E); // 1
* ```
*
* ### Random Numbers
* ```js
* var rand = Math.random(); // 0.0 to 0.999...
* // Random integer between 1 and 10:
* var dice = Math.floor(Math.random() * 10) + 1;
* ```
*
* ### Finding Min/Max
* ```js
* var biggest = Math.max(5, 10, 3); // 10
* var smallest = Math.min(5, 10, 3); // 3
* ```
*
* ### Trigonometry
* ```js
* var sine = Math.sin(Math.PI / 2); // 1
* var cosine = Math.cos(0); // 1
* var angle = Math.atan2(1, 1); // 0.785... (PI/4)
* ```
*
* ### ❌ Common Mistakes
* ```js
* new Math() // TypeError — Math is not a constructor
* Math() // TypeError — Math is not a function
* ```
*/
export interface Math {
/** Euler's number (~2.718), the base of natural logarithms */
static readonly E: number;
/** Natural logarithm of 2 (~0.693) */
static readonly LN2: number;
/** Natural logarithm of 10 (~2.303) */
static readonly LN10: number;
/** Base-2 logarithm of e (~1.443) */
static readonly LOG2E: number;
/** Base-10 logarithm of e (~0.434) */
static readonly LOG10E: number;
/** Ratio of a circle's circumference to its diameter (~3.14159) */
static readonly PI: number;
/** Square root of 0.5 (~0.707) */
static readonly SQRT1_2: number;
/** Square root of 2 (~1.414) */
static readonly SQRT2: number;
/** Returns the absolute value of a number */
static abs(x: number): number;
/** Returns the arccosine (in radians) of a number */
static acos(x: number): number;
/** Returns the arcsine (in radians) of a number */
static asin(x: number): number;
/** Returns the arctangent (in radians) of a number */
static atan(x: number): number;
/** Returns the arctangent of two numbers (y/x), with proper quadrant handling */
static atan2(y: number, x: number): number;
/** Returns the smallest integer greater than or equal to a number */
static ceil(x: number): number;
/** Returns the cosine (in radians) of a number */
static cos(x: number): number;
/** Returns e raised to the power of a number */
static exp(x: number): number;
/** Returns the largest integer less than or equal to a number */
static floor(x: number): number;
/** Returns the natural logarithm (base e) of a number */
static log(x: number): number;
/** Returns the largest of zero or more numbers */
static max(...values: number[]): number;
/** Returns the smallest of zero or more numbers */
static min(...values: number[]): number;
/** Returns base raised to the power of exponent */
static pow(x: number, y: number): number;
/** Returns a random number between 0 (inclusive) and 1 (exclusive) */
static random(): number;
/** Returns the value of a number rounded to the nearest integer */
static round(x: number): number;
/** Returns the sine (in radians) of a number */
static sin(x: number): number;
/** Returns the square root of a number */
static sqrt(x: number): number;
/** Returns the tangent (in radians) of a number */
static tan(x: number): number;
}
-74
View File
@@ -1,74 +0,0 @@
/**
* ECMAScript 5.1 - Number type for working with numeric values and constants.
* Access static constants like Number.MAX_VALUE or format numbers with instance methods.
*
* ## How to Use
*
* ### Number Constants
* ```js
* Number.MAX_VALUE; // ~1.79e+308 (largest representable number)
* Number.MIN_VALUE; // ~5e-324 (smallest positive number)
* Number.NaN; // NaN
* Number.POSITIVE_INFINITY; // Infinity
* Number.NEGATIVE_INFINITY; // -Infinity
* ```
*
* ### Formatting Numbers
* ```js
* var n = 3.14159;
* n.toFixed(2); // "3.14" (fixed decimal places)
* n.toFixed(0); // "3"
* n.toPrecision(4); // "3.142" (significant digits)
* n.toExponential(2); // "3.14e+0" (scientific notation)
* ```
*
* ### Converting to String
* ```js
* var n = 255;
* n.toString(); // "255" (base 10, default)
* n.toString(16); // "ff" (hexadecimal)
* n.toString(2); // "11111111" (binary)
* n.toString(8); // "377" (octal)
* ```
*
* ### ❌ Common Mistakes
* ```js
* Number.toFixed(2); // TypeError — instance method, not static
* (3).toFixed(2); // "3.00" ✅ — wrap literal in parentheses
* 3.toFixed(2); // SyntaxError — parser reads 3. as float
* ```
*/
export interface Number {
/** The largest representable number (~1.79e+308) */
static readonly MAX_VALUE: number;
/** The smallest representable positive number (~5e-324) */
static readonly MIN_VALUE: number;
/** Represents "Not a Number" (NaN) - the result of undefined or invalid arithmetic operations */
static readonly NaN: number;
/** Represents negative infinity, the result of overflow or division by zero */
static readonly NEGATIVE_INFINITY: number;
/** Represents positive infinity, the result of overflow or division by zero */
static readonly POSITIVE_INFINITY: number;
/** Formats the number using exponential notation with optional fractional digits */
toExponential(fractionDigits: number): string;
/** Formats the number as a fixed-point string with the specified number of fractional digits (0-20) */
toFixed(fractionDigits: number): string;
/** Returns a localized string representation of the number (format depends on locale) */
toLocaleString(): string;
/** Formats the number as a string with the specified number of significant digits (1-21) */
toPrecision(precision: number): string;
/** Converts the number to a string in the specified radix (base 2-36, default 10) */
toString(radix: number): string;
/** Returns the primitive numeric value of this Number object */
valueOf(): number;
}
-105
View File
@@ -1,105 +0,0 @@
/**
* ECMAScript 5.1 - Object type, the base type for all JavaScript objects.
* Use static methods like Object.keys() and Object.create() to manipulate object structure.
*
* ## How to Use
*
* ### Creating Objects
* ```js
* var obj = {}; // Empty object literal
* var person = { name: "Steve", age: 20 }; // Object with properties
* var child = Object.create(person); // Create with prototype
* ```
*
* ### Inspecting Objects
* ```js
* var obj = { a: 1, b: 2, c: 3 };
* Object.keys(obj); // ["a", "b", "c"]
* Object.getOwnPropertyNames(obj); // ["a", "b", "c"] (includes non-enumerable)
* obj.hasOwnProperty("a"); // true
* obj.hasOwnProperty("toString"); // false (inherited, not own)
* ```
*
* ### Freezing & Sealing
* ```js
* var config = { debug: false };
* Object.freeze(config); // Cannot modify, add, or delete properties
* config.debug = true; // Silently fails (or throws in strict mode)
* Object.isFrozen(config); // true
*
* var settings = { volume: 50 };
* Object.seal(settings); // Can modify values, but cannot add/delete
* settings.volume = 75; // ✅ Works
* settings.newProp = true; // Silently fails
* ```
*
* ### Property Descriptors
* ```js
* var obj = {};
* Object.defineProperty(obj, "id", {
* value: 42,
* writable: false, // Cannot be changed
* enumerable: true // Shows up in for-in / Object.keys
* });
* ```
*
* ### ❌ Common Mistakes
* ```js
* Object.keys(); // TypeError — needs an argument
* obj.keys(); // TypeError — keys is a static method
* Object.hasOwnProperty("a"); // Wrong — instance method on the object
* ```
*/
export interface Object {
/** Creates a new object with the specified prototype and optional property descriptors */
static create(proto: any, propertiesObject: any): any;
/** Defines or modifies multiple properties on an object and returns the modified object */
static defineProperties(obj: any, props: any): any;
/** Defines a new property on an object or modifies an existing property and returns the object */
static defineProperty(obj: any, prop: string, descriptor: any): any;
/** Prevents all modifications to an object (cannot add, modify, or delete properties) */
static freeze(obj: any): any;
/** Returns a property descriptor for a named property on an object, or undefined if not found */
static getOwnPropertyDescriptor(obj: any, prop: string): any;
/** Returns an array of all property names (both enumerable and non-enumerable) on an object */
static getOwnPropertyNames(obj: any): string[];
/** Returns the prototype object of the specified object */
static getPrototypeOf(obj: any): any;
/** Determines whether an object is extensible (can have new properties added to it) */
static isExtensible(obj: any): boolean;
/** Determines whether an object has been frozen (is immutable) */
static isFrozen(obj: any): boolean;
/** Determines whether an object is sealed (cannot add or delete properties) */
static isSealed(obj: any): boolean;
/** Returns an array of all enumerable property names on an object */
static keys(obj: any): string[];
/** Prevents new properties from being added to an object but allows modification of existing ones */
static preventExtensions(obj: any): any;
/** Prevents all modifications to an object except for reading and writing property values */
static seal(obj: any): any;
/** Determines whether an object has a property with the specified name (direct property, not inherited) */
hasOwnProperty(prop: string): boolean;
/** Determines whether an object is in the prototype chain of another object */
isPrototypeOf(obj: any): boolean;
/** Determines whether an object property is enumerable (would be included in a for-in loop) */
propertyIsEnumerable(prop: string): boolean;
/** Returns a localized string representation of the object (format depends on locale) */
toLocaleString(): string;
}
-94
View File
@@ -1,94 +0,0 @@
/**
* ECMAScript 5.1 - RegExp type for pattern matching and string manipulation.
* Create with the RegExp constructor or literal syntax: /pattern/flags
*
* ## How to Use
*
* ### Creating Regular Expressions
* ```js
* // Method 1: Regex literal (preferred)
* var re = /hello/;
* var reFlags = /hello/gi; // g=global, i=ignore case, m=multiline
*
* // Method 2: Constructor (useful for dynamic patterns)
* var re2 = new RegExp("hello");
* var re3 = new RegExp("hello", "gi");
* var dynamic = new RegExp(playerName); // Build pattern from variable
* ```
*
* ### Testing for Matches
* ```js
* /\d+/.test("abc123"); // true — contains digits
* /^\d+$/.test("abc123"); // false — not ALL digits
* /^\d+$/.test("12345"); // true — all digits
* /hello/i.test("Hello World"); // true — case insensitive
* ```
*
* ### Extracting Matches
* ```js
* var match = /\d+/.exec("abc123def"); // ["123"]
* var noMatch = /\d+/.exec("no digits"); // null
*
* // With capturing groups
* var result = /(\w+)@(\w+)/.exec("user@domain");
* // result[0] = "user@domain" (full match)
* // result[1] = "user" (first group)
* // result[2] = "domain" (second group)
* ```
*
* ### Using with String Methods
* ```js
* "abc123".match(/\d+/); // ["123"]
* "abc123".search(/\d/); // 3 (index of first digit)
* "abc123".replace(/\d+/, "NUM"); // "abcNUMdef"
* "a,b,,c".split(/,+/); // ["a", "b", "c"]
* ```
*
* ### RegExp Properties
* ```js
* var re = /hello/gi;
* re.source; // "hello"
* re.global; // true
* re.ignoreCase; // true
* re.multiline; // false
* re.lastIndex; // 0 (changes with global exec/test)
* ```
*
* ### ❌ Common Mistakes
* ```js
* RegExp.test("string"); // TypeError — test is an INSTANCE method!
* new RegExp.test("string"); // TypeError — incorrect syntax
* // ✅ CORRECT:
* /pattern/.test("string"); // Use on a regex instance
* new RegExp("pattern").test("string"); // Or create instance first
*
* // Double-escape backslashes in constructor strings:
* new RegExp("\d+"); // Wrong — \d becomes just d
* new RegExp("\\d+"); // ✅ Correct — \\d becomes \d
* ```
*/
export interface RegExp {
/** The pattern string that was used to create this regular expression */
source: string;
/** True if the 'g' (global) flag is set, affecting match behavior in exec() and test() */
global: boolean;
/** True if the 'i' (ignore case) flag is set, making pattern matching case-insensitive */
ignoreCase: boolean;
/** True if the 'm' (multiline) flag is set, affecting ^ and $ anchor behavior */
multiline: boolean;
/** The index at which to start searching in the string (used with 'g' flag in exec() loops) */
lastIndex: number;
/** Searches the string for a match and returns an array of matches or null if no match found */
exec(string: string): any[];
/** Tests whether the pattern matches the string, returning true or false */
test(string: string): boolean;
/** Returns a string representation of the regular expression (e.g., "/pattern/flags") */
toString(): string;
}
-82
View File
@@ -1,82 +0,0 @@
/**
* ECMAScript 5.1 - String type for working with text. Strings are immutable sequences of characters.
* Use String.fromCharCode() to create a string from character codes.
*
* ## How to Use
*
* ### Creating Strings
* ```js
* var greeting = "Hello, world!"; // String literal (double quotes)
* var name = 'Steve'; // String literal (single quotes)
* var fromCode = String.fromCharCode(65); // "A" (from char code)
* ```
*
* ### Searching & Checking
* ```js
* var str = "Hello, world!";
* str.indexOf("world"); // 7
* str.indexOf("missing"); // -1 (not found)
* str.lastIndexOf("l"); // 10
* str.search(/world/); // 7 (regex search)
* str.charAt(0); // "H"
* str.charCodeAt(0); // 72
* str.length; // 13
* ```
*
* ### Extracting & Transforming
* ```js
* var str = "Hello, world!";
* str.slice(7, 12); // "world"
* str.substring(0, 5); // "Hello"
* str.toUpperCase(); // "HELLO, WORLD!"
* str.toLowerCase(); // "hello, world!"
* str.trim(); // Removes leading/trailing whitespace
* str.replace("world", "NPC"); // "Hello, NPC!"
* str.replace(/l/g, "L"); // "HeLLo, worLd!" (regex with global flag)
* ```
*
* ### Splitting & Joining
* ```js
* "a,b,c".split(","); // ["a", "b", "c"]
* "hello".split(""); // ["h", "e", "l", "l", "o"]
* ["a", "b", "c"].join("-"); // "a-b-c" (Array.join, but related)
* "one two three".split(" ", 2); // ["one", "two"] (limit results)
* ```
*
* ### Pattern Matching
* ```js
* "abc123".match(/\d+/); // ["123"]
* "no numbers".match(/\d+/); // null
* "hello".concat(" ", "world"); // "hello world"
* ```
*
* ### ❌ Common Mistakes
* ```js
* str.replace("l", "L"); // Only replaces FIRST "l" — use /l/g for all
* String.charAt(0); // TypeError — instance method, not static
* "abc"[0]; // May not work in all engines — use charAt()
* ```
*/
export interface String {
/** The number of characters in the string */
length: number;
/** Creates a string from one or more Unicode character codes (e.g., String.fromCharCode(65, 66, 67) returns "ABC") */
static fromCharCode(...codes: number[]): string;
/** Returns the Unicode code point (0–65535) of the character at the specified index. Unlike Java's charAt() + cast, this returns the numeric code directly. */
charCodeAt(pos: number): number;
/** Tests the string against a regular expression and returns an array of matches, or null if no match found */
match(regexp: any): any[];
/**
* Replaces a pattern (string or RegExp object) with a replacement string.
* Unlike Java's replace/replaceAll which only accept String/CharSequence,
* this accepts a RegExp object as the first argument.
*/
replace(searchValue: any, replaceValue: any): string;
/** Returns the index of the first character that matches a regular expression, or -1 if not found */
search(regexp: any): number;
}
Submodule gradle-plugins deleted from 19dc9a8361.
+9
View File
@@ -0,0 +1,9 @@
/.gradle
/build
/out
/bin
/.idea
/.vscode
/.settings
.project
.classpath
+94
View File
@@ -0,0 +1,94 @@
# dts-gradle-plugin
This repo contains the Gradle plugin for generating TypeScript `.d.ts` files for the CustomNPC-Plus API.
These files are used for the generation of auto-completion suggestions and type/interface documentation when scripting
in the Script Editor in-game.
### Implementation using JitPack
Add JitPack to the buildscript and depend on the plugin JAR. Using `main-SNAPSHOT` will build the latest `main` commit;
for reproducible builds use a tag or commit hash instead.
`settings.gradle`
```gradle
pluginManagement {
resolutionStrategy {
eachPlugin {
if(requested.id.toString() == "dts.typescript-generator") {
useModule("com.github.bigguy345:dts-gradle-plugin:main-SNAPSHOT")
}
}
}
repositories {
maven { url "https://jitpack.io" }
gradlePluginPortal()
mavenCentral()
mavenLocal()
}
}
```
`build.gradle`:
```gradle
plugins {
id 'dts.typescript-generator'
}
// ============================================================================
// TypeScript Definition Generation Task
// Generates .d.ts files from Java API sources for scripting IDE support
// ============================================================================
// TypeScript plugin is applied above in the main plugins block
tasks.named("generateTypeScriptDefinitions").configure {
// Source directories containing the Java API code
sourceDirectories = ['src/main/java']
// Packages in source directories to generate .d.ts files for
apiPackages = ['noppes.npcs.api'] as Set
// Output directory for the generated .d.ts files
// Must be within resources/assets/${modId}/api to be detected by CNPC+
outputDirectory = "src/main/resources/assets/${modId}/api"
// Whether to clean old generated files before regenerating
cleanOutputFirst = true
// Optional: copy external patch .d.ts files into assets/<modid>/api/patches
patchesDirectory = "dts-patches"
}
// Optional: To ensure definitions are generated on processing resources on jar build
// But in most cases, you may want to run the task manually when needed
// processResources.dependsOn generateTypeScriptDefinitions
```
---
## Patches (optional overrides)
Use `dts-patches/` to override or refine generated types. Files in this folder are copied to
`assets/<modid>/api/patches` after generation.
### Example: override `IPlayer.getDBCPlayer()` to return `IDBCAddon` instead of `IDBCPlayer`
File: `dts-patches/IPlayer.d.ts`
```ts
/**
* DBC Addon patch for IPlayer
* @javaFqn noppes.npcs.api.entity.IPlayer
*/
export interface IPlayer<T> {
getDBCPlayer(): IDBCAddon;
}
```
+50
View File
@@ -0,0 +1,50 @@
plugins {
id 'groovy-gradle-plugin'
id 'maven-publish'
}
group = 'dts'
version = '1.0.0'
repositories {
mavenCentral()
}
dependencies {
implementation gradleApi()
implementation localGroovy()
}
// Configure source sets if building as standalone
sourceSets {
main {
groovy {
srcDirs = ['src/main/groovy']
}
resources {
srcDirs = ['src/main/resources']
}
}
}
gradlePlugin {
plugins {
typescriptGenerator {
id = 'dts.typescript-generator'
implementationClass = 'dts.TypeScriptGeneratorPlugin'
displayName = 'TypeScript Definition Generator'
description = 'Generates TypeScript definition files from Java API sources'
}
}
}
publishing {
repositories {
mavenLocal()
}
}
// Handle duplicate resources
tasks.processResources {
duplicatesStrategy = 'include'
}
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'dts-gradle-plugin'
@@ -0,0 +1,175 @@
package dts
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Optional
/**
* Gradle task that generates TypeScript definition (.d.ts) files from Java API sources.
*
* Usage in build.gradle:
*
* tasks.withType(GenerateTypeScriptTask).configureEach {
* sourceDirectories = ['src/api/java'] // Strings are converted to Files
* outputDirectory = 'src/main/resources/${modid}/api' // String converted to File
* apiPackages = ['noppes.npcs.api', 'kamkeel.npcdbc.api']
* }
*/
abstract class GenerateTypeScriptTask extends DefaultTask {
// Accept Object types (String or File) with @Internal annotation
@Internal
List<Object> sourceDirectories = []
@Internal
Object outputDirectory
@Input
Set<String> apiPackages = []
@Input
Boolean cleanOutputFirst = false
@Input
List<String> excludePatterns = []
@Internal
Object patchesDirectory
// Provide task input/output properties that Gradle can validate
@InputFiles
protected List<File> getResolvedSourceDirectories() {
return sourceDirectories.collect { obj ->
if (obj instanceof File) return obj
String pathStr = obj.toString()
if (pathStr.contains('${modid}')) {
String modid = project.archivesBaseName ?: 'mod'
pathStr = pathStr.replace('${modid}', modid)
}
File f = new File(pathStr)
if (!f.isAbsolute()) {
f = new File(project.projectDir, pathStr)
}
return f
}
}
@OutputDirectory
protected File getResolvedOutputDirectory() {
def obj = outputDirectory
if (obj instanceof File) return obj
String pathStr = obj.toString()
if (pathStr.contains('${modid}')) {
String modid = project.archivesBaseName ?: 'mod'
pathStr = pathStr.replace('${modid}', modid)
}
File f = new File(pathStr)
if (!f.isAbsolute()) {
f = new File(project.projectDir, pathStr)
}
return f
}
@Optional
@InputDirectory
protected File getResolvedDtsPatchesDirectory() {
if (patchesDirectory == null) return null
def obj = patchesDirectory
if (obj instanceof File) return obj
String pathStr = obj.toString()
if (pathStr.contains('${modid}')) {
String modid = project.archivesBaseName ?: 'mod'
pathStr = pathStr.replace('${modid}', modid)
}
File f = new File(pathStr)
if (!f.isAbsolute()) {
f = new File(project.projectDir, pathStr)
}
return f
}
/**
* Converts a value (String or File) to a File object.
* Supports special tokens like ${modid}.
*/
// conversion logic inlined into getters to avoid calling private helper at configuration time
GenerateTypeScriptTask() {
group = 'api'
description = 'Generates TypeScript definition files from Java API sources'
}
@TaskAction
void generate() {
List<File> srcDirs = getResolvedSourceDirectories()
File outDir = getResolvedOutputDirectory()
File patchesDir = getResolvedDtsPatchesDirectory()
logger.lifecycle("=".multiply(60))
logger.lifecycle("Generating TypeScript definitions...")
logger.lifecycle("=".multiply(60))
if (srcDirs.isEmpty()) {
logger.warn("No source directories specified!")
return
}
// Validate directories
srcDirs.each { dir ->
if (!dir.exists()) {
logger.warn("Source directory does not exist: ${dir}")
} else {
logger.lifecycle("Source: ${dir}")
}
}
logger.lifecycle("Output: ${outDir}")
logger.lifecycle("API Packages: ${apiPackages}")
// Clean output if requested
if (cleanOutputFirst && outDir.exists()) {
logger.lifecycle("Cleaning output directory...")
outDir.eachFileRecurse { file ->
if (file.name.endsWith('.d.ts') && !file.name.equals('minecraft-raw.d.ts') && !file.name.equals('forge-events-raw.d.ts')) {
file.delete()
}
}
}
// Create converter and process
JavaToTypeScriptConverter converter = new JavaToTypeScriptConverter(outDir, apiPackages)
List<File> validDirs = srcDirs.findAll { it.exists() }
if (validDirs.isEmpty()) {
logger.error("No valid source directories found!")
return
}
converter.processDirectories(validDirs, logger)
if (patchesDir != null) {
if (!patchesDir.exists()) {
logger.lifecycle("Patches directory does not exist: ${patchesDir}")
} else {
File patchOutputDir = new File(outDir, "patches")
if (patchOutputDir.exists()) {
patchOutputDir.deleteDir()
}
project.copy {
from patchesDir
into patchOutputDir
}
logger.lifecycle("Copied .d.ts patches to: ${patchOutputDir}")
}
}
logger.lifecycle("=".multiply(60))
logger.lifecycle("TypeScript definition generation complete!")
logger.lifecycle("=".multiply(60))
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,17 @@
package dts
import org.gradle.api.Plugin
import org.gradle.api.Project
/**
* Gradle plugin for generating TypeScript definition files from Java API sources.
*/
class TypeScriptGeneratorPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
if (project.tasks.findByName('generateTypeScriptDefinitions') == null) {
project.tasks.register('generateTypeScriptDefinitions', GenerateTypeScriptTask)
}
}
}
@@ -0,0 +1 @@
implementation-class=dts.TypeScriptGeneratorPlugin
+1 -1
View File
@@ -199,7 +199,7 @@ disableCheckstyle = true
# ideaCheckSpotlessOnBuild = true # ideaCheckSpotlessOnBuild = true
# Non-GTNH properties # Non-GTNH properties
modVersion = 1.11.2 modVersion = 1.11.0
# Increase Gradle's JVM memory usage to avoid daemon expiration due to # Increase Gradle's JVM memory usage to avoid daemon expiration due to
# insufficient heap space on CI builds. # insufficient heap space on CI builds.
Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 554 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 114 KiB

After

Width:  |  Height:  |  Size: 114 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 135 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 337 KiB

After

Width:  |  Height:  |  Size: 337 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 MiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 227 KiB

After

Width:  |  Height:  |  Size: 227 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 230 KiB

After

Width:  |  Height:  |  Size: 230 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 573 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 787 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 MiB

+1 -1
Submodule src/api updated: e7f363727e...f383fc3037.
@@ -1,21 +0,0 @@
package kamkeel.npcs.fixtures;
/**
* One piece of content, the category it belongs in, and why it exists.
*
* <p>The note is the part that does not survive serialization. A directory of numbered files says
* nothing about which one is the dialog whose availability is gated four ways, and the next person
* to need that case will otherwise author a second one.
*/
public final class Case<T> {
public final String category;
public final T value;
public final String note;
public Case(String category, T value, String note) {
this.category = category;
this.value = value;
this.note = note;
}
}
@@ -1,118 +0,0 @@
package kamkeel.npcs.fixtures;
import kamkeel.npcs.fixtures.worlds.DefaultsWorld;
import kamkeel.npcs.fixtures.worlds.EdgeWorld;
import kamkeel.npcs.fixtures.worlds.LegacyWorld;
import kamkeel.npcs.fixtures.worlds.MaximalWorld;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Generates CustomNPC+ save data offline, for use as test fixtures.
*
* <p>The point is that the bytes are written by CustomNPC+ itself. Hand-authoring a
* {@code factions.dat} that looks right is easy and proves nothing: it asserts what its author
* believed the format to be. Everything here goes through the shipping data classes' own
* serialization, so a fixture is evidence about the format rather than about the author.
*
* <p>Usage: {@code gradlew scribeFixtures -Pout=<dir> [-Pworlds=maximal,edge]}
*/
public final class FixtureGenerator {
private static final List<FixtureWorld> ALL = Arrays.<FixtureWorld>asList(
new MaximalWorld(),
new DefaultsWorld(),
new EdgeWorld(),
new LegacyWorld());
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("usage: FixtureGenerator <output-dir> [--worlds a,b,c]");
System.exit(2);
}
File out = new File(args[0]).getAbsoluteFile();
List<FixtureWorld> selected = new ArrayList<FixtureWorld>(ALL);
for (int i = 1; i < args.length - 1; i++) {
if ("--worlds".equals(args[i])) {
selected = select(args[i + 1]);
}
}
System.out.println("[fixtures] bootstrapping Minecraft");
Fixtures.bootMinecraft();
Manifest manifest = new Manifest();
recordKnownWarnings(manifest);
int normalized = 0;
for (FixtureWorld world : selected) {
WorldWriter writer = new WorldWriter(out, world.name(), manifest);
manifest.world(world.name(), world.purpose());
int before = manifest.count();
world.build(writer);
normalized += writer.normalizedCount();
System.out.println("[fixtures] " + pad(world.name())
+ (manifest.count() - before) + " files");
}
manifest.write(new File(out, "manifest.json"));
Readme.write(new File(out, "README.md"), selected, manifest);
System.out.println("[fixtures] " + manifest.count() + " files total -> " + out);
System.out.println("[fixtures] dialogs " + manifest.countOf("dialog")
+ ", quests " + manifest.countOf("quest"));
// Reported every run so the one normalization cannot quietly spread to other keys.
System.out.println("[fixtures] " + normalized + " wall-clock values pinned (TimePast)");
}
/**
* Facts a consumer cannot get from the bytes, and would otherwise learn from a flaky test.
*
* <p>Each was found by reading the writer, not by guessing.
*/
private static void recordKnownWarnings(Manifest manifest) {
manifest.warn("NORMALIZED: TimePast is pinned to 0 in every document. PlayerMail.writeNBT "
+ "stamps it with System.currentTimeMillis() - time, and a PlayerMail hangs off every "
+ "dialog and every quest whether or not mail was configured -- so left alone, every "
+ "file here would differ between two runs and a version-controlled corpus would churn "
+ "completely on each regeneration. This is the ONLY key these fixtures rewrite after "
+ "CustomNPC+ produced it. Nothing reads the value back except a live-clock display.");
manifest.warn("Quest.writeToNBTPartial writes NextQuestTitle from the live QuestController, "
+ "which is empty offline, so NextQuestTitle is written as the value set on the object "
+ "rather than resolved from the target quest. NextQuestId is the real link.");
manifest.warn("PlayerMail.writeNBT writes MailQuestTitle only when the quest resolves in the "
+ "live QuestController. Offline it never resolves, so the key is absent.");
manifest.warn("These worlds hold no level.dat and no region files. They are the customnpcs/ "
+ "directory of a world, which is the part CustomNPC+ owns.");
}
private static List<FixtureWorld> select(String csv) {
Map<String, FixtureWorld> byName = new LinkedHashMap<String, FixtureWorld>();
for (FixtureWorld w : ALL) {
byName.put(w.name(), w);
}
List<FixtureWorld> selected = new ArrayList<FixtureWorld>();
for (String name : csv.split(",")) {
FixtureWorld w = byName.get(name.trim());
if (w == null) {
throw new IllegalArgumentException("No such world: " + name + " (have " + byName.keySet() + ")");
}
selected.add(w);
}
return selected;
}
private static String pad(String name) {
StringBuilder sb = new StringBuilder(name);
while (sb.length() < 12) {
sb.append(' ');
}
return sb.toString();
}
}
@@ -1,13 +0,0 @@
package kamkeel.npcs.fixtures;
/** One generated world. Each answers a different question, so tests can load only what they need. */
public interface FixtureWorld {
/** Directory name, and the name a test refers to. */
String name();
/** What this world is for. Goes into the manifest, because a folder of ids explains nothing. */
String purpose();
void build(WorldWriter out);
}
@@ -1,168 +0,0 @@
package kamkeel.npcs.fixtures;
import cpw.mods.fml.common.Loader;
import kamkeel.npcs.addon.DBCAddon;
import net.minecraft.init.Bootstrap;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import noppes.npcs.NoppesUtilServer;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
/**
* Shared machinery for the fixture generator: bringing Minecraft far enough up to serialize, and
* building the item stacks the content refers to.
*
* <p>Nothing here decides what a fixture contains. That lives in the world builders.
*/
public final class Fixtures {
/**
* A fixed instant, used everywhere a fixture wants a timestamp.
*
* <p>2021-03-14T01:59:26Z. Any constant would do; what matters is that it is a constant, so
* two runs of the generator produce the same bytes and a diff means something changed.
*/
public static final long EPOCH = 1615687166000L;
private static boolean booted;
private Fixtures() {
}
/**
* Registers vanilla blocks and items so item stacks can be serialized.
*
* <p>{@link Item#itemRegistry} is Forge's {@code FMLControlledNamespacedRegistry}, and
* {@link noppes.npcs.NoppesUtilServer#writeItem} asks it for a registry name -- so a stack
* written before this call would be saved as {@code minecraft:air} rather than failing, which
* is the quiet kind of wrong.
*/
public static void bootMinecraft() {
if (booted) {
return;
}
installBareLoader();
Bootstrap.func_151354_b();
// PlayerData.getNBT ends with DBCAddon.instance.writeToNBT(...), and the field is only set
// by the constructor. DBCAddon is a shell whose methods a companion mod replaces by mixin,
// so every method here is a no-op -- constructing one costs nothing and is what stops a
// player record from throwing on its last line. Without the addon installed this is
// exactly the state a real server is in.
new DBCAddon();
booted = true;
verifyRegistry();
}
/**
* Makes {@code Loader.instance()} answerable without launching FML.
*
* <p>Registering an item goes {@code FMLControlledNamespacedRegistry.addObject} ->
* {@code GameData.register} -> {@code GameData.addPrefix}, and addPrefix asks
* {@code Loader.instance().activeModContainer()} which namespace to use. Reaching that
* normally constructs a {@code Loader}, whose constructor builds a {@code ModClassLoader} and
* casts its parent to LaunchWrapper's {@code LaunchClassLoader} -- which fails outside a
* LaunchWrapper launch, and is where this generator first stopped.
*
* <p>So the singleton is filled with an allocated-but-unconstructed Loader. Its
* {@code modController} is null, {@code activeModContainer()} returns null, and addPrefix
* takes its own documented branch: <i>"no mod container, assume minecraft"</i>. That is
* exactly the branch real vanilla registration takes, because no mod is active while
* {@code Item.registerItems()} runs.
*
* <p>Nothing about the naming rule is reimplemented here -- Forge still computes it. What this
* removes is only the classloader assumption. {@link #verifyRegistry()} then checks the result
* against what real CustomNPC+ save files contain, so the shortcut is measured rather than
* trusted. On the registration path {@code Loader} is touched at that one call and nowhere
* else; the other uses in GameData are world remapping and mod-declared substitutions.
*/
private static void installBareLoader() {
try {
Field instance = Loader.class.getDeclaredField("instance");
instance.setAccessible(true);
if (instance.get(null) != null) {
return;
}
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
instance.set(null, unsafe.allocateInstance(Loader.class));
} catch (Exception e) {
throw new IllegalStateException(
"Could not install a bare FML Loader. Without it the item registry cannot be "
+ "populated outside a LaunchWrapper launch.", e);
}
}
/**
* Checks that registration produced the names real save files contain.
*
* <p>{@code minecraft:diamond}, not {@code diamond}: the prefix comes from Forge, and a
* generator that quietly lost it would emit fixtures that every reader tested against them
* would then agree with. The expected values here were read out of the CustomNPC+ worlds in
* {@code run/saves/}, not from the code that produces them.
*/
private static void verifyRegistry() {
String diamond = Item.itemRegistry.getNameForObject(Items.diamond);
if (!"minecraft:diamond".equals(diamond)) {
throw new IllegalStateException("Item registry produced '" + diamond
+ "' where real CustomNPC+ saves contain 'minecraft:diamond'. Item stacks in these "
+ "fixtures would not match anything the mod writes.");
}
NBTTagCompound probe = new NBTTagCompound();
NoppesUtilServer.writeItem(new ItemStack(Items.golden_apple, 2, 1), probe);
if (!"minecraft:golden_apple".equals(probe.getString("id"))
|| probe.getByte("Count") != 2
|| probe.getShort("Damage") != 1) {
throw new IllegalStateException(
"NoppesUtilServer.writeItem produced " + probe + ", which is not an item stack.");
}
}
/** A stack of a vanilla item, by registry name, so the fixture reads as what it is. */
public static ItemStack item(String registryName, int count, int damage) {
Item item = (Item) Item.itemRegistry.getObject(registryName);
if (item == null) {
throw new IllegalArgumentException("No such item: " + registryName);
}
return new ItemStack(item, count, damage);
}
public static ItemStack item(String registryName, int count) {
return item(registryName, count, 0);
}
/**
* A stack carrying custom NBT, which is the case that matters most to Scribe: item state above
* (id, damage) is what the Flattening and Data Components rearranged.
*/
public static ItemStack namedItem(String registryName, int count, int damage, String displayName) {
ItemStack stack = item(registryName, count, damage);
NBTTagCompound display = new NBTTagCompound();
display.setString("Name", displayName);
NBTTagList lore = new NBTTagList();
lore.appendTag(new NBTTagString("Written by the Scribe fixture generator"));
display.setTag("Lore", lore);
NBTTagCompound tag = new NBTTagCompound();
tag.setTag("display", display);
tag.setBoolean("Unbreakable", true);
tag.setInteger("RepairCost", 7);
stack.stackTagCompound = tag;
return stack;
}
/**
* A stack whose identity is a pre-Flattening variant -- damage as a variant selector rather
* than durability. Scribe converts these through a table that throws on a gap, so a fixture
* holding one is the only way to find out which entries the table is still missing.
*/
public static ItemStack variant(String registryName, int count, int variantDamage) {
return item(registryName, count, variantDamage);
}
}
@@ -1,159 +0,0 @@
package kamkeel.npcs.fixtures;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* An index of what was generated, why, and where it landed.
*
* <p>Deliberately not a second copy of the data. The files are the fixture; this says which file
* holds which case, so a test can pick the one it needs without opening twenty of them, and so a
* reviewer can see the intent that a compound of integers does not carry.
*/
public final class Manifest {
/** One generated file. */
public static final class Entry {
final String world;
final String system;
final String id;
final String path;
final String note;
Entry(String world, String system, String id, String path, String note) {
this.world = world;
this.system = system;
this.id = id;
this.path = path;
this.note = note;
}
}
private final List<Entry> entries = new ArrayList<Entry>();
private final Set<String> warnings = new LinkedHashSet<String>();
private final List<String[]> worlds = new ArrayList<String[]>();
public void world(String name, String purpose) {
worlds.add(new String[]{name, purpose});
}
public void record(String world, String system, String id, String path, String note) {
entries.add(new Entry(world, system, id, path, note));
}
/**
* Records something a consumer of these fixtures has to know and could not discover from the
* bytes -- above all, the places CustomNPC+ writes a value that changes between runs.
*/
public void warn(String warning) {
warnings.add(warning);
}
public Set<String> warnings() {
return warnings;
}
public int count() {
return entries.size();
}
public int countOf(String system) {
int n = 0;
for (Entry e : entries) {
if (e.system.equals(system)) {
n++;
}
}
return n;
}
public void write(File file) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" \"generatedBy\": \"CustomNPC+ scribeFixtures\",\n");
sb.append(" \"note\": \"The files are the fixture. This index records intent and location, ");
sb.append("not a second copy of the data. Readable renderings of every .dat sit under ");
sb.append("<world>/_readable/, written by CustomNPC+'s own NBTJsonUtil.\",\n");
sb.append(" \"warnings\": [\n");
int wi = 0;
for (String w : warnings) {
sb.append(" ").append(quote(w));
sb.append(++wi < warnings.size() ? ",\n" : "\n");
}
sb.append(" ],\n");
sb.append(" \"worlds\": {\n");
for (int i = 0; i < worlds.size(); i++) {
String[] w = worlds.get(i);
sb.append(" ").append(quote(w[0])).append(": ").append(quote(w[1]));
sb.append(i + 1 < worlds.size() ? ",\n" : "\n");
}
sb.append(" },\n");
sb.append(" \"entries\": [\n");
for (int i = 0; i < entries.size(); i++) {
Entry e = entries.get(i);
sb.append(" {");
sb.append("\"world\": ").append(quote(e.world));
sb.append(", \"system\": ").append(quote(e.system));
sb.append(", \"id\": ").append(quote(e.id));
sb.append(", \"path\": ").append(quote(e.path));
sb.append(", \"note\": ").append(quote(e.note));
sb.append("}");
sb.append(i + 1 < entries.size() ? ",\n" : "\n");
}
sb.append(" ]\n");
sb.append("}\n");
Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
try {
out.write(sb.toString());
} finally {
out.close();
}
}
/**
* JSON string escaping. Hand-rolled rather than pulled from a library because the manifest is
* the one file here that is not written by CustomNPC+, so it should have no dependency that
* could change what it produces between environments.
*/
private static String quote(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
default:
if (c < 0x20 || c > 0x7E) {
sb.append(String.format("\\u%04x", (int) c));
} else {
sb.append(c);
}
}
}
return sb.append('"').toString();
}
}
@@ -1,73 +0,0 @@
package kamkeel.npcs.fixtures;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Replaces the values CustomNPC+ writes from the wall clock with a constant.
*
* <p>This is the one place a generated file departs from what the mod would write, and it exists
* because of a specific property of one writer. {@code PlayerMail.writeNBT} does:
*
* <pre>compound.setLong("TimePast", System.currentTimeMillis() - time);</pre>
*
* <p>and a {@code PlayerMail} hangs off every dialog and every quest whether or not any mail was
* configured -- so <i>every</i> dialog and quest file differs between two runs, on that one key.
*
* <p><b>Why normalize rather than document and accept.</b> There is no "the" value here to be
* faithful to; the mod writes a different one every second. Left alone, regenerating rewrites all
* 70-odd files, so a corpus held in version control churns completely on every run and a real
* change is invisible in the noise. Pinning it to zero makes the corpus byte-reproducible, which
* is what lets a diff mean something.
*
* <p>Zero is also the honest value: {@code TimePast} means "how long ago, relative to now", and a
* file on disk has no now. Nothing reads it back -- {@code PlayerMail.readNBT} loads
* {@code timePast} and the field is only used for display against a live clock.
*
* <p>Every key touched is listed here rather than matched by pattern, and the count is reported,
* so this can never quietly grow to cover a field that actually matters.
*/
public final class Normalize {
/** Keys written from the wall clock. Exhaustive, and each one deliberate. */
private static final List<String> WALL_CLOCK_KEYS = Arrays.asList("TimePast");
private Normalize() {
}
/** Rewrites wall-clock keys in place, at any depth. Returns how many were changed. */
public static int wallClock(NBTTagCompound compound) {
int changed = 0;
for (String key : keysOf(compound)) {
NBTBase tag = compound.getTag(key);
if (tag == null) {
continue;
}
if (WALL_CLOCK_KEYS.contains(key) && tag.getId() == 4) {
compound.setLong(key, 0L);
changed++;
} else if (tag.getId() == 10) {
changed += wallClock((NBTTagCompound) tag);
} else if (tag.getId() == 9) {
NBTTagList list = (NBTTagList) tag;
if (list.func_150303_d() == 10) {
for (int i = 0; i < list.tagCount(); i++) {
// getCompoundTagAt returns the live entry, so this edits in place.
changed += wallClock(list.getCompoundTagAt(i));
}
}
}
}
return changed;
}
@SuppressWarnings("unchecked")
private static List<String> keysOf(NBTTagCompound compound) {
return new ArrayList<String>(compound.func_150296_c());
}
}
@@ -1,81 +0,0 @@
package kamkeel.npcs.fixtures;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
/** Writes the README that ships beside the generated worlds. */
public final class Readme {
private Readme() {
}
public static void write(File file, List<FixtureWorld> worlds, Manifest manifest) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("# CustomNPC+ fixtures\n\n");
sb.append("Generated by `gradlew scribeFixtures` in the CustomNPC+ repository, on the\n");
sb.append("`scribe` branch. Do not edit by hand -- regenerate.\n\n");
sb.append("## What these are\n\n");
sb.append("Real CustomNPC+ save data, written by CustomNPC+'s own serialization running\n");
sb.append("against a bootstrapped-but-unlaunched Minecraft. No world was played to produce\n");
sb.append("them and no byte here was hand-authored.\n\n");
sb.append("That distinction is the whole point. A hand-written `factions.dat` asserts what\n");
sb.append("its author believed the format to be, so a reader tested against it only proves\n");
sb.append("it agrees with that belief. These files are evidence about the format itself.\n\n");
sb.append("## Layout\n\n");
sb.append("```\n");
for (FixtureWorld world : worlds) {
sb.append(world.name()).append("/customnpcs/ <- a CustomNPC+ world directory, and nothing else\n");
}
sb.append("_readable/<world>/ <- NBTJsonUtil renderings of the .dat files, for humans\n");
sb.append("manifest.json <- which file holds which case, and why\n");
sb.append("```\n\n");
sb.append("Each `<world>/` holds `customnpcs/` and nothing else, so it drops straight into\n");
sb.append("a save directory -- or, in Scribe, works as-is as a `cnpc_data_sets` overlay.\n");
sb.append("The readable renderings sit outside the world directories for that reason.\n\n");
sb.append("`_readable/` is a debugging aid, not a fixture: it is CustomNPC+'s own JSON\n");
sb.append("rendering, which suffixes scalars with their type (`5b`, `5L`, `1.0f`) and is\n");
sb.append("therefore deliberately not strict JSON. The widths being visible is the point.\n\n");
sb.append("## The worlds\n\n");
for (FixtureWorld world : worlds) {
sb.append("- **`").append(world.name()).append("`** -- ").append(world.purpose()).append("\n");
}
sb.append("\n");
sb.append("## Two formats, not one\n\n");
sb.append("- **`.dat`** -- gzipped NBT, written with `CompressedStreamTools`. Factions,\n");
sb.append(" custom effects, recipes, magic, animations, linked items, tags, and the rest.\n");
sb.append("- **Dialogs and quests are not `.dat`.** They are `NBTJsonUtil` text files at\n");
sb.append(" `customnpcs/dialogs/<category>/<id>.json`. The directory *is* the category and\n");
sb.append(" the filename *is* the id -- neither appears inside the file, because\n");
sb.append(" `saveDialog` writes `writeToNBTPartial`, which omits `DialogId`.\n\n");
sb.append("## Reproducibility\n\n");
sb.append("Regenerating produces byte-identical output, with the exceptions below. Those\n");
sb.append("are properties of CustomNPC+'s writers, not of this generator.\n\n");
for (String warning : manifest.warnings()) {
sb.append("- ").append(warning).append("\n");
}
sb.append("\n");
sb.append("## Totals\n\n");
sb.append("`").append(manifest.count()).append("` files: ");
sb.append(manifest.countOf("dialog")).append(" dialogs, ");
sb.append(manifest.countOf("quest")).append(" quests, ");
sb.append(manifest.count() - manifest.countOf("dialog") - manifest.countOf("quest"));
sb.append(" other documents.\n");
Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
try {
out.write(sb.toString());
} finally {
out.close();
}
}
}
@@ -1,221 +0,0 @@
package kamkeel.npcs.fixtures;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.NoppesStringUtils;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.Quest;
import noppes.npcs.util.NBTJsonUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
/**
* Writes one CustomNPC+ world.
*
* <p><b>What is authoritative and what is copied.</b> Every byte of content here comes from
* CustomNPC+'s own {@code writeToNBT} / {@code writeNBT} and from {@link NBTJsonUtil} and
* {@link CompressedStreamTools}. What this class supplies is only <i>where the file goes and what
* it is called</i>, because the controllers reach that through
* {@code CustomNpcs.getWorldSaveDirectory()}, which returns null without a running server, and
* because every {@code save*} fires {@code SyncController.syncUpdate} into a network stack that
* does not exist offline.
*
* <p>So each method below names the controller and method it was copied from. If a layout changes
* upstream, that reference is where to look. The layout logic is a handful of lines per system;
* the serialization, which is the part a fixture actually asserts, is never reimplemented.
*
* <p>The generated {@code <world>/customnpcs/} directory is exactly a CustomNPC+ world and holds
* nothing else. Readable renderings of the binary files go in a sibling {@code _readable/} tree so
* that dropping {@code customnpcs/} into a real save is safe.
*/
public final class WorldWriter {
private final String world;
private final File root;
private final File customnpcs;
private final File readable;
private final Manifest manifest;
private int normalized;
public WorldWriter(File outputRoot, String world, Manifest manifest) {
this.world = world;
this.root = new File(outputRoot, world);
this.customnpcs = new File(root, "customnpcs");
// Outside the world directory, not inside it. A generated <world>/ is meant to be usable
// as a drop-in overlay -- Scribe's smoke harness copies a set's contents straight into a
// server's world -- so it must contain customnpcs/ and nothing else.
this.readable = new File(new File(outputRoot, "_readable"), world);
this.manifest = manifest;
mkdirs(customnpcs);
mkdirs(readable);
}
public String world() {
return world;
}
// ------------------------------------------------------------------
// Dialogs -- DialogController.saveDialog / loadCategoryDir
//
// The directory is the category and the filename is the id. Neither appears inside the file:
// saveDialog writes writeToNBTPartial, which omits DialogId, and loadCategoryDir recovers the
// id by parsing the filename. A dialog's identity is where it sits.
// ------------------------------------------------------------------
public void dialog(String category, Dialog dialog, String note) {
String dir = NoppesStringUtils.cleanFileName(category);
File file = new File(new File(customnpcs, "dialogs"), dir + "/" + dialog.id + ".json");
writeJson(file, dialog.writeToNBTPartial(new NBTTagCompound()));
manifest.record(world, "dialog", String.valueOf(dialog.id), rel(file), note);
}
// ------------------------------------------------------------------
// Quests -- QuestController.saveQuest / loadCategoryDir
//
// Same shape as dialogs, and the same identity rule.
// ------------------------------------------------------------------
public void quest(String category, Quest quest, String note) {
String dir = NoppesStringUtils.cleanFileName(category);
File file = new File(new File(customnpcs, "quests"), dir + "/" + quest.id + ".json");
writeJson(file, quest.writeToNBTPartial(new NBTTagCompound()));
manifest.record(world, "quest", String.valueOf(quest.id), rel(file), note);
}
// ------------------------------------------------------------------
// Custom effects -- CustomEffectController.saveCustomEffect / loadEffectsFromDir
//
// The filename is the name: loadEffectsFromDir overwrites whatever `name` the file contained
// with the filename minus .json. An empty category means the effect sits at the root of
// customeffects/, which is what CategoryManager calls Uncategorized -- there is no category
// file anywhere, only the directory.
// ------------------------------------------------------------------
public void effect(String category, CustomEffect effect, String note) {
effect(category, effect.getName(), effect, note);
}
/**
* As {@link #effect}, with the filename stated separately.
*
* <p>Needed because the filename and the {@code name} key are genuinely independent on disk,
* and a fixture proving the loader prefers the filename has to be able to disagree with it.
*/
public void effect(String category, String fileName, CustomEffect effect, String note) {
File dir = new File(customnpcs, "customeffects");
if (category != null && !category.isEmpty()) {
dir = new File(dir, NoppesStringUtils.cleanFileName(category));
}
File file = new File(dir, NoppesStringUtils.cleanFileName(fileName) + ".json");
writeJson(file, effect.writeToNBT(true));
manifest.record(world, "effect", String.valueOf(effect.id), rel(file), note);
}
/**
* A dialog written from a compound rather than from a {@link Dialog}.
*
* <p>Only for the legacy world, which ages a document by removing keys a newer CustomNPC+
* added. The compound still comes from CustomNPC+'s writer; what is synthesized is the
* subtraction. Every caller must say in its note which keys it removed and why.
*/
public void dialogRaw(String category, int id, NBTTagCompound compound, String note) {
String dir = NoppesStringUtils.cleanFileName(category);
File file = new File(new File(customnpcs, "dialogs"), dir + "/" + id + ".json");
writeJson(file, compound);
manifest.record(world, "dialog", String.valueOf(id), rel(file), note);
}
/** As {@link #dialogRaw}, for quests. */
public void questRaw(String category, int id, NBTTagCompound compound, String note) {
String dir = NoppesStringUtils.cleanFileName(category);
File file = new File(new File(customnpcs, "quests"), dir + "/" + id + ".json");
writeJson(file, compound);
manifest.record(world, "quest", String.valueOf(id), rel(file), note);
}
/**
* A gzipped NBT document at the root of the world.
*
* <p>The shape every {@code .dat} controller uses -- FactionController.saveFactions,
* CustomEffectController.saveCustomEffects, GlobalDataController.save and the rest: build one
* compound, {@code CompressedStreamTools.writeCompressed} it, rotate the previous file to
* {@code _old}. The rotation is not reproduced, because a generated world has no previous file
* and inventing a {@code .dat_old} would be inventing history.
*/
public void dat(String system, String fileName, NBTTagCompound compound, String note) {
File file = new File(customnpcs, fileName);
mkdirs(file.getParentFile());
normalized += Normalize.wallClock(compound);
try {
OutputStream out = new FileOutputStream(file);
try {
CompressedStreamTools.writeCompressed(compound, out);
} finally {
out.close();
}
} catch (IOException e) {
throw new IllegalStateException("Failed writing " + file, e);
}
renderReadable(fileName, compound);
manifest.record(world, system, fileName, rel(file), note);
}
/** A JSON document at an explicit path under {@code customnpcs/}, for the per-player records. */
public void json(String system, String id, String relativePath, NBTTagCompound compound, String note) {
File file = new File(customnpcs, relativePath);
writeJson(file, compound);
manifest.record(world, system, id, rel(file), note);
}
private void writeJson(File file, NBTTagCompound compound) {
mkdirs(file.getParentFile());
normalized += Normalize.wallClock(compound);
try {
NBTJsonUtil.SaveFile(file, compound);
} catch (Exception e) {
throw new IllegalStateException("Failed writing " + file, e);
}
}
/** How many wall-clock values were pinned in this world. See {@link Normalize}. */
public int normalizedCount() {
return normalized;
}
/**
* Writes CustomNPC+'s own JSON rendering of a binary document beside the world, for reading.
*
* <p>Not a fixture and not parseable as strict JSON -- NBTJsonUtil suffixes scalars with their
* type ({@code 5b}, {@code 5L}, {@code 1.0f}), which is exactly what makes it worth having:
* the widths are visible, and a fixture whose value silently became a byte shows up here.
*/
private void renderReadable(String fileName, NBTTagCompound compound) {
File file = new File(readable, fileName + ".txt");
mkdirs(file.getParentFile());
try {
Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
try {
out.write(NBTJsonUtil.Convert(compound));
} finally {
out.close();
}
} catch (IOException e) {
throw new IllegalStateException("Failed writing " + file, e);
}
}
private String rel(File file) {
String base = root.getAbsolutePath();
String path = file.getAbsolutePath();
return path.startsWith(base) ? path.substring(base.length() + 1).replace('\\', '/') : path;
}
private static void mkdirs(File dir) {
if (dir != null && !dir.exists() && !dir.mkdirs()) {
throw new IllegalStateException("Could not create " + dir);
}
}
}
@@ -1,484 +0,0 @@
package kamkeel.npcs.fixtures.content;
import kamkeel.npcs.fixtures.Case;
import kamkeel.npcs.fixtures.Fixtures;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.constants.EnumAvailabilityDialog;
import noppes.npcs.constants.EnumAvailabilityFaction;
import noppes.npcs.constants.EnumAvailabilityFactionType;
import noppes.npcs.constants.EnumAvailabilityQuest;
import noppes.npcs.constants.EnumDayTime;
import noppes.npcs.constants.EnumOptionType;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.DialogImage;
import noppes.npcs.controllers.data.DialogOption;
import java.util.ArrayList;
import java.util.List;
/**
* Dialogs, built by axis rather than by example.
*
* <p>A dialog has about forty fields across six sub-objects, and picking a few realistic-looking
* ones covers the fields the author happened to think of. So each block below walks one axis to
* its ends -- every enum constant, every slot, both sides of every boolean -- and the id ranges
* are reserved per axis so a new case does not renumber the others.
*
* <p>Ranges: 1-9 basics, 10-29 options, 30-59 availability, 60-79 appearance, 80-89 images,
* 90-99 mail / quest link / faction rewards.
*/
public final class DialogFixtures {
private DialogFixtures() {
}
public static List<Case<Dialog>> maximal() {
List<Case<Dialog>> out = new ArrayList<Case<Dialog>>();
basics(out);
options(out);
availability(out);
appearance(out);
images(out);
attachments(out);
return out;
}
// ------------------------------------------------------------------ basics
private static void basics(List<Case<Dialog>> out) {
Dialog bare = dialog(1, "Bare", "");
out.add(new Case<Dialog>("Basics", bare,
"every field left at its constructor default, with an empty text. The baseline a "
+ "reader's defaults are compared against"));
Dialog plain = dialog(2, "Plain Greeting",
"Hello {player},\n\nWelcome to our village. I hope you enjoy your stay");
out.add(new Case<Dialog>("Basics", plain,
"title and text only, with the {player} placeholder and embedded newlines that "
+ "CustomNPC+'s own default dialog uses"));
Dialog longText = dialog(3, "Long Text", repeat(
"This sentence exists so the stored text crosses the length CustomNPC+ warns about. ", 200));
out.add(new Case<Dialog>("Basics", longText,
"text over 15000 chars, which DialogController logs as an 'Extremely big dialog'. "
+ "Loads normally -- the check is a warning, not a limit"));
Dialog unicode = dialog(4, Text.KATAKANA_FACTION + " " + Text.EM_DASH + " " + Text.ELEVES,
Text.CYRILLIC_QUEST + "\n" + Text.RTL + "\n" + Text.ASTRAL);
out.add(new Case<Dialog>("Basics", unicode,
"title and text outside Latin-1, including one astral-plane code point. NBT strings "
+ "are modified UTF-8, so the astral char is stored as a surrogate pair"));
Dialog formatted = dialog(5, Text.SECTION + "6Formatted " + Text.SECTION + "lTitle",
Text.SECTION + "cRed " + Text.SECTION + "aGreen " + Text.SECTION + "r" + "plain");
out.add(new Case<Dialog>("Basics", formatted,
"section-sign colour codes in title and text, which is how all CustomNPC+ content is "
+ "coloured"));
Dialog command = dialog(6, "Runs A Command", "The gate opens.");
command.command = "/say {player} opened the gate";
out.add(new Case<Dialog>("Basics", command,
"DialogCommand set -- a command run on the server when the dialog opens"));
Dialog sounds = dialog(7, "Sounds", "Listen.");
sounds.sound = "customnpcs:dialog.open";
sounds.textSound = "minecraft:random.orb";
sounds.textPitch = 0.75F;
out.add(new Case<Dialog>("Basics", sounds,
"DialogSound plus a non-default TextSound and TextPitch. Note DialogSound is written "
+ "only when non-empty, so the key is absent on every other dialog here"));
}
// ------------------------------------------------------------------ options
private static void options(List<Case<Dialog>> out) {
// One dialog per option type, because the type drives what the other fields mean.
int id = 10;
for (EnumOptionType type : EnumOptionType.values()) {
Dialog d = dialog(id, "Option " + type.name(), "Choose.");
DialogOption option = new DialogOption();
option.title = type.name() + " option";
option.optionType = type;
option.dialogId = type == EnumOptionType.DialogOption ? 2 : -1;
option.optionColor = 0x00FF00;
option.command = type == EnumOptionType.CommandBlock ? "/time set day" : "";
d.options.put(0, option);
out.add(new Case<Dialog>("Options", d,
"a single option of type " + type.name() + " (ordinal " + type.ordinal() + ")"));
id++;
}
Dialog full = dialog(20, "Six Options", "Pick one.");
for (int slot = 0; slot < 6; slot++) {
DialogOption option = new DialogOption();
option.title = "Option in slot " + slot;
option.optionType = EnumOptionType.DialogOption;
option.dialogId = 2;
option.optionColor = 0x100000 * (slot + 1);
full.options.put(slot, option);
}
out.add(new Case<Dialog>("Options", full,
"six options in contiguous slots 0-5, each a different colour"));
// Slots are a map key, not a list index. A reader that treats Options as an ordered list
// silently renumbers this one.
Dialog sparse = dialog(21, "Sparse Slots", "The gaps matter.");
int[] slots = {0, 3, 7, 12};
for (int slot : slots) {
DialogOption option = new DialogOption();
option.title = "Slot " + slot;
option.optionType = EnumOptionType.DialogOption;
option.dialogId = 2;
sparse.options.put(slot, option);
}
out.add(new Case<Dialog>("Options", sparse,
"options at non-contiguous slots 0, 3, 7 and 12. OptionSlot is stored per entry, so "
+ "the gaps survive; a reader treating the list as positional loses them"));
Dialog dangling = dialog(22, "Dangling Option", "Where does this go?");
DialogOption toNowhere = new DialogOption();
toNowhere.title = "To a dialog that is not here";
toNowhere.optionType = EnumOptionType.DialogOption;
toNowhere.dialogId = 999999;
dangling.options.put(0, toNowhere);
out.add(new Case<Dialog>("Options", dangling,
"an option pointing at a dialog id that does not exist in this world. Conversion must "
+ "keep the id rather than resolve it"));
Dialog emptyTitle = dialog(23, "Empty Option Title", "...");
DialogOption blank = new DialogOption();
blank.title = "";
blank.optionType = EnumOptionType.DialogOption;
blank.dialogId = 2;
blank.optionColor = 0;
emptyTitle.options.put(0, blank);
out.add(new Case<Dialog>("Options", emptyTitle,
"an option with an empty title and DialogColor 0. On read, colour 0 is replaced by the "
+ "default 0xe0e0e0 -- so this file does not round-trip, by design upstream"));
}
// ------------------------------------------------------------------ availability
private static void availability(List<Case<Dialog>> out) {
// Every EnumAvailabilityQuest constant, one dialog each. These are the rules whose loss
// makes a gated dialog visible to everybody, so each constant gets its own file.
int id = 30;
for (EnumAvailabilityQuest rule : EnumAvailabilityQuest.values()) {
Dialog d = dialog(id, "Quest rule " + rule.name(), "Gated on a quest.");
d.availability.questAvailable = rule;
d.availability.questId = 1;
out.add(new Case<Dialog>("Availability", d,
"AvailabilityQuest = " + rule.name() + " (ordinal " + rule.ordinal()
+ ") against quest 1"));
id++;
}
// All four quest slots at once, each a different rule and a different target.
Dialog fourQuests = dialog(40, "Four Quest Rules", "Four gates.");
fourQuests.availability.questAvailable = EnumAvailabilityQuest.After;
fourQuests.availability.questId = 1;
fourQuests.availability.quest2Available = EnumAvailabilityQuest.Before;
fourQuests.availability.quest2Id = 2;
fourQuests.availability.quest3Available = EnumAvailabilityQuest.Active;
fourQuests.availability.quest3Id = 3;
fourQuests.availability.quest4Available = EnumAvailabilityQuest.NotAcceptable;
fourQuests.availability.quest4Id = 4;
out.add(new Case<Dialog>("Availability", fourQuests,
"all four AvailabilityQuest slots set to different rules and different quests. The "
+ "case a reader that reads only the first slot passes anyway"));
int dialogRuleId = 41;
for (EnumAvailabilityDialog rule : EnumAvailabilityDialog.values()) {
Dialog d = dialog(dialogRuleId, "Dialog rule " + rule.name(), "Gated on a dialog.");
d.availability.dialogAvailable = rule;
d.availability.dialogId = 2;
out.add(new Case<Dialog>("Availability", d,
"AvailabilityDialog = " + rule.name() + " against dialog 2 -- read tracking"));
dialogRuleId++;
}
Dialog fourDialogs = dialog(44, "Four Dialog Rules", "Four read-gates.");
fourDialogs.availability.dialogAvailable = EnumAvailabilityDialog.After;
fourDialogs.availability.dialogId = 1;
fourDialogs.availability.dialog2Available = EnumAvailabilityDialog.Before;
fourDialogs.availability.dialog2Id = 2;
fourDialogs.availability.dialog3Available = EnumAvailabilityDialog.After;
fourDialogs.availability.dialog3Id = 3;
fourDialogs.availability.dialog4Available = EnumAvailabilityDialog.Before;
fourDialogs.availability.dialog4Id = 4;
out.add(new Case<Dialog>("Availability", fourDialogs,
"all four AvailabilityDialog slots set"));
// Faction rules: type x stance, both slots.
int factionRuleId = 45;
for (EnumAvailabilityFactionType type : EnumAvailabilityFactionType.values()) {
for (EnumAvailabilityFaction stance : EnumAvailabilityFaction.values()) {
if (type == EnumAvailabilityFactionType.Always && stance != EnumAvailabilityFaction.Friendly) {
continue; // Always ignores the stance; one file is enough for it.
}
Dialog d = dialog(factionRuleId, "Faction " + type.name() + " " + stance.name(),
"Gated on standing.");
d.availability.factionAvailable = type;
d.availability.factionStance = stance;
d.availability.factionId = 10;
out.add(new Case<Dialog>("Availability", d,
"AvailabilityFaction = " + type.name() + ", stance " + stance.name()
+ ", against faction 10 (Hidden Watchers)"));
factionRuleId++;
}
}
Dialog bothFactions = dialog(53, "Both Faction Slots", "Two standings.");
bothFactions.availability.factionAvailable = EnumAvailabilityFactionType.Is;
bothFactions.availability.factionStance = EnumAvailabilityFaction.Friendly;
bothFactions.availability.factionId = 0;
bothFactions.availability.faction2Available = EnumAvailabilityFactionType.IsNot;
bothFactions.availability.faction2Stance = EnumAvailabilityFaction.Hostile;
bothFactions.availability.faction2Id = 2;
out.add(new Case<Dialog>("Availability", bothFactions,
"both faction slots, one Is/Friendly and one IsNot/Hostile"));
int daytimeId = 54;
for (EnumDayTime time : EnumDayTime.values()) {
Dialog d = dialog(daytimeId, "Daytime " + time.name(), "Time-gated.");
d.availability.daytime = time;
out.add(new Case<Dialog>("Availability", d,
"AvailabilityDayTime = " + time.name() + " (ordinal " + time.ordinal() + ")"));
daytimeId++;
}
Dialog level = dialog(57, "Min Level", "You look experienced.");
level.availability.minPlayerLevel = 30;
out.add(new Case<Dialog>("Availability", level,
"AvailabilityMinPlayerLevel = 30"));
Dialog everything = dialog(58, "Every Rule At Once", "Nothing gets through this.");
everything.availability.daytime = EnumDayTime.Night;
everything.availability.minPlayerLevel = 99;
everything.availability.dialogAvailable = EnumAvailabilityDialog.After;
everything.availability.dialogId = 1;
everything.availability.dialog2Available = EnumAvailabilityDialog.Before;
everything.availability.dialog2Id = 2;
everything.availability.dialog3Available = EnumAvailabilityDialog.After;
everything.availability.dialog3Id = 3;
everything.availability.dialog4Available = EnumAvailabilityDialog.Before;
everything.availability.dialog4Id = 4;
everything.availability.questAvailable = EnumAvailabilityQuest.After;
everything.availability.questId = 1;
everything.availability.quest2Available = EnumAvailabilityQuest.Active;
everything.availability.quest2Id = 2;
everything.availability.quest3Available = EnumAvailabilityQuest.NotActive;
everything.availability.quest3Id = 3;
everything.availability.quest4Available = EnumAvailabilityQuest.Acceptable;
everything.availability.quest4Id = 4;
everything.availability.factionAvailable = EnumAvailabilityFactionType.Is;
everything.availability.factionStance = EnumAvailabilityFaction.Friendly;
everything.availability.factionId = 0;
everything.availability.faction2Available = EnumAvailabilityFactionType.IsNot;
everything.availability.faction2Stance = EnumAvailabilityFaction.Hostile;
everything.availability.faction2Id = 2;
out.add(new Case<Dialog>("Availability", everything,
"every availability slot set simultaneously -- ten rules plus daytime and level. The "
+ "single densest availability block in these fixtures"));
}
// ------------------------------------------------------------------ appearance
private static void appearance(List<Case<Dialog>> out) {
Dialog flags = dialog(60, "Flags Inverted", "Every boolean off its default.");
flags.hideNPC = true;
flags.showWheel = true;
flags.disableEsc = true;
flags.darkenScreen = false;
flags.showOptionLine = false;
flags.renderGradual = true;
flags.showPreviousBlocks = false;
out.add(new Case<Dialog>("Appearance", flags,
"all seven display booleans flipped away from their defaults. Four of them read back "
+ "as true when their key is absent, so a writer that omits defaults changes "
+ "behaviour"));
Dialog colors = dialog(61, "Colors", "Coloured.");
colors.color = 0x336699;
colors.titleColor = 0xCC3300;
out.add(new Case<Dialog>("Appearance", colors,
"Color and TitleColor off the 0xe0e0e0 default"));
Dialog colorData = dialog(62, "Color Data Enabled", "Full chrome colours.");
colorData.colorData.setEnableColorSettings(true);
colorData.colorData.setLineColor1(0xff112233);
colorData.colorData.setLineColor2(0xff445566);
colorData.colorData.setLineColor3(0xff778899);
colorData.colorData.setSlotColor(0xffaabbcc);
colorData.colorData.setButtonAcceptColor(0xff00ff00);
colorData.colorData.setButtonRejectColor(0xffff0000);
out.add(new Case<Dialog>("Appearance", colorData,
"DialogColorData with ColorSettings enabled and all six colours set. The six keys are "
+ "written ONLY when the flag is on -- see id 63 for the other half"));
Dialog colorDataOff = dialog(63, "Color Data Disabled", "Colours set but not enabled.");
colorDataOff.colorData.setEnableColorSettings(false);
colorDataOff.colorData.setLineColor1(0xff112233);
colorDataOff.colorData.setSlotColor(0xffaabbcc);
out.add(new Case<Dialog>("Appearance", colorDataOff,
"ColorSettings off with colours assigned. Proves the six colour keys are absent from "
+ "the file, so the values are lost upstream and there is nothing to convert"));
Dialog layout = dialog(64, "Layout", "Positioned.");
layout.textWidth = 420;
layout.textHeight = 260;
layout.textOffsetX = -12;
layout.textOffsetY = 34;
layout.titlePos = 2;
layout.titleOffsetX = 8;
layout.titleOffsetY = -6;
layout.optionOffsetX = 5;
layout.optionOffsetY = -5;
layout.optionSpaceX = 3;
layout.optionSpaceY = 14;
layout.npcScale = 2.25F;
layout.npcOffsetX = -40;
layout.npcOffsetY = 18;
out.add(new Case<Dialog>("Appearance", layout,
"every geometry field set, several negative. Fourteen integers and one float that a "
+ "dialog screen has to place things by"));
for (byte alignment = 0; alignment <= 2; alignment++) {
Dialog d = dialog(65 + alignment, "Alignment " + alignment, "Aligned.");
d.alignment = alignment;
out.add(new Case<Dialog>("Appearance", d,
"DialogAlignment = " + alignment + " (0 bottom, 1 top, 2 centre). Stored as a byte, "
+ "not an int -- the one narrow scalar on a dialog"));
}
}
// ------------------------------------------------------------------ images
private static void images(List<Case<Dialog>> out) {
Dialog one = dialog(80, "One Image", "Look.");
one.dialogImages.put(0, image(0, "customnpcs:textures/gui/dialog.png", 1));
out.add(new Case<Dialog>("Images", one,
"a single DialogImage with every field at a non-default"));
Dialog many = dialog(81, "Three Images", "Look again.");
for (int i = 0; i < 3; i++) {
DialogImage img = image(i, "customnpcs:textures/gui/image" + i + ".png", i);
img.x = 10 * i;
img.y = 20 * i;
img.alignment = i;
many.dialogImages.put(i, img);
}
out.add(new Case<Dialog>("Images", many,
"three images with imageType 0, 1 and 2 -- Default, Text and Option"));
Dialog defaults = dialog(82, "Default Image", "An untouched image.");
defaults.dialogImages.put(0, new DialogImage(0));
out.add(new Case<Dialog>("Images", defaults,
"a DialogImage left entirely at its constructor defaults, including an empty texture"));
}
// ------------------------------------------------------------------ attachments
private static void attachments(List<Case<Dialog>> out) {
Dialog quest = dialog(90, "Starts A Quest", "Take this.");
quest.quest = 1;
out.add(new Case<Dialog>("Attachments", quest,
"DialogQuest = 1 -- opening this dialog starts quest 1. The link a conversion that "
+ "drops the field turns into a quest nobody can be given"));
Dialog mail = dialog(91, "Sends Mail", "Check your inbox.");
mail.mail.subject = "A letter from the village";
mail.mail.sender = "Elder Marrow";
mail.mail.time = Fixtures.EPOCH;
mail.mail.beenRead = false;
NBTTagCompound message = new NBTTagCompound();
message.setString("Text", "Thank you for your help.");
mail.mail.message = message;
mail.mail.items[0] = Fixtures.item("minecraft:golden_apple", 3, 1);
mail.mail.items[2] = Fixtures.namedItem("minecraft:diamond_sword", 1, 12, "Villager's Thanks");
out.add(new Case<Dialog>("Attachments", mail,
"DialogMail with subject, sender, a message compound and two of four item slots -- "
+ "one of them a variant damage, one carrying custom NBT. NOTE: TimePast inside "
+ "this compound is not reproducible between runs"));
Dialog reward = dialog(92, "Faction Reward", "The Legion remembers.");
reward.factionOptions.factionId = 14;
reward.factionOptions.factionPoints = 250;
reward.factionOptions.decreaseFactionPoints = false;
reward.factionOptions.faction2Id = 15;
reward.factionOptions.faction2Points = 100;
reward.factionOptions.decreaseFaction2Points = true;
out.add(new Case<Dialog>("Attachments", reward,
"both faction reward slots -- one granting points, one decreasing them"));
Dialog everything = dialog(93, "Everything At Once",
"This dialog exercises every sub-object CustomNPC+ hangs off a dialog.");
everything.quest = 2;
everything.command = "/say done";
everything.sound = "customnpcs:dialog.open";
everything.color = 0x445566;
everything.titleColor = 0x998877;
everything.hideNPC = true;
everything.renderGradual = true;
everything.npcScale = 1.5F;
everything.availability.daytime = EnumDayTime.Day;
everything.availability.minPlayerLevel = 5;
everything.availability.questAvailable = EnumAvailabilityQuest.Before;
everything.availability.questId = 3;
everything.factionOptions.factionId = 0;
everything.factionOptions.factionPoints = 10;
everything.colorData.setEnableColorSettings(true);
everything.colorData.setSlotColor(0xff00ffff);
everything.mail.subject = "Everything";
everything.mail.sender = "The Generator";
everything.mail.time = Fixtures.EPOCH;
everything.mail.items[0] = Fixtures.item("minecraft:emerald", 64);
everything.dialogImages.put(0, image(0, "customnpcs:textures/gui/all.png", 2));
DialogOption opt = new DialogOption();
opt.title = "Continue";
opt.optionType = EnumOptionType.DialogOption;
opt.dialogId = 2;
opt.optionColor = 0xFFAA00;
everything.options.put(0, opt);
out.add(new Case<Dialog>("Attachments", everything,
"one dialog touching every sub-object at once: options, availability, faction rewards, "
+ "colour data, mail, an image and a quest link"));
}
// ------------------------------------------------------------------ helpers
private static Dialog dialog(int id, String title, String text) {
Dialog dialog = new Dialog();
dialog.id = id;
dialog.title = title;
dialog.text = text;
return dialog;
}
private static DialogImage image(int id, String texture, int imageType) {
DialogImage image = new DialogImage(id);
image.texture = texture;
image.x = 12;
image.y = 34;
image.width = 64;
image.height = 48;
image.textureX = 8;
image.textureY = 16;
image.scale = 1.75F;
image.color = 0x88CCFF;
image.selectedColor = 0xFFCC88;
image.alpha = 0.5F;
image.rotation = 45.0F;
image.imageType = imageType;
image.alignment = 1;
return image;
}
static String repeat(String s, int times) {
StringBuilder sb = new StringBuilder(s.length() * times);
for (int i = 0; i < times; i++) {
sb.append(s);
}
return sb.toString();
}
}
@@ -1,187 +0,0 @@
package kamkeel.npcs.fixtures.content;
import kamkeel.npcs.fixtures.Case;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.ScriptContainer;
import noppes.npcs.controllers.data.CustomEffect;
import noppes.npcs.controllers.data.EffectScript;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* Custom effects, which persist in two places at once.
*
* <p>Each effect is a file at {@code customeffects/<Name>.json} -- or
* {@code customeffects/<Category>/<Name>.json}, where the subdirectory is the category -- written
* with {@code writeToNBT(true)}. <b>The filename is the name</b>: {@code loadEffectsFromDir}
* overwrites whatever {@code name} the file contained with the filename minus {@code .json}, so
* the {@code name} key inside is dead weight and the two can legitimately disagree. There is a
* fixture for that below.
*
* <p>Alongside them, {@code customeffects.dat} is an index of {@code {Name, ID}} pairs plus
* {@code lastID} -- not the effects themselves. An effect whose name is empty is left out of the
* index entirely, which is its own case.
*/
public final class EffectFixtures {
private EffectFixtures() {
}
public static List<Case<CustomEffect>> maximal() {
List<Case<CustomEffect>> out = new ArrayList<Case<CustomEffect>>();
CustomEffect bare = effect(1, "Bare");
out.add(new Case<CustomEffect>("", bare,
"every field at its constructor default. Note menuName defaults to a coloured "
+ "'NEW EFFECT' containing a section sign, so even the bare case is not ASCII"));
CustomEffect full = effect(2, "Fully Configured");
full.menuName = Text.SECTION + "bFully " + Text.SECTION + "6Configured";
full.length = 1200;
full.everyXTick = 10;
full.lossOnDeath = false;
full.icon = "customnpcs:textures/gui/effects.png";
full.iconX = 32;
full.iconY = 48;
full.width = 24;
full.height = 24;
out.add(new Case<CustomEffect>("", full,
"every scalar off its default: a 60-second duration, a 10-tick period, an icon with "
+ "its atlas offsets and size, and lossOnDeath cleared"));
CustomEffect animated = effect(3, "Animated Icon");
animated.animated = true;
animated.frameCount = 8;
animated.frametime = 3;
animated.icon = "customnpcs:textures/gui/anim.png";
out.add(new Case<CustomEffect>("", animated,
"an animated icon -- iconAnimated, iconFrameCount and iconFrameTime. Both counts are "
+ "clamped to a minimum of 1 on read, so zero cannot round-trip"));
CustomEffect tagged = effect(4, "Tagged");
tagged.tagUUIDs.addAll(Arrays.asList(
UUID.fromString("0e5f2b6a-1c3d-4e5f-8a9b-0c1d2e3f4a5b"),
UUID.fromString("1a2b3c4d-5e6f-4071-8293-a4b5c6d7e8f9"),
UUID.fromString("ffffffff-ffff-4fff-bfff-ffffffffffff")));
out.add(new Case<CustomEffect>("", tagged,
"three tag UUIDs. TagController.writeTagUUIDs omits the key entirely when the set is "
+ "empty, so every other effect here has no TagUUIDs key at all"));
CustomEffect scripted = effect(5, "Scripted");
scripted.setScriptHandler(script(
"function onEffectAdd(event) { event.player.message('effect added'); }\n"
+ "function onEffectTick(event) {}\n"
+ "function onEffectRemove(event) {}\n", true, "ECMAScript"));
out.add(new Case<CustomEffect>("", scripted,
"a ScriptData compound carrying ScriptLanguage, ScriptEnabled and a ScriptContent "
+ "unit with three hook functions"));
CustomEffect scriptDisabled = effect(6, "Script Disabled");
scriptDisabled.setScriptHandler(script("function onEffectTick(event) {}", false, "javascript"));
out.add(new Case<CustomEffect>("", scriptDisabled,
"ScriptEnabled false, and a language string that is not the canonical 'ECMAScript' -- "
+ "normalizeLanguage runs on read, not on write"));
CustomEffect hugeScript = effect(7, "Huge Script");
StringBuilder sb = new StringBuilder();
while (sb.length() < 70000) {
sb.append("// a line of script that exists only to push past the 65535 char limit\n");
}
hugeScript.setScriptHandler(script(sb.toString(), true, "ECMAScript"));
out.add(new Case<CustomEffect>("", hugeScript,
"a script over 65535 characters. NBT strings cannot hold that, so ScriptContainer "
+ "splits it across Script plus ExpandedScript0..N, bounded by "
+ "ConfigScript.ExpandedScriptLimit which defaults to 2. Check the written file "
+ "to see how many parts survived -- this fixture exists to record that"));
CustomEffect noName = effect(8, "");
out.add(new Case<CustomEffect>("", noName,
"an EMPTY name. writeMapNBT skips these, so this effect is absent from "
+ "customeffects.dat while its file exists on disk -- and since the filename is "
+ "the name, its file is '.json'. Recorded rather than avoided"));
CustomEffect categorised = effect(10, "In A Category");
out.add(new Case<CustomEffect>("Buffs", categorised,
"an effect inside a category subdirectory. Categories are directories and nothing "
+ "else -- there is no category file and no id stored anywhere"));
CustomEffect unicode = effect(11, "Unicode");
unicode.menuName = Text.KATAKANA_FACTION + " " + Text.EM_DASH + " " + Text.ELEVES;
out.add(new Case<CustomEffect>("Buffs", unicode,
"a non-Latin menu name inside a category"));
CustomEffect extremes = effect(12, "Extremes");
extremes.length = Integer.MAX_VALUE;
extremes.everyXTick = Integer.MAX_VALUE;
extremes.iconX = Integer.MIN_VALUE;
extremes.iconY = Integer.MIN_VALUE;
extremes.width = 0;
extremes.height = 0;
extremes.frameCount = 0;
extremes.frametime = 0;
out.add(new Case<CustomEffect>("", extremes,
"integer boundaries, plus zero width, height, frame count and frame time. Width and "
+ "height fall back to 16 on read only when their key is ABSENT, so an explicit "
+ "zero survives where a missing key does not"));
return out;
}
/**
* The filename for {@link #nameMismatch()}, deliberately unequal to the effect's name field.
*/
public static final String MISMATCH_FILENAME = "Name On Disk";
/**
* An effect whose {@code name} key disagrees with its filename.
*
* <p>Kept out of {@link #maximal()} because it cannot be expressed there: everything in that
* list is written to a file named after the effect, which is what makes a mismatch impossible
* to state. loadEffectsFromDir assigns {@code effect.name} from the filename after reading, so
* the key inside is discarded and a reader that trusts it gets a different answer.
*/
public static CustomEffect nameMismatch() {
CustomEffect mismatched = effect(9, "Name Inside The File");
return mismatched;
}
/** The index document. Copied from CustomEffectController.writeMapNBT. */
public static NBTTagCompound index(List<Case<CustomEffect>> effects, int lastUsedId) {
NBTTagList list = new NBTTagList();
for (Case<CustomEffect> c : effects) {
CustomEffect effect = c.value;
// writeMapNBT skips unnamed effects. Reproduced, because the omission is the contract.
if (!effect.getName().isEmpty()) {
NBTTagCompound entry = new NBTTagCompound();
entry.setString("Name", effect.getName());
entry.setInteger("ID", effect.id);
list.appendTag(entry);
}
}
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("CustomEffects", list);
compound.setInteger("lastID", lastUsedId);
return compound;
}
private static CustomEffect effect(int id, String name) {
CustomEffect effect = new CustomEffect();
effect.id = id;
effect.name = name;
return effect;
}
private static EffectScript script(String source, boolean enabled, String language) {
EffectScript handler = new EffectScript();
handler.setLanguage(language);
handler.setEnabled(enabled);
ScriptContainer container = new ScriptContainer(handler);
container.script = source;
handler.addScriptUnit(container);
return handler;
}
}
@@ -1,153 +0,0 @@
package kamkeel.npcs.fixtures.content;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.data.Faction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Factions, and the {@code factions.dat} document that holds them.
*
* <p>Layout copied from FactionController.getNBT: {@code lastID} plus an {@code NPCFactions} list
* of {@link Faction#writeNBT} compounds. The controller iterates a HashMap; this iterates a list,
* so the order is stable between runs. Order is not part of the format -- the loader keys each
* entry on its own {@code Slot} -- but an unstable order would make every regeneration a diff.
*/
public final class FactionFixtures {
private FactionFixtures() {
}
/** The three CustomNPC+ creates for a new world, when factions.dat is absent or empty. */
public static List<Faction> vanillaDefaults() {
return new ArrayList<Faction>(Arrays.asList(
new Faction(0, "Friendly", 0x00DD00, 2000),
new Faction(1, "Neutral", 0xF2DD00, 1000),
new Faction(2, "Aggressive", 0xDD0000, 0)));
}
/**
* Every flag and threshold moved off its default, and the mutual-hostility graph populated.
*
* <p>The three booleans are the interesting part for a port: {@code hideFaction} suppresses the
* standing message, {@code getsAttacked} lets vanilla mobs target members, {@code isPassive}
* stops members retaliating. They are independent, so they get an entry each rather than one
* faction with all three set.
*/
public static List<Faction> maximal() {
List<Faction> factions = vanillaDefaults();
Faction hidden = faction(10, "Hidden Watchers", 0x2B2B2B, 900);
hidden.hideFaction = true;
hidden.neutralPoints = 250;
hidden.friendlyPoints = 2750;
factions.add(hidden);
Faction attacked = faction(11, "Hunted", 0xAA5500, 1200);
attacked.getsAttacked = true;
factions.add(attacked);
Faction passive = faction(12, "Pacifists", 0x55FFFF, 1800);
passive.isPassive = true;
factions.add(passive);
Faction all = faction(13, "Every Flag", 0xFF00FF, 0);
all.hideFaction = true;
all.getsAttacked = true;
all.isPassive = true;
all.neutralPoints = 0;
all.friendlyPoints = 0;
factions.add(all);
// A hostility graph rather than a single edge: the reader has to keep a set per faction,
// and a reader that keeps one integer looks correct until the second entry.
Faction warring = faction(14, "Iron Legion", 0xB0B0B0, 400);
warring.attackFactions.addAll(Arrays.asList(2, 10, 11, 12));
factions.add(warring);
Faction rival = faction(15, "Ash Covenant", 0x7A0000, 600);
rival.attackFactions.addAll(Arrays.asList(14, 0));
factions.add(rival);
// Thresholds inverted -- friendly below neutral. CustomNPC+ does not validate this, and
// Availability and Faction read the boundary differently, so it is worth having on disk.
Faction inverted = faction(16, "Inverted Bands", 0x123456, 1000);
inverted.neutralPoints = 1800;
inverted.friendlyPoints = 200;
factions.add(inverted);
Faction negative = faction(17, "Debtors", 0x000080, -500);
negative.neutralPoints = -1000;
negative.friendlyPoints = -100;
factions.add(negative);
return factions;
}
/** Names and values that are legal, unusual, and have broken a reader somewhere. */
public static List<Faction> edge() {
List<Faction> factions = new ArrayList<Faction>();
factions.add(faction(0, "", 0, 0));
// Built from code points rather than written as literals. This source stays pure ASCII on
// purpose: a generator whose own file gets mojibaked by a CP-1252 toolchain would emit
// fixtures that assert the mojibake, and every reader downstream would agree with it.
Faction unicode = faction(1, Text.KATAKANA_FACTION + " " + Text.EM_DASH + " " + Text.ELEVES,
0xFFFFFF, 1000);
factions.add(unicode);
Faction formatting = faction(2,
Text.SECTION + "cRed " + Text.SECTION + "lBold" + Text.SECTION + "r", 0xFF5555, 1000);
factions.add(formatting);
Faction longName = faction(3, repeat("Faction With A Very Long Name ", 12), 0x00FF00, 1000);
factions.add(longName);
Faction extremes = faction(4, "Integer Extremes", 0xFFFFFF, Integer.MAX_VALUE);
extremes.neutralPoints = Integer.MIN_VALUE;
extremes.friendlyPoints = Integer.MAX_VALUE;
extremes.color = -1;
factions.add(extremes);
// Points to factions that are not in this file. A converter that resolves eagerly breaks
// here; one that keeps the id does not.
Faction dangling = faction(5, "Dangling References", 0x808080, 1000);
dangling.attackFactions.addAll(Arrays.asList(9001, -3, 0));
factions.add(dangling);
// A non-contiguous, high id. Nothing requires ids to be dense, and lastID is separate.
factions.add(faction(4096, "Sparse Id", 0x00FFFF, 1000));
return factions;
}
/** The controller-shaped document. Copied from FactionController.getNBT. */
public static NBTTagCompound document(List<Faction> factions, int lastUsedId) {
NBTTagList list = new NBTTagList();
for (Faction faction : factions) {
NBTTagCompound tag = new NBTTagCompound();
faction.writeNBT(tag);
list.appendTag(tag);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("lastID", lastUsedId);
compound.setTag("NPCFactions", list);
return compound;
}
private static Faction faction(int id, String name, int color, int defaultPoints) {
return new Faction(id, name, color, defaultPoints);
}
private static String repeat(String s, int times) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++) {
sb.append(s);
}
return sb.toString();
}
}
@@ -1,180 +0,0 @@
package kamkeel.npcs.fixtures.content;
import kamkeel.npcs.fixtures.Case;
import kamkeel.npcs.fixtures.Fixtures;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.data.PlayerData;
import noppes.npcs.controllers.data.Quest;
import noppes.npcs.controllers.data.QuestData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Per-player records, and the name/uuid index beside them.
*
* <p>A record is {@code playerdata/<uuid>.json}, written by {@code PlayerData.getNBT}, which
* composes fifteen sub-writers -- dialog, bank, quest, transport, faction, item giver, mail,
* timers, skin overlays, animation, effect, magic, trade, ability and hotbar. Only some are
* populated here; the rest write their empty form, which is itself worth having, since "what an
* untouched sub-record looks like" is a contract too.
*
* <p>{@code playerdatamap.dat} is a flat {@code {Name, UUID}} list. It is a lookup index rebuilt
* by scanning the directory when absent, so it is derived rather than authoritative -- but it is
* what CustomNPC+ reads first.
*
* <p>The record can also be gzipped NBT rather than JSON, chosen by {@code ConfigMain.DatFormat}.
* Both forms are generated, because a reader that only handles the default will meet the other on
* somebody's server.
*/
public final class PlayerFixtures {
private PlayerFixtures() {
}
/** uuid -> display name, in a fixed order so the index document is reproducible. */
public static Map<String, String> roster() {
Map<String, String> roster = new LinkedHashMap<String, String>();
roster.put("29cc52dd-2c50-4e8f-a388-be6c497cf0b4", "Fresh");
roster.put("8667ba71-b85a-4004-af54-457a9734eed7", "Progressed");
roster.put("069a79f4-44e9-4726-a5be-fca90e38aaf5", "Notch");
roster.put("00000000-0000-0000-0000-000000000000", "NilUuid");
return roster;
}
public static List<Case<PlayerData>> records() {
List<Case<PlayerData>> out = new ArrayList<Case<PlayerData>>();
PlayerData fresh = player("29cc52dd-2c50-4e8f-a388-be6c497cf0b4", "Fresh");
out.add(new Case<PlayerData>("", fresh,
"a player who has done nothing. Every one of the fifteen sub-records writes its empty "
+ "form -- the baseline for what an untouched record contains"));
PlayerData progressed = player("8667ba71-b85a-4004-af54-457a9734eed7", "Progressed");
progressed.dialogData.dialogsRead.addAll(Arrays.asList(1, 2, 3, 41, 90));
progressed.factionData.factionData.put(0, 1800);
progressed.factionData.factionData.put(1, 1000);
progressed.factionData.factionData.put(2, 0);
progressed.factionData.factionData.put(14, -250);
progressed.questData.finishedQuests.put(1, Fixtures.EPOCH);
progressed.questData.finishedQuests.put(30, Fixtures.EPOCH + 86400000L);
progressed.questData.activeQuests.put(2, questData(2, false));
progressed.questData.activeQuests.put(71, questData(71, true));
progressed.companionID = 4;
progressed.profileSlot = 2;
out.add(new Case<PlayerData>("", progressed,
"read dialogs, standing in four factions including a negative one, two finished "
+ "quests with completion timestamps, and two active quests -- one of them marked "
+ "complete but not turned in. Also a companion id and a non-zero profile slot"));
PlayerData extras = player("069a79f4-44e9-4726-a5be-fca90e38aaf5", "Notch");
QuestData withExtras = questData(75, false);
withExtras.extraData.setTag("Killed", killed("Zombie", 14, "Skeleton", 3));
withExtras.extraData.setBoolean("LocationFound", true);
withExtras.extraData.setBoolean("Location2Found", true);
extras.questData.activeQuests.put(75, withExtras);
extras.dialogData.dialogsRead.add(58);
out.add(new Case<PlayerData>("", extras,
"an active quest whose ExtraData holds per-objective progress, in the shapes the "
+ "quest classes actually read. Kill counts are a Killed tag list of Slot/Value "
+ "compounds -- NBTTags.getStringIntegerMap -- not loose integers keyed by mob "
+ "name, and a reached location is a boolean under its own key. The quest stores "
+ "only the targets, so a reader that ignores ExtraData can never show progress"));
PlayerData party = player("11111111-2222-3333-4444-555555555555", "PartyMember");
QuestData shared = questData(76, false);
// The per-player half of a party kill quest: QuestKill keys it by the player's own name
// rather than by slot, so two members of one party each carry their own tally.
shared.extraData.setTag("PartyMemberKilled", killed("Creeper", 2));
shared.extraData.setTag("Killed", killed("Creeper", 5));
party.questData.activeQuests.put(76, shared);
out.add(new Case<PlayerData>("", party,
"a party kill quest, which stores the group total under Killed and each member's own "
+ "share under <playerName>Killed. The second key is composed from a name, so it "
+ "cannot be enumerated from the quest -- only from the party that took it"));
PlayerData foreign = player("22222222-3333-4444-5555-666666666666", "AddonUser");
QuestData unclaimed = questData(77, false);
// ExtraData is an opaque compound: nothing validates its keys, so an addon that stores
// its own progress there produces a file no objective kind here can read. Deliberate,
// and the case a reader has to report rather than silently drop.
unclaimed.extraData.setInteger("dbcaddon:KiCharged", 900);
unclaimed.extraData.setString("dbcaddon:Form", "SuperSaiyan");
foreign.questData.activeQuests.put(77, unclaimed);
out.add(new Case<PlayerData>("", foreign,
"an active quest whose ExtraData holds only keys no objective kind claims, which is "
+ "what an addon writing its own progress leaves behind. Nothing validates this "
+ "compound, so a reader meets it on a real server and has to say so rather than "
+ "drop it"));
PlayerData nil = player("00000000-0000-0000-0000-000000000000", "NilUuid");
nil.dialogData.dialogsRead.add(1);
out.add(new Case<PlayerData>("", nil,
"the nil UUID, which is legal in the file and names no player. A reader that treats "
+ "it as absent rather than as a value diverges here"));
return out;
}
/** PlayerDataController.writeNBT -- a flat Name/UUID list, with no lastID. */
public static NBTTagCompound index(Map<String, String> roster) {
NBTTagList list = new NBTTagList();
for (Map.Entry<String, String> entry : roster.entrySet()) {
NBTTagCompound player = new NBTTagCompound();
// The controller keys the map by NAME and stores the uuid as the value, which is the
// opposite of what the file's key order suggests at a glance.
player.setString("Name", entry.getValue());
player.setString("UUID", entry.getKey());
list.appendTag(player);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("PlayerDataMap", list);
return compound;
}
private static PlayerData player(String uuid, String name) {
PlayerData data = new PlayerData();
data.uuid = uuid;
data.playername = name;
return data;
}
/**
* An entry in a player's active quest list.
*
* <p>{@code QuestData} needs a {@link Quest} to construct, but only writes three keys and
* never touches it -- the quest id is the map key in the enclosing list, not part of the
* entry. So a bare Quest carrying the right id is enough and nothing is invented.
*/
/**
* A counter map in the shape {@code NBTTags.nbtStringIntegerMap} writes and
* {@code getStringIntegerMap} reads: a list of {@code {Slot, Value}} compounds.
*
* <p>Written out by hand rather than through {@code NBTTags} so the fixture states the shape
* it is asserting. A generator that borrows the reader's own helper agrees with it by
* construction and proves nothing about it.
*/
private static NBTTagList killed(Object... slotsAndCounts) {
NBTTagList list = new NBTTagList();
for (int at = 0; at < slotsAndCounts.length; at += 2) {
NBTTagCompound entry = new NBTTagCompound();
entry.setString("Slot", (String) slotsAndCounts[at]);
entry.setInteger("Value", ((Integer) slotsAndCounts[at + 1]).intValue());
list.appendTag(entry);
}
return list;
}
private static QuestData questData(int questId, boolean completed) {
Quest quest = new Quest();
quest.id = questId;
QuestData data = new QuestData(quest);
data.isCompleted = completed;
data.sendAlerts = true;
return data;
}
}
@@ -1,445 +0,0 @@
package kamkeel.npcs.fixtures.content;
import kamkeel.npcs.fixtures.Case;
import kamkeel.npcs.fixtures.Fixtures;
import net.minecraft.nbt.NBTTagCompound;
import noppes.npcs.constants.EnumPartyExchange;
import noppes.npcs.constants.EnumPartyObjectives;
import noppes.npcs.constants.EnumPartyRequirements;
import noppes.npcs.constants.EnumProfileSync;
import noppes.npcs.constants.EnumQuestCompletion;
import noppes.npcs.constants.EnumQuestRepeat;
import noppes.npcs.constants.EnumQuestType;
import noppes.npcs.controllers.data.Quest;
import noppes.npcs.quests.QuestDialog;
import noppes.npcs.quests.QuestItem;
import noppes.npcs.quests.QuestKill;
import noppes.npcs.quests.QuestLocation;
import noppes.npcs.quests.QuestManual;
import java.util.ArrayList;
import java.util.List;
/**
* Quests, one axis at a time.
*
* <p><b>A quest has no availability.</b> Worth stating because it is easy to conclude otherwise:
* {@code Quest.readNBTPartial} calls {@code VersionCompatibility.CheckAvailabilityCompatibility},
* whose name says availability, and which is in fact a generic "fill in keys this file predates"
* pass applied to every {@code ICompatibilty}. {@code Quest} declares no {@code Availability}
* field, {@code writeToNBTPartial} writes no {@code Availability*} key, and neither does the 1.20
* line. Gating is a property of the dialog that offers the quest.
*
* <p>Ranges: 1-9 the six types, 10-29 repeat and completion, 30-49 rewards, 50-69 party and
* profile, 70-89 objectives in depth, 90-99 combinations.
*/
public final class QuestFixtures {
private QuestFixtures() {
}
public static List<Case<Quest>> maximal() {
List<Case<Quest>> out = new ArrayList<Case<Quest>>();
types(out);
repeatAndCompletion(out);
rewards(out);
partyAndProfile(out);
objectives(out);
combinations(out);
return out;
}
// ------------------------------------------------------------------ types
private static void types(List<Case<Quest>> out) {
int id = 1;
for (EnumQuestType type : EnumQuestType.values()) {
Quest quest = quest(id, "Type " + type.name(), type);
populateObjective(quest, type);
out.add(new Case<Quest>("Types", quest,
"quest type " + type.name() + " (ordinal " + type.ordinal() + ") with its "
+ "objective populated. NOTE: Kill and AreaKill both build a QuestKill and "
+ "write the same keys -- the only thing separating them on disk is Type"));
id++;
}
}
/** Kill and AreaKill differ by Type alone, so they get compared directly. */
private static void populateObjective(Quest quest, EnumQuestType type) {
if (type == EnumQuestType.Item) {
QuestItem items = (QuestItem) quest.questInterface;
items.items.items.put(0, Fixtures.item("minecraft:iron_ingot", 12));
items.items.items.put(1, Fixtures.namedItem("minecraft:written_book", 1, 0, "Proof"));
items.leaveItems = true;
items.ignoreDamage = true;
items.ignoreNBT = false;
} else if (type == EnumQuestType.Dialog) {
QuestDialog dialogs = (QuestDialog) quest.questInterface;
dialogs.dialogs.put(0, 1);
dialogs.dialogs.put(1, 2);
dialogs.dialogs.put(2, 3);
} else if (type == EnumQuestType.Kill || type == EnumQuestType.AreaKill) {
QuestKill kill = (QuestKill) quest.questInterface;
kill.targets.put("Zombie", 20);
kill.targets.put("Skeleton", 15);
kill.targetType = type == EnumQuestType.AreaKill ? 1 : 0;
kill.customTargetType = "noppes.npcs.entity.EntityCustomNpc";
} else if (type == EnumQuestType.Location) {
QuestLocation location = (QuestLocation) quest.questInterface;
location.location = "Northern Watchtower";
location.location2 = "Sunken Crypt";
location.location3 = "The Long Bridge";
} else if (type == EnumQuestType.Manual) {
QuestManual manual = (QuestManual) quest.questInterface;
manual.manuals.put("Speak to the smith", 1);
manual.manuals.put("Gather reeds", 30);
}
}
// ------------------------------------------------------------------ repeat and completion
private static void repeatAndCompletion(List<Case<Quest>> out) {
int id = 10;
for (EnumQuestRepeat repeat : EnumQuestRepeat.values()) {
Quest quest = quest(id, "Repeat " + repeat.name(), EnumQuestType.Manual);
quest.repeat = repeat;
// The two CUSTOM modes are the only ones that read customCooldown, but it is written
// unconditionally, so setting it everywhere shows that.
quest.customCooldown = 3600000L;
((QuestManual) quest.questInterface).manuals.put("Do the thing", 1);
out.add(new Case<Quest>("Repeat", quest,
"QuestRepeat = " + repeat.name() + " (ordinal " + repeat.ordinal() + ") with "
+ "CustomCooldown 3600000. MCDAILY/MCWEEKLY count world ticks, RLDAILY/RLWEEKLY "
+ "count wall time, and only MCCUSTOM/RLCUSTOM read the cooldown"));
id++;
}
int completionId = 18;
for (EnumQuestCompletion completion : EnumQuestCompletion.values()) {
Quest quest = quest(completionId, "Completion " + completion.name(), EnumQuestType.Manual);
quest.completion = completion;
quest.completerNpc = completion == EnumQuestCompletion.Npc ? "Quest Giver" : "";
((QuestManual) quest.questInterface).manuals.put("Do the thing", 1);
out.add(new Case<Quest>("Repeat", quest,
"QuestCompletion = " + completion.name() + ". Npc requires turning in to the named "
+ "NPC; Instant completes the moment the objective is met"));
completionId++;
}
Quest cooldownExtremes = quest(20, "Cooldown Extremes", EnumQuestType.Manual);
cooldownExtremes.repeat = EnumQuestRepeat.RLCUSTOM;
cooldownExtremes.customCooldown = Long.MAX_VALUE;
((QuestManual) cooldownExtremes.questInterface).manuals.put("Wait", 1);
out.add(new Case<Quest>("Repeat", cooldownExtremes,
"CustomCooldown at Long.MAX_VALUE -- the one long on a quest, and the field most "
+ "likely to be narrowed to an int by a reader"));
}
// ------------------------------------------------------------------ rewards
private static void rewards(List<Case<Quest>> out) {
Quest exp = quest(30, "Experience Reward", EnumQuestType.Manual);
exp.rewardExp = 2500;
((QuestManual) exp.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", exp, "RewardExp only"));
Quest items = quest(31, "Item Rewards", EnumQuestType.Manual);
items.rewardItems.items.put(0, Fixtures.item("minecraft:diamond", 5));
items.rewardItems.items.put(1, Fixtures.item("minecraft:gold_ingot", 32));
items.rewardItems.items.put(8, Fixtures.namedItem("minecraft:diamond_pickaxe", 1, 3, "Miner's Due"));
((QuestManual) items.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", items,
"three of the nine reward slots filled, including slot 8 and one stack with custom "
+ "NBT. Stored under the Rewards tag as an NpcMiscInventory"));
Quest full = quest(32, "Nine Item Rewards", EnumQuestType.Manual);
String[] nine = {
"minecraft:stone", "minecraft:dirt", "minecraft:oak_stairs", "minecraft:torch",
"minecraft:bread", "minecraft:coal", "minecraft:string", "minecraft:bone",
"minecraft:paper"
};
for (int i = 0; i < nine.length; i++) {
full.rewardItems.items.put(i, Fixtures.item(nine[i], i + 1));
}
((QuestManual) full.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", full,
"all nine reward slots filled, each a different count -- the inventory at capacity"));
Quest random = quest(33, "Random Reward", EnumQuestType.Manual);
random.randomReward = true;
random.rewardItems.items.put(0, Fixtures.item("minecraft:emerald", 1));
random.rewardItems.items.put(1, Fixtures.item("minecraft:redstone", 1));
((QuestManual) random.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", random,
"RandomReward true -- one of the reward slots is granted rather than all of them"));
Quest faction = quest(34, "Faction Reward", EnumQuestType.Manual);
faction.factionOptions.factionId = 14;
faction.factionOptions.factionPoints = 500;
faction.factionOptions.decreaseFactionPoints = false;
faction.factionOptions.faction2Id = 15;
faction.factionOptions.faction2Points = 250;
faction.factionOptions.decreaseFaction2Points = true;
((QuestManual) faction.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", faction,
"both faction reward slots, nested under QuestFactionPoints -- note a dialog writes "
+ "the same FactionOptions keys flat, not nested"));
Quest mail = quest(35, "Mail Reward", EnumQuestType.Manual);
mail.mail.subject = "Your reward";
mail.mail.sender = "The Guild";
mail.mail.time = Fixtures.EPOCH;
NBTTagCompound message = new NBTTagCompound();
message.setString("Text", "Enclosed, with thanks.");
mail.mail.message = message;
mail.mail.items[0] = Fixtures.item("minecraft:gold_nugget", 64);
mail.mail.items[3] = Fixtures.item("minecraft:cake", 1);
((QuestManual) mail.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", mail,
"QuestMail with two of four item slots, including the last slot"));
Quest command = quest(36, "Command On Completion", EnumQuestType.Manual);
command.command = "/give {player} minecraft:diamond 1";
((QuestManual) command.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", command, "QuestCommand with a {player} placeholder"));
Quest chain = quest(37, "Chains To Another", EnumQuestType.Manual);
chain.nextQuestid = 30;
chain.nextQuestTitle = "Experience Reward";
((QuestManual) chain.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", chain,
"NextQuestId 30 with a matching NextQuestTitle. On read CustomNPC+ overwrites the "
+ "title from the live controller and blanks it when the target is missing, so "
+ "the id is the real link and the title is a cache"));
Quest danglingChain = quest(38, "Chains Nowhere", EnumQuestType.Manual);
danglingChain.nextQuestid = 999999;
danglingChain.nextQuestTitle = "A quest that does not exist";
((QuestManual) danglingChain.questInterface).manuals.put("Earn it", 1);
out.add(new Case<Quest>("Rewards", danglingChain,
"NextQuestId pointing at nothing, with a stale title still on disk -- what a world "
+ "looks like after the target quest was deleted"));
}
// ------------------------------------------------------------------ party and profile
private static void partyAndProfile(List<Case<Quest>> out) {
// The party block is written only when AllowParty is true. Both halves matter.
Quest disabled = quest(50, "Party Disabled", EnumQuestType.Manual);
disabled.partyOptions.allowParty = false;
disabled.partyOptions.minPartySize = 4;
disabled.partyOptions.maxPartySize = 8;
((QuestManual) disabled.questInterface).manuals.put("Solo", 1);
out.add(new Case<Quest>("Party", disabled,
"AllowParty false with sizes assigned. Proves the eight party keys are ABSENT from "
+ "the file when the flag is off -- the values are lost upstream, so there is "
+ "nothing for a converter to preserve"));
Quest enabled = quest(51, "Party Enabled", EnumQuestType.Manual);
enabled.partyOptions.allowParty = true;
enabled.partyOptions.onlyParty = true;
enabled.partyOptions.partyRequirements = EnumPartyRequirements.All;
enabled.partyOptions.rewardControl = EnumPartyExchange.Enrolled;
enabled.partyOptions.completeFor = EnumPartyExchange.Valid;
enabled.partyOptions.executeCommand = EnumPartyExchange.All;
enabled.partyOptions.minPartySize = 2;
enabled.partyOptions.maxPartySize = 6;
enabled.partyOptions.objectiveRequirement = EnumPartyObjectives.Leader;
((QuestManual) enabled.questInterface).manuals.put("Together", 1);
out.add(new Case<Quest>("Party", enabled,
"AllowParty true and all eight party keys set to non-default enum constants"));
int id = 52;
for (EnumPartyRequirements requirement : EnumPartyRequirements.values()) {
Quest quest = quest(id, "Party Requirement " + requirement.name(), EnumQuestType.Manual);
quest.partyOptions.allowParty = true;
quest.partyOptions.partyRequirements = requirement;
((QuestManual) quest.questInterface).manuals.put("Together", 1);
out.add(new Case<Quest>("Party", quest,
"PartyRequirements = " + requirement.name() + " (ordinal " + requirement.ordinal() + ")"));
id++;
}
for (EnumPartyExchange exchange : EnumPartyExchange.values()) {
Quest quest = quest(id, "Party Reward " + exchange.name(), EnumQuestType.Manual);
quest.partyOptions.allowParty = true;
quest.partyOptions.rewardControl = exchange;
((QuestManual) quest.questInterface).manuals.put("Together", 1);
out.add(new Case<Quest>("Party", quest,
"RewardControl = " + exchange.name() + " (ordinal " + exchange.ordinal() + ")"));
id++;
}
for (EnumPartyObjectives objective : EnumPartyObjectives.values()) {
Quest quest = quest(id, "Party Objective " + objective.name(), EnumQuestType.Manual);
quest.partyOptions.allowParty = true;
quest.partyOptions.objectiveRequirement = objective;
((QuestManual) quest.questInterface).manuals.put("Together", 1);
out.add(new Case<Quest>("Party", quest,
"ObjectiveRequirement = " + objective.name() + " (ordinal " + objective.ordinal() + ")"));
id++;
}
Quest profileOff = quest(62, "Profiles Disabled", EnumQuestType.Manual);
profileOff.profileOptions.enableOptions = false;
profileOff.profileOptions.cooldownControl = EnumProfileSync.Shared;
((QuestManual) profileOff.questInterface).manuals.put("Alone", 1);
out.add(new Case<Quest>("Party", profileOff,
"EnableProfiles false with a Shared cooldown assigned -- the two profile keys are "
+ "absent from the file, same shape as the party block"));
int profileId = 63;
for (EnumProfileSync sync : EnumProfileSync.values()) {
Quest quest = quest(profileId, "Profile " + sync.name(), EnumQuestType.Manual);
quest.profileOptions.enableOptions = true;
quest.profileOptions.cooldownControl = sync;
quest.profileOptions.completeControl = sync;
((QuestManual) quest.questInterface).manuals.put("Alone", 1);
out.add(new Case<Quest>("Party", quest,
"EnableProfiles true, CooldownControl and CompleteControl = " + sync.name()));
profileId++;
}
}
// ------------------------------------------------------------------ objectives in depth
private static void objectives(List<Case<Quest>> out) {
Quest emptyKill = quest(70, "Kill Nothing", EnumQuestType.Kill);
out.add(new Case<Quest>("Objectives", emptyKill,
"a Kill quest with an EMPTY target list. isCompleted counts completed targets against "
+ "the target count, so zero of zero passes -- this quest is complete on accept"));
Quest manyKill = quest(71, "Kill Many Kinds", EnumQuestType.Kill);
QuestKill kill = (QuestKill) manyKill.questInterface;
String[] mobs = {"Zombie", "Skeleton", "Creeper", "Spider", "Enderman", "Blaze"};
for (int i = 0; i < mobs.length; i++) {
kill.targets.put(mobs[i], (i + 1) * 10);
}
out.add(new Case<Quest>("Objectives", manyKill,
"six kill targets. Stored as a TreeMap, so the file is alphabetical rather than "
+ "insertion-ordered -- Blaze first, Zombie last"));
Quest customTarget = quest(72, "Kill A Custom NPC", EnumQuestType.Kill);
QuestKill custom = (QuestKill) customTarget.questInterface;
custom.targets.put("Village Elder", 1);
custom.targetType = 1;
custom.customTargetType = "noppes.npcs.entity.EntityCustomNpc";
out.add(new Case<Quest>("Objectives", customTarget,
"TargetType 1 with a CustomTargetType class name -- targets an NPC by display name "
+ "rather than an entity by type"));
Quest emptyItems = quest(73, "Bring Nothing", EnumQuestType.Item);
QuestItem noItems = (QuestItem) emptyItems.questInterface;
noItems.ignoreDamage = true;
noItems.ignoreNBT = true;
noItems.leaveItems = true;
out.add(new Case<Quest>("Objectives", emptyItems,
"an Item quest with no required items and all three matching flags on"));
Quest variantItems = quest(74, "Bring Variants", EnumQuestType.Item);
QuestItem variants = (QuestItem) variantItems.questInterface;
variants.items.items.put(0, Fixtures.variant("minecraft:wool", 8, 14));
variants.items.items.put(1, Fixtures.variant("minecraft:planks", 4, 3));
variants.items.items.put(2, Fixtures.variant("minecraft:dye", 16, 4));
out.add(new Case<Quest>("Objectives", variantItems,
"three pre-Flattening variants -- red wool (14), jungle planks (3) and lapis dye (4). "
+ "Damage is a variant selector here, not durability, and each becomes a distinct "
+ "item after 1.13, so this is the case a variant table has to cover"));
Quest manyDialogs = quest(75, "Read Many Dialogs", EnumQuestType.Dialog);
QuestDialog dialogs = (QuestDialog) manyDialogs.questInterface;
for (int i = 0; i < 5; i++) {
dialogs.dialogs.put(i, 30 + i);
}
out.add(new Case<Quest>("Objectives", manyDialogs,
"five dialog objectives. NOTE the key collision worth knowing about: a Dialog quest "
+ "stores these under QuestDialogs, which is exactly where a pre-split Kill quest "
+ "stored its targets -- see the legacy world"));
Quest oneLocation = quest(76, "One Location", EnumQuestType.Location);
((QuestLocation) oneLocation.questInterface).location = "The Old Well";
out.add(new Case<Quest>("Objectives", oneLocation,
"only the first of three location slots set; the other two are written as empty"));
Quest manuals = quest(77, "Manual Counters", EnumQuestType.Manual);
QuestManual manual = (QuestManual) manuals.questInterface;
manual.manuals.put("Deliver the letter", 1);
manual.manuals.put("Light the beacons", 3);
manual.manuals.put("Survive the night", 1);
out.add(new Case<Quest>("Objectives", manuals,
"three manual counters -- progress a script or an operator advances by hand"));
}
// ------------------------------------------------------------------ combinations
private static void combinations(List<Case<Quest>> out) {
Quest everything = quest(90, "Everything At Once", EnumQuestType.Item);
everything.logText = "Bring the ingots, and be quick about it.";
everything.completeText = "You have my thanks.";
everything.completerNpc = "Quartermaster";
everything.command = "/say {player} finished";
everything.repeat = EnumQuestRepeat.MCCUSTOM;
everything.customCooldown = 172800000L;
everything.completion = EnumQuestCompletion.Instant;
everything.nextQuestid = 1;
everything.nextQuestTitle = "Type Item";
everything.rewardExp = 1000;
everything.randomReward = true;
everything.rewardItems.items.put(0, Fixtures.item("minecraft:diamond", 3));
everything.rewardItems.items.put(4, Fixtures.namedItem("minecraft:iron_sword", 1, 5, "Reward"));
everything.factionOptions.factionId = 0;
everything.factionOptions.factionPoints = 75;
everything.partyOptions.allowParty = true;
everything.partyOptions.onlyParty = false;
everything.partyOptions.partyRequirements = EnumPartyRequirements.Valid;
everything.partyOptions.rewardControl = EnumPartyExchange.All;
everything.partyOptions.minPartySize = 2;
everything.partyOptions.maxPartySize = 4;
everything.profileOptions.enableOptions = true;
everything.profileOptions.cooldownControl = EnumProfileSync.Shared;
everything.profileOptions.completeControl = EnumProfileSync.Individual;
everything.mail.subject = "Everything";
everything.mail.sender = "Quartermaster";
everything.mail.time = Fixtures.EPOCH;
everything.mail.items[0] = Fixtures.item("minecraft:emerald", 12);
QuestItem items = (QuestItem) everything.questInterface;
items.items.items.put(0, Fixtures.item("minecraft:iron_ingot", 20));
items.items.items.put(2, Fixtures.variant("minecraft:wool", 1, 11));
items.leaveItems = false;
items.ignoreDamage = false;
items.ignoreNBT = true;
out.add(new Case<Quest>("Combinations", everything,
"every quest sub-object populated at once: objective, rewards, faction, party, "
+ "profile, mail, chain, cooldown and command"));
Quest bare = quest(91, "Bare", EnumQuestType.Item);
out.add(new Case<Quest>("Combinations", bare,
"every field at its constructor default, for comparison against id 90"));
Quest unicode = quest(92, Text.CYRILLIC_QUEST + " " + Text.EM_DASH + " " + Text.ELEVES,
EnumQuestType.Manual);
unicode.logText = Text.RTL;
unicode.completeText = Text.ASTRAL;
unicode.completerNpc = Text.KATAKANA_FACTION;
((QuestManual) unicode.questInterface).manuals.put(Text.CYRILLIC_QUEST, 1);
out.add(new Case<Quest>("Combinations", unicode,
"non-Latin title, log text, complete text, completer name and objective key. The "
+ "objective key is the interesting one -- it is an NBT map key, not a value"));
}
// ------------------------------------------------------------------ helpers
/**
* Builds a quest with its type applied.
*
* <p>Order matters: {@code setType} replaces {@code questInterface} and stamps it with the
* quest id, so both must be set before the objective is populated.
*/
private static Quest quest(int id, String title, EnumQuestType type) {
Quest quest = new Quest();
quest.id = id;
quest.title = title;
quest.setType(type);
quest.logText = "Objective for " + title + ".";
quest.completeText = "Done: " + title + ".";
return quest;
}
}
@@ -1,52 +0,0 @@
package kamkeel.npcs.fixtures.content;
/**
* Non-ASCII strings the fixtures use, built from code points.
*
* <p>Every source file here is pure ASCII, and this class is why. A generator whose own source has
* been mojibaked by a CP-1252 toolchain emits fixtures that contain the mojibake, and then every
* reader tested against those fixtures agrees with it -- the corruption becomes the specification.
* Writing the code points out removes the whole class of accident, at the cost of one indirection.
*
* <p>The strings themselves matter: CustomNPC+ content is authored by players, in every language,
* with the section sign used for colour codes throughout.
*/
public final class Text {
private Text() {
}
/** The colour-code prefix, U+00A7. Appears in CustomNPC+'s own default effect name. */
public static final String SECTION = cp(0x00A7);
/** U+2014. Punctuation above Latin-1 that a byte-oriented reader truncates. */
public static final String EM_DASH = cp(0x2014);
/** "Eleves" with acute and grave accents -- two-byte UTF-8, still one char in Java. */
public static final String ELEVES = cp(0x00C9, 0x6C, 0x00E8, 0x76, 0x65, 0x73);
/** Katakana for "faction". Three-byte UTF-8, and outside anything CP-1252 can represent. */
public static final String KATAKANA_FACTION = cp(0x30D5, 0x30A1, 0x30AF, 0x30B7, 0x30E7, 0x30F3);
/** Cyrillic "Zadanie" (quest). */
public static final String CYRILLIC_QUEST = cp(0x0417, 0x0430, 0x0434, 0x0430, 0x043D, 0x0438, 0x0435);
/**
* A character outside the Basic Multilingual Plane -- U+1F5FF, the moai. One code point, two
* Java chars, four UTF-8 bytes. NBT strings are modified UTF-8, which encodes this as a
* surrogate pair rather than as one four-byte sequence, so it is the case where a reader that
* treats NBT strings as standard UTF-8 diverges from one that does not.
*/
public static final String ASTRAL = cp(0x1F5FF);
/** A right-to-left string: Arabic for "quest". Exercises no encoding rule, only rendering. */
public static final String RTL = cp(0x0645, 0x0647, 0x0645, 0x0629);
private static String cp(int... codePoints) {
StringBuilder sb = new StringBuilder(codePoints.length);
for (int codePoint : codePoints) {
sb.appendCodePoint(codePoint);
}
return sb.toString();
}
}
@@ -1,256 +0,0 @@
package kamkeel.npcs.fixtures.content;
import kamkeel.npcs.fixtures.Fixtures;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import noppes.npcs.controllers.data.Bank;
import noppes.npcs.controllers.data.SpawnData;
import noppes.npcs.controllers.data.Tag;
import noppes.npcs.controllers.data.TransportCategory;
import noppes.npcs.controllers.data.TransportLocation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* The world-level {@code .dat} documents: global, tags, transport, banks and spawns.
*
* <p>All five share a shape -- one compound holding a list of entries plus a {@code lastID} -- and
* each list is built here in a fixed order rather than by iterating the controller's HashMap, so
* regeneration is a no-op rather than a reshuffle.
*
* <p>Every document format below is copied from its controller's {@code getNBT}, named per method.
*/
public final class WorldDataFixtures {
private WorldDataFixtures() {
}
// ------------------------------------------------------------------ global.dat
/** GlobalDataController.saveData -- a single integer, and the smallest document CNPC+ writes. */
public static NBTTagCompound global(int itemGiverId) {
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("itemGiverId", itemGiverId);
return compound;
}
// ------------------------------------------------------------------ tags.dat
/**
* Tags. Note {@link Tag#uuid} defaults to {@code randomUUID()}, so every fixture here sets one
* explicitly -- otherwise the corpus would differ on every run and the reproducibility check
* would fail for a reason that has nothing to do with the format.
*/
public static NBTTagCompound tags() {
List<Tag> tags = new ArrayList<Tag>();
tags.add(tag(1, "Boss", 0xFF0000, "3f2504e0-4f89-41d3-9a0c-0305e82c3301", false));
tags.add(tag(2, "Hidden", 0x333333, "3f2504e0-4f89-41d3-9a0c-0305e82c3302", true));
tags.add(tag(3, "", 0x00FF00, "3f2504e0-4f89-41d3-9a0c-0305e82c3303", false));
tags.add(tag(4, Text.KATAKANA_FACTION, 0xFFFFFF,
"3f2504e0-4f89-41d3-9a0c-0305e82c3304", false));
tags.add(tag(5, "Extremes", -1, "ffffffff-ffff-ffff-ffff-ffffffffffff", true));
NBTTagList list = new NBTTagList();
for (Tag tag : tags) {
NBTTagCompound entry = new NBTTagCompound();
tag.writeNBT(entry);
list.appendTag(entry);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("lastID", 5);
compound.setTag("NPCTags", list);
return compound;
}
private static Tag tag(int id, String name, int color, String uuid, boolean hidden) {
Tag tag = new Tag();
tag.id = id;
tag.name = name;
tag.color = color;
tag.uuid = UUID.fromString(uuid);
tag.hideTag = hidden;
return tag;
}
// ------------------------------------------------------------------ transport.dat
/**
* Transport locations, grouped into categories.
*
* <p>The one place CustomNPC+ stores a dimension as a bare {@code int} alongside a position --
* which is the signature that stopped being expressible after 1.16, so it is worth having on
* disk in both a vanilla dimension and a modded id.
*/
public static NBTTagCompound transport() {
List<TransportCategory> categories = new ArrayList<TransportCategory>();
TransportCategory overworld = category(1, "Overworld");
overworld.locations.put(1, location(1, "Spawn Plaza", 0.5D, 64.0D, 0.5D, 0, 0));
overworld.locations.put(2, location(2, "Northern Watchtower", -1204.5D, 96.0D, 3311.5D, 1, 0));
overworld.locations.put(3, location(3, "Negative Coordinates",
-30000000.0D, -64.0D, -30000000.0D, 2, 0));
categories.add(overworld);
TransportCategory other = category(2, "Other Dimensions");
other.locations.put(4, location(4, "Nether Hub", 12.0D, 70.0D, -8.0D, 0, -1));
other.locations.put(5, location(5, "The End", 100.0D, 50.0D, 0.0D, 0, 1));
// A modded dimension id, which is the case a numeric-to-key translation table must either
// cover or refuse rather than silently map to the overworld.
other.locations.put(6, location(6, "Modded Dimension", 0.0D, 0.0D, 0.0D, 0, 7265));
categories.add(other);
TransportCategory empty = category(3, "Empty Category");
categories.add(empty);
NBTTagList list = new NBTTagList();
for (TransportCategory category : categories) {
NBTTagCompound entry = new NBTTagCompound();
category.writeNBT(entry);
list.appendTag(entry);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("lastID", 6);
compound.setTag("NPCTransportCategories", list);
return compound;
}
private static TransportCategory category(int id, String title) {
TransportCategory category = new TransportCategory();
category.id = id;
category.title = title;
return category;
}
private static TransportLocation location(int id, String name, double x, double y, double z,
int type, int dimension) {
TransportLocation location = new TransportLocation();
location.id = id;
location.name = name;
location.posX = x;
location.posY = y;
location.posZ = z;
location.type = type;
location.dimension = dimension;
return location;
}
// ------------------------------------------------------------------ bank.dat
/** BankController.getNBT -- note the key is "Data" and there is no lastID. */
public static NBTTagCompound banks() {
List<Bank> banks = new ArrayList<Bank>();
Bank basic = bank(1, "Village Bank", 2, 9);
basic.currencyInventory.items.put(0, Fixtures.item("minecraft:emerald", 1));
basic.upgradeInventory.items.put(0, Fixtures.item("minecraft:gold_ingot", 8));
for (int slot = 0; slot < 9; slot++) {
basic.slotTypes.put(slot, slot % 3);
}
banks.add(basic);
Bank bare = bank(2, "", 1, 1);
banks.add(bare);
Bank big = bank(3, "Vault", 6, 54);
big.currencyInventory.items.put(0, Fixtures.namedItem("minecraft:diamond", 64, 0, "Deposit"));
for (int slot = 0; slot < 54; slot++) {
big.slotTypes.put(slot, slot % 4);
}
banks.add(big);
NBTTagList list = new NBTTagList();
for (Bank bank : banks) {
NBTTagCompound entry = new NBTTagCompound();
bank.writeEntityToNBT(entry);
list.appendTag(entry);
}
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("Data", list);
return compound;
}
private static Bank bank(int id, String name, int startSlots, int maxSlots) {
Bank bank = new Bank();
bank.id = id;
bank.name = name;
bank.startSlots = startSlots;
bank.maxSlots = maxSlots;
return bank;
}
// ------------------------------------------------------------------ spawns.dat
/**
* Natural spawn entries.
*
* <p>The interesting shape here is {@code SpawnCompound<n>}: the per-variant NPC data is
* written as a numbered key rather than a list, so a reader has to probe for
* {@code SpawnCompound0}, {@code SpawnCompound1}, ... rather than iterate. The dimension set
* is written only when non-empty, so the key is absent on most entries.
*/
public static NBTTagCompound spawns() {
List<SpawnData> spawns = new ArrayList<SpawnData>();
SpawnData plains = spawn(1, "Plains Wanderer", 10);
plains.biomes.addAll(Arrays.asList("Plains", "Sunflower Plains", "Forest"));
plains.spawnCompounds.put(0, npcStub("Wanderer"));
spawns.add(plains);
SpawnData variants = spawn(2, "Cave Dweller", 3);
variants.biomes.add("Extreme Hills");
variants.dimensions.addAll(Arrays.asList(0, -1, 7265));
variants.monsterSpawning = true;
variants.animalSpawning = false;
variants.airSpawning = true;
variants.liquidSpawning = true;
variants.spawnHeightMin = 5;
variants.spawnHeightMax = 40;
variants.maxAlive = 12;
variants.cooldownTicks = 600;
variants.attemptsPerCycle = 4;
// Three numbered compounds, which is the shape worth pinning.
variants.spawnCompounds.put(0, npcStub("Dweller A"));
variants.spawnCompounds.put(1, npcStub("Dweller B"));
variants.spawnCompounds.put(2, npcStub("Dweller C"));
spawns.add(variants);
SpawnData bare = spawn(3, "", 0);
spawns.add(bare);
NBTTagList list = new NBTTagList();
for (SpawnData spawn : spawns) {
list.appendTag(spawn.writeNBT(new NBTTagCompound()));
}
NBTTagCompound compound = new NBTTagCompound();
compound.setInteger("lastID", 3);
compound.setTag("NPCSpawnData", list);
return compound;
}
private static SpawnData spawn(int id, String name, int weight) {
SpawnData spawn = new SpawnData();
spawn.id = id;
spawn.name = name;
spawn.itemWeight = weight;
return spawn;
}
/**
* A stand-in for a stored NPC.
*
* <p>Deliberately not a real {@code EntityCustomNpc}: constructing one needs a World, and a
* spawn entry stores whatever compound it was given without inspecting it. A fixture with a
* full NPC in it belongs with the NPC system, which is not covered here yet -- so this says
* what it is rather than pretending.
*/
private static NBTTagCompound npcStub(String name) {
NBTTagCompound stub = new NBTTagCompound();
stub.setString("Name", name);
stub.setString("FixtureNote", "placeholder -- not a serialized EntityCustomNpc");
return stub;
}
}
@@ -1,86 +0,0 @@
package kamkeel.npcs.fixtures.worlds;
import kamkeel.npcs.fixtures.FixtureWorld;
import kamkeel.npcs.fixtures.WorldWriter;
import kamkeel.npcs.fixtures.content.FactionFixtures;
import noppes.npcs.constants.EnumOptionType;
import noppes.npcs.controllers.data.Dialog;
import noppes.npcs.controllers.data.DialogOption;
import noppes.npcs.controllers.data.Faction;
import java.util.List;
/**
* What CustomNPC+ writes for a world nobody has edited.
*
* <p>Worth its own world because "the defaults" is a real contract and an easy thing to get subtly
* wrong: a reader that supplies its own idea of a default agrees with this file on every field it
* happens to share and disagrees on the rest, silently. Reproduced from
* FactionController.loadFactions and DialogController.loadDefaultDialogs.
*/
public final class DefaultsWorld implements FixtureWorld {
public String name() {
return "defaults";
}
public String purpose() {
return "exactly what CustomNPC+ creates for a fresh world -- the three default factions and "
+ "the three Villager dialogs -- and nothing else.";
}
public void build(WorldWriter out) {
List<Faction> factions = FactionFixtures.vanillaDefaults();
out.dat("faction", "factions.dat", FactionFixtures.document(factions, 0),
"the three factions FactionController creates when factions.dat is missing or empty: "
+ "Friendly 2000, Neutral 1000, Aggressive 0");
// Copied field for field from DialogController.loadDefaultDialogs.
Dialog start = new Dialog();
start.id = 1;
start.title = "Start";
start.text = "Hello {player}, \n\nWelcome to our village. I hope you enjoy your stay";
Dialog village = new Dialog();
village.id = 2;
village.title = "Ask about village";
village.text = "This village has been around for ages. Enjoy your stay here.";
Dialog who = new Dialog();
who.id = 3;
who.title = "Who are you";
who.text = "I'm a villager here. I have lived in this village my whole life.";
DialogOption toVillage = new DialogOption();
toVillage.title = "Tell me something about this village";
toVillage.dialogId = 2;
toVillage.optionType = EnumOptionType.DialogOption;
DialogOption toWho = new DialogOption();
toWho.title = "Who are you?";
toWho.dialogId = 3;
toWho.optionType = EnumOptionType.DialogOption;
DialogOption goodbye = new DialogOption();
goodbye.title = "Goodbye";
goodbye.optionType = EnumOptionType.QuitOption;
start.options.put(0, toWho);
start.options.put(1, toVillage);
start.options.put(2, goodbye);
DialogOption back = new DialogOption();
back.title = "Back";
back.dialogId = 1;
village.options.put(1, back);
who.options.put(1, back);
out.dialog("Villager", start,
"CustomNPC+'s own default dialog 1, with its three options. Note showWheel is false "
+ "here because the object was never read back -- readNBTPartial defaults an "
+ "absent DialogShowWheel to true, which the writer does not do");
out.dialog("Villager", village, "CustomNPC+'s own default dialog 2");
out.dialog("Villager", who, "CustomNPC+'s own default dialog 3");
}
}
Loaded 100 of 850 files, more files were not shown because too many files have changed in this diff. Show more