Merge branch 'dev' into pr-254

# Conflicts:
#	src/main/java/noppes/npcs/client/gui/GuiNpcMobSpawnerSelector.java
This commit is contained in:
KAMKEEL committed 2026-08-11 06:29:18 -04:00
commit 22a8ef5036
791 files changed
+117380 -18377

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
<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
@@ -0,0 +1,11 @@
<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
@@ -0,0 +1,954 @@
/* ============================================================
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
@@ -0,0 +1,14 @@
<!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
@@ -0,0 +1,19 @@
{
"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
@@ -0,0 +1,64 @@
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
@@ -0,0 +1,16 @@
.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
@@ -0,0 +1,97 @@
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>
)
}
@@ -0,0 +1,143 @@
.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
@@ -0,0 +1,29 @@
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>
)
}
@@ -0,0 +1,36 @@
.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
@@ -0,0 +1,18 @@
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>
)
}
@@ -0,0 +1,46 @@
.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
@@ -0,0 +1,30 @@
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>
)
}
@@ -0,0 +1,47 @@
.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); }
}
@@ -0,0 +1,186 @@
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>
)
}
@@ -0,0 +1,303 @@
.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
@@ -0,0 +1,38 @@
// ─── 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
@@ -0,0 +1,50 @@
*, *::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
@@ -0,0 +1,13 @@
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
@@ -0,0 +1,94 @@
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
@@ -0,0 +1,12 @@
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
@@ -0,0 +1,18 @@
#!/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
@@ -0,0 +1,107 @@
#!/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
@@ -0,0 +1,52 @@
#!/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:
fetch-depth: 0
- name: Initialize CNPC+ API submodule
run: git submodule update --init --recursive src/api
- name: Initialize submodules
run: git submodule update --init --recursive
- name: Checkout workflows repo
uses: actions/checkout@v4
+224
View File
@@ -0,0 +1,224 @@
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
+4
View File
@@ -44,3 +44,7 @@ run
src/main/resources/assets/customnpcs/api
df/
tmp/
src/test
node_modules
.github/pages-dist
-144
View File
@@ -1,144 +0,0 @@
# CNPC+ 1.11 Ability System Beta
🟡 **In Testing**
## Features: ⚒️
- **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
@@ -1,199 +0,0 @@
# ⚔️ 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
---
-57
View File
@@ -1,57 +0,0 @@
# CNPC+ 1.11 Beta - Market Update
🟡 **In Testing**
## 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
@@ -1,121 +0,0 @@
# 🏪 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
@@ -0,0 +1,98 @@
# 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
+402 -65
View File
@@ -1,95 +1,432 @@
![CustomNPC+ Banner](images/logo_banner.png)
## 👋 Welcome to the CustomNPC+ Repository.
![](images/logo_banner.png)
# CustomNPC+
> 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 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 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 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)
----------------
---
### ❗ 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)
## Installation
### ⬇️ Downloads
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.
> 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)
- **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.
---
### ❓ 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
<a href="https://ko-fi.com/kamkeel"> <img src="images/Kofi.png" width="400" height="60"> </a>
#### 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)
> More betas with new features will continue to be released to supporters for **Early Access** to new content!
## 🔰 Skin Model Feature:
###### **Majority of these cape designs are taken from the internet with fair-usage.*
##### ❔ Please note all *local* skins in this version of CustomNPC, must match the model selected.
<img src="images/skinAnimation.gif" width="474" height="260"/>
---
## Feature Overview
### 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"/>
#### Url64:
<img src="images/Url64Example.gif" width="474" height="260"/>
---
#### DarkMode + Cloner GUI:
<img src="images/ClonerGUI-DarkMode.png" width="474" height="260"/>
### NPC Roles & Jobs
## 🔗 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.
**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.
[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.
---
[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.
### Dialog System
## Cloning / Compiling / Building
Create branching dialog trees for storytelling and player interaction.
git clone call `git submodule update --init --recursive`
<img src="images/Dialog.png" width="474" height="260"/>
Using IntelliJ, take the following steps:
1. Run `setupDecompWorkspace` under the `forgegradle` tab.
2. Refresh Gradle.
3. Run `genIntellijRuns` under the `other` tab to set up your Minecraft runs.
- **Dialog Trees** - Multi-level branching conversations with unlimited depth
- **Dialog Options** - Player choices that affect outcomes, trigger quests, or change faction standings
- **Dialog Images** - Display images alongside dialog text
- **Dialog Colors** - Customizable text and background colors
- **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.
---
Mixin code will not work if you do not add `--tweakClass org.spongepowered.asm.launch.MixinTweaker --mixin customnpcs.mixins.json` to your program arguments.
### Quest System
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).
+54 -1
View File
@@ -3,9 +3,10 @@
plugins {
id 'com.gtnewhorizons.gtnhconvention'
id 'idea'
id "dts.typescript-generator"
}
version = "1.11-beta1"
version = "1.11.1"
group= "kamkeel.customnpc-plus"
archivesBaseName = "CustomNPC-Plus"
@@ -56,5 +57,57 @@ sourceSets.main.java {
srcDirs += apiDir
}
// ============================================================================
// 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 {
sourceDirectories = ['src/api/java', 'src/main/java']
outputDirectory = "src/main/resources/assets/${project.property("modId")}/api"
apiPackages = ['noppes.npcs.api', 'net.minecraft'] as Set
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
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'
+5 -3
View File
@@ -35,7 +35,7 @@
*/
def embedMixin = !project.hasProperty("nomixin");
dependencies {
runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.5.4-GTNH:dev")
runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.8.44-GTNH:dev")
if (!project.hasProperty("noNashorn")) {
runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946")
}
@@ -43,8 +43,10 @@ dependencies {
// compileOnly(files("./tools/bukkit-api/spigot-api-ONLY.jar"))
// compileOnly(files("./tools/bukkit-api/Vault-1.4.1.jar"))
shadowImplementation(project.files("tools/standalone-JaninoLoader-1.0.1-ALPHA.jar"))
annotationProcessor(project.files("tools/standalone-JaninoLoader-1.0.1-ALPHA.jar"))
shadowImplementation(project.files("tools/standalone-JaninoLoader-1.0.2.jar"))
annotationProcessor(project.files("tools/standalone-JaninoLoader-1.0.2.jar"))
testImplementation("junit:junit:4.13.2")
if(embedMixin){
// Normal Jar will include built in Mixins
+126
View File
@@ -0,0 +1,126 @@
/**
* 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
@@ -0,0 +1,36 @@
/**
* 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
@@ -0,0 +1,168 @@
/**
* 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
@@ -0,0 +1,81 @@
/**
* 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
@@ -0,0 +1,75 @@
/**
* 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
@@ -0,0 +1,100 @@
/**
* 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
@@ -0,0 +1,128 @@
/**
* 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
@@ -0,0 +1,74 @@
/**
* 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
@@ -0,0 +1,105 @@
/**
* 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
@@ -0,0 +1,94 @@
/**
* 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
@@ -0,0 +1,82 @@
/**
* 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;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 554 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 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

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 230 KiB

After

Width:  |  Height:  |  Size: 230 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 MiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 337 KiB

After

Width:  |  Height:  |  Size: 337 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 573 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 787 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 227 KiB

After

Width:  |  Height:  |  Size: 227 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.0 MiB

+12 -1
View File
@@ -1,6 +1,14 @@
pluginManagement {
// resolutionStrategy {
// eachPlugin {
// if(requested.id.toString() == "dts.typescript-generator") {
// useModule("com.github.bigguy345:dts-gradle-plugin:95b8ab4")
// }
// }
// }
//
repositories {
maven { url "https://jitpack.io"}
maven {
// RetroFuturaGradle
name "GTNH Maven"
@@ -19,3 +27,6 @@ pluginManagement {
plugins {
id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.27'
}
// Include the local gradle-plugins composite build so plugin is resolved locally
includeBuild 'gradle-plugins'
+1 -1
Submodule src/api updated: fd4c77d015...e7f363727e.
+2 -1
View File
@@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand;
import foxz.commandhelper.permissions.OpOnly;
import foxz.commandhelper.permissions.ParamCheck;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import net.minecraft.command.CommandBase;
import net.minecraft.entity.player.EntityPlayer;
import noppes.npcs.NoppesUtilServer;
@@ -90,7 +91,7 @@ public class CmdDialog extends ChMcLogger {
)
public boolean reload(String args[]) {
new DialogController().load();
SyncController.syncAllDialogs();
SyncController.syncAll(SyncType.DIALOG_CATEGORY);
return true;
}
+1 -1
View File
@@ -142,7 +142,7 @@ public class CmdNpc extends ChMcLogger {
EntityCustomNpc npc = new EntityCustomNpc(pw);
if (args.length > 0)
npc.display.name = args[0];
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.cameraYaw, player.cameraPitch);
npc.setPositionAndRotation(player.posX, player.posY, player.posZ, player.rotationYaw, 0);
npc.ais.startPos = new int[]{MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)};
pw.spawnEntityInWorld(npc);
npc.setHealth(npc.getMaxHealth());
+2 -1
View File
@@ -6,6 +6,7 @@ import foxz.commandhelper.annotations.SubCommand;
import foxz.commandhelper.permissions.OpOnly;
import foxz.commandhelper.permissions.ParamCheck;
import kamkeel.npcs.controllers.SyncController;
import kamkeel.npcs.network.enums.SyncType;
import kamkeel.npcs.network.packets.data.AchievementPacket;
import kamkeel.npcs.network.packets.data.ChatAlertPacket;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -170,7 +171,7 @@ public class CmdQuest extends ChMcLogger {
)
public boolean reload(String args[]) {
new QuestController().load();
SyncController.syncAllQuests();
SyncController.syncAll(SyncType.QUEST_CATEGORY);
return true;
}
}
@@ -37,6 +37,15 @@ public class DBCAddon {
public void doDBCDamage(EntityNPCInterface npc, float attackStrength, Entity receiver) {
}
/**
* Returns the pre-calculated DBC attack damage of the current attacker,
* or the vanilla damage if DBC damage was not calculated.
* Used by Counter (PERCENT mode) to base counter damage on the full DBC attack, not vanilla base.
*/
public float getAttackerDBCDamage(float vanillaDamage) {
return vanillaDamage;
}
public boolean isKO(EntityNPCInterface npc, EntityPlayer player) {
return false;
}
@@ -0,0 +1,42 @@
package kamkeel.npcs.client.command;
import kamkeel.npcs.util.CNPCDebug;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
/**
* Client-only command to toggle debug logging.
* Registered via ClientCommandHandler so it runs entirely on the client
* without sending a packet to the server.
*/
public class CommandCNPCDebugger extends CommandBase {
@Override
public String getCommandName() {
return "cnpcdebugger";
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "/cnpcdebugger <type> - Toggle client debug logging for a type (e.g. energy)";
}
@Override
public int getRequiredPermissionLevel() {
return 0;
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args.length == 0) {
sender.addChatMessage(new ChatComponentText("\u00A7cUsage: /cnpcdebugger <type>"));
return;
}
String type = args[0].toLowerCase();
boolean newState = CNPCDebug.toggleClient(type);
String stateText = newState ? "\u00A7aENABLED" : "\u00A7cDISABLED";
sender.addChatMessage(new ChatComponentText("\u00A77[CNPC+] \u00A7eClient debug '" + type + "' " + stateText));
}
}
@@ -0,0 +1,38 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import kamkeel.npcs.controllers.data.energycharge.EnergyChargePreviewManager;
import kamkeel.npcs.entity.EntityEnergyProjectile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.client.event.RenderWorldLastEvent;
/**
* Renders packet-driven charging previews through RenderManager.
*/
public class EnergyChargePreviewRenderer {
@SubscribeEvent
public void onRenderWorldLast(RenderWorldLastEvent event) {
if (EnergyChargePreviewManager.ClientInstance == null || !EnergyChargePreviewManager.ClientInstance.hasPreviews()) {
return;
}
Minecraft mc = Minecraft.getMinecraft();
EntityPlayer player = mc.thePlayer;
if (player == null) return;
float partialTicks = event.partialTicks;
for (EntityEnergyProjectile entity : EnergyChargePreviewManager.ClientInstance.getPreviews()) {
if (entity == null || entity.isDead) continue;
double x = entity.prevPosX + (entity.posX - entity.prevPosX) * partialTicks - RenderManager.renderPosX;
double y = entity.prevPosY + (entity.posY - entity.prevPosY) * partialTicks - RenderManager.renderPosY;
double z = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * partialTicks - RenderManager.renderPosZ;
RenderManager.instance.renderEntityWithPosYaw(entity, x, y, z, entity.rotationYaw, partialTicks);
}
}
}
@@ -1,259 +0,0 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
/**
* Base renderer for ability projectiles.
* Provides common GL state setup and rendering utilities.
*
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public abstract class RenderAbilityProjectile extends Render {
protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png");
public RenderAbilityProjectile() {
this.shadowSize = 0.0f;
}
/**
* Setup GL state for translucent, self-illuminated rendering.
* Forces full brightness so world lighting does not affect projectiles.
*/
protected void setupRenderState() {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_TEXTURE_2D);
// Force full brightness - prevents world lighting from darkening projectiles
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f);
}
/**
* Restore GL state after rendering.
*/
protected void restoreRenderState() {
GL11.glPopAttrib();
GL11.glPopMatrix();
}
/**
* Extract RGB components from color int.
*/
protected float[] extractRGB(int color) {
float r = ((color >> 16) & 0xFF) / 255.0f;
float g = ((color >> 8) & 0xFF) / 255.0f;
float b = (color & 0xFF) / 255.0f;
return new float[]{r, g, b};
}
/**
* Render a cube centered at origin with given color and alpha.
*/
protected void renderCube(int color, float alpha, float halfSize) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
// Front face (z+)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 0, 1);
tess.addVertex(-halfSize, -halfSize, halfSize);
tess.addVertex(halfSize, -halfSize, halfSize);
tess.addVertex(halfSize, halfSize, halfSize);
tess.addVertex(-halfSize, halfSize, halfSize);
tess.draw();
// Back face (z-)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 0, -1);
tess.addVertex(halfSize, -halfSize, -halfSize);
tess.addVertex(-halfSize, -halfSize, -halfSize);
tess.addVertex(-halfSize, halfSize, -halfSize);
tess.addVertex(halfSize, halfSize, -halfSize);
tess.draw();
// Top face (y+)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 1, 0);
tess.addVertex(-halfSize, halfSize, halfSize);
tess.addVertex(halfSize, halfSize, halfSize);
tess.addVertex(halfSize, halfSize, -halfSize);
tess.addVertex(-halfSize, halfSize, -halfSize);
tess.draw();
// Bottom face (y-)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, -1, 0);
tess.addVertex(-halfSize, -halfSize, -halfSize);
tess.addVertex(halfSize, -halfSize, -halfSize);
tess.addVertex(halfSize, -halfSize, halfSize);
tess.addVertex(-halfSize, -halfSize, halfSize);
tess.draw();
// Right face (x+)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(1, 0, 0);
tess.addVertex(halfSize, -halfSize, halfSize);
tess.addVertex(halfSize, -halfSize, -halfSize);
tess.addVertex(halfSize, halfSize, -halfSize);
tess.addVertex(halfSize, halfSize, halfSize);
tess.draw();
// Left face (x-)
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(-1, 0, 0);
tess.addVertex(-halfSize, -halfSize, -halfSize);
tess.addVertex(-halfSize, -halfSize, halfSize);
tess.addVertex(-halfSize, halfSize, halfSize);
tess.addVertex(-halfSize, halfSize, -halfSize);
tess.draw();
}
/**
* Render a flat disc (cylinder with very small height) centered at origin.
* The disc lies flat on the XZ plane.
*/
protected void renderDisc(int color, float alpha, float radius, float thickness, int segments) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
float halfThick = thickness * 0.5f;
// Top face
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 1, 0);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
tess.addVertex(0, halfThick, 0);
tess.addVertex(x1, halfThick, z1);
tess.addVertex(x2, halfThick, z2);
tess.addVertex(0, halfThick, 0);
}
tess.draw();
// Bottom face
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, -1, 0);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
tess.addVertex(0, -halfThick, 0);
tess.addVertex(x2, -halfThick, z2);
tess.addVertex(x1, -halfThick, z1);
tess.addVertex(0, -halfThick, 0);
}
tess.draw();
// Edge
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
// Normal pointing outward
float nx = (float) Math.cos((angle1 + angle2) * 0.5);
float nz = (float) Math.sin((angle1 + angle2) * 0.5);
tess.setNormal(nx, 0, nz);
tess.addVertex(x1, -halfThick, z1);
tess.addVertex(x2, -halfThick, z2);
tess.addVertex(x2, halfThick, z2);
tess.addVertex(x1, halfThick, z1);
}
tess.draw();
}
/**
* Render a line segment as a quad billboard facing the camera.
*/
protected void renderLineSegment(double x1, double y1, double z1,
double x2, double y2, double z2,
float width, int color, float alpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
// Calculate direction
double dx = x2 - x1;
double dy = y2 - y1;
double dz = z2 - z1;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len < 0.001) return;
// Perpendicular vectors for billboard
double perpX, perpY, perpZ;
if (Math.abs(dy) < 0.9) {
// Cross with up vector
perpX = -dz;
perpY = 0;
perpZ = dx;
} else {
// Cross with right vector
perpX = 0;
perpY = dz;
perpZ = -dy;
}
double perpLen = Math.sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ);
if (perpLen > 0) {
perpX = perpX / perpLen * width * 0.5;
perpY = perpY / perpLen * width * 0.5;
perpZ = perpZ / perpLen * width * 0.5;
}
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.addVertex(x1 - perpX, y1 - perpY, z1 - perpZ);
tess.addVertex(x2 - perpX, y2 - perpY, z2 - perpZ);
tess.addVertex(x2 + perpX, y2 + perpY, z2 + perpZ);
tess.addVertex(x1 + perpX, y1 + perpY, z1 + perpZ);
tess.draw();
}
@Override
protected ResourceLocation getEntityTexture(Entity entity) {
return WHITE_TEXTURE;
}
}
@@ -0,0 +1,410 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityEnergyAbility;
import kamkeel.npcs.entity.EntityEnergyProjectile;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.config.ConfigClient;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
/**
* Base renderer for ability projectiles.
* Provides common GL state setup and rendering utilities.
* <p>
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public abstract class RenderEnergy extends Render {
protected static final ResourceLocation WHITE_TEXTURE = new ResourceLocation("customnpcs", "textures/entity/white.png");
protected static final int HIDE_INITIAL_ACTIVE_TICKS = 1;
public RenderEnergy() {
this.shadowSize = 0.0f;
}
/**
* Hide the first active tick to avoid the visible spawn-frame pause at fire time.
* Charging previews are never hidden.
*/
protected boolean shouldSkipInitialActiveRender(Entity entity) {
if (!(entity instanceof EntityEnergyAbility)) return false;
EntityEnergyAbility ability = (EntityEnergyAbility) entity;
return !ability.isPreviewMode() && !ability.isCharging() && ability.ticksExisted <= HIDE_INITIAL_ACTIVE_TICKS;
}
/**
* Setup GL state for translucent, self-illuminated rendering.
* Forces full brightness so world lighting does not affect projectiles.
*/
protected void setupRenderState() {
GL11.glPushMatrix();
GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glAlphaFunc(GL11.GL_GREATER, 0.003921569F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_TEXTURE_2D);
// Force full brightness - prevents world lighting from darkening projectiles
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f);
}
/**
* Restore GL state after rendering.
*/
protected void restoreRenderState() {
GL11.glPopAttrib();
GL11.glPopMatrix();
}
/**
* Extract RGB components from color int.
*/
protected float[] extractRGB(int color) {
float r = ((color >> 16) & 0xFF) / 255.0f;
float g = ((color >> 8) & 0xFF) / 255.0f;
float b = (color & 0xFF) / 255.0f;
return new float[]{r, g, b};
}
/**
* Render a cube centered at origin with given color and alpha.
*/
protected void renderCube(int color, float alpha, float halfSize) {
Tessellator tess = Tessellator.instance;
float r = ((color >> 16) & 0xFF) / 255.0f;
float g = ((color >> 8) & 0xFF) / 255.0f;
float b = (color & 0xFF) / 255.0f;
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
addCubeVertices(tess, 0, 0, 0, halfSize);
tess.draw();
}
// ==================== BATCHED CUBE RENDERING ====================
/**
* Begin a batched cube draw call. All cubes added via {@link #addBatchedCube}
* will be drawn in a single tessellator pass when {@link #endCubeBatch} is called.
*/
protected void beginCubeBatch() {
Tessellator.instance.startDrawingQuads();
}
/**
* Add a cube to the current batch at the given position with per-cube color/alpha.
* Must be called between {@link #beginCubeBatch} and {@link #endCubeBatch}.
*/
protected void addBatchedCube(float px, float py, float pz, float halfSize,
float r, float g, float b, float alpha) {
Tessellator tess = Tessellator.instance;
tess.setColorRGBA_F(r, g, b, alpha);
addCubeVertices(tess, px, py, pz, halfSize);
}
/**
* End the batched cube draw call, flushing all queued cubes in one draw.
*/
protected void endCubeBatch() {
Tessellator.instance.draw();
}
/**
* Add the 24 vertices (6 faces) of a cube centered at (px,py,pz) to the tessellator.
* Color must be set before calling. Used by both single and batched cube rendering.
*/
private static void addCubeVertices(Tessellator tess, float px, float py, float pz, float h) {
float x0 = px - h, x1 = px + h;
float y0 = py - h, y1 = py + h;
float z0 = pz - h, z1 = pz + h;
// Front (z+)
tess.setNormal(0, 0, 1);
tess.addVertex(x0, y0, z1);
tess.addVertex(x1, y0, z1);
tess.addVertex(x1, y1, z1);
tess.addVertex(x0, y1, z1);
// Back (z-)
tess.setNormal(0, 0, -1);
tess.addVertex(x1, y0, z0);
tess.addVertex(x0, y0, z0);
tess.addVertex(x0, y1, z0);
tess.addVertex(x1, y1, z0);
// Top (y+)
tess.setNormal(0, 1, 0);
tess.addVertex(x0, y1, z1);
tess.addVertex(x1, y1, z1);
tess.addVertex(x1, y1, z0);
tess.addVertex(x0, y1, z0);
// Bottom (y-)
tess.setNormal(0, -1, 0);
tess.addVertex(x0, y0, z0);
tess.addVertex(x1, y0, z0);
tess.addVertex(x1, y0, z1);
tess.addVertex(x0, y0, z1);
// Right (x+)
tess.setNormal(1, 0, 0);
tess.addVertex(x1, y0, z1);
tess.addVertex(x1, y0, z0);
tess.addVertex(x1, y1, z0);
tess.addVertex(x1, y1, z1);
// Left (x-)
tess.setNormal(-1, 0, 0);
tess.addVertex(x0, y0, z0);
tess.addVertex(x0, y0, z1);
tess.addVertex(x0, y1, z1);
tess.addVertex(x0, y1, z0);
}
/**
* Render a flat disc (cylinder with very small height) centered at origin.
* The disc lies flat on the XZ plane.
*/
protected void renderDisc(int color, float alpha, float radius, float thickness, int segments) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
float halfThick = thickness * 0.5f;
// Top face
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 1, 0);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
tess.addVertex(0, halfThick, 0);
tess.addVertex(x1, halfThick, z1);
tess.addVertex(x2, halfThick, z2);
tess.addVertex(0, halfThick, 0);
}
tess.draw();
// Bottom face
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, -1, 0);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
tess.addVertex(0, -halfThick, 0);
tess.addVertex(x2, -halfThick, z2);
tess.addVertex(x1, -halfThick, z1);
tess.addVertex(0, -halfThick, 0);
}
tess.draw();
// Edge
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
for (int i = 0; i < segments; i++) {
float angle1 = (float) (2 * Math.PI * i / segments);
float angle2 = (float) (2 * Math.PI * (i + 1) / segments);
float x1 = (float) Math.cos(angle1) * radius;
float z1 = (float) Math.sin(angle1) * radius;
float x2 = (float) Math.cos(angle2) * radius;
float z2 = (float) Math.sin(angle2) * radius;
// Normal pointing outward
float nx = (float) Math.cos((angle1 + angle2) * 0.5);
float nz = (float) Math.sin((angle1 + angle2) * 0.5);
tess.setNormal(nx, 0, nz);
tess.addVertex(x1, -halfThick, z1);
tess.addVertex(x2, -halfThick, z2);
tess.addVertex(x2, halfThick, z2);
tess.addVertex(x1, halfThick, z1);
}
tess.draw();
}
/**
* Render a line segment as a quad billboard facing the camera.
*/
protected void renderLineSegment(double x1, double y1, double z1,
double x2, double y2, double z2,
float width, int color, float alpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
// Calculate direction
double dx = x2 - x1;
double dy = y2 - y1;
double dz = z2 - z1;
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (len < 0.001) return;
// Perpendicular vectors for billboard
double perpX, perpY, perpZ;
if (Math.abs(dy) < 0.9) {
// Cross with up vector
perpX = -dz;
perpY = 0;
perpZ = dx;
} else {
// Cross with right vector
perpX = 0;
perpY = dz;
perpZ = -dy;
}
double perpLen = Math.sqrt(perpX * perpX + perpY * perpY + perpZ * perpZ);
if (perpLen > 0) {
perpX = perpX / perpLen * width * 0.5;
perpY = perpY / perpLen * width * 0.5;
perpZ = perpZ / perpLen * width * 0.5;
}
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
tess.addVertex(x1 - perpX, y1 - perpY, z1 - perpZ);
tess.addVertex(x2 - perpX, y2 - perpY, z2 - perpZ);
tess.addVertex(x2 + perpX, y2 + perpY, z2 + perpZ);
tess.addVertex(x1 + perpX, y1 + perpY, z1 + perpZ);
tess.draw();
}
// ==================== SHARED LIGHTNING ====================
/**
* Get or create the lightning state for an energy entity.
* Uses the lightningState field on EntityEnergyAbility (stored as Object
* to avoid client class loading on server).
*/
protected AttachedLightningRenderer.LightningState getLightningState(EntityEnergyAbility entity) {
if (entity.lightningState == null) {
entity.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) entity.lightningState;
}
/**
* Render attached lightning arcs around an energy entity.
*
* @param entity the energy entity
* @param innerScale multiplier for inner radius (e.g. 0.3f for projectiles, 0.95f for dome)
* @param baseSize the entity's current render size/scale
*/
protected void renderAttachedLightning(EntityEnergyAbility entity, float innerScale, float baseSize) {
AttachedLightningRenderer.LightningState state = getLightningState(entity);
float density = entity.getLightningDensity();
float innerRadius = innerScale * baseSize;
float radius = innerRadius + entity.getLightningRadius() * baseSize;
int outerColor = entity.getOuterColor();
int innerColor = entity.getInnerColor();
int fadeTime = entity.getLightningFadeTime();
// Barrier impact spark: briefly force brighter white crackles at the contact point.
if (entity instanceof EntityEnergyProjectile) {
int sparkTicks = ((EntityEnergyProjectile) entity).getBarrierSparkTicks();
if (sparkTicks > 0) {
density = Math.max(density, 4.0f + sparkTicks * 0.6f);
radius = Math.max(radius, innerRadius + Math.max(0.35f, baseSize * 0.65f));
outerColor = 0xF0F6FF;
innerColor = 0xFFFFFF;
fadeTime = Math.max(fadeTime, 6);
}
}
state.update(density, radius, outerColor, innerColor, fadeTime);
state.render();
}
// ==================== PROXIMITY ALPHA ====================
/**
* Calculate a proximity-based alpha multiplier for owner's energy projectiles.
* Returns a factor between ProximityAlphaMin and 1.0 based on:
* - Distance from camera (close = faded, far = full)
* - Entity age (young = faded, old = full; ignored while charging)
* <p>
* Only applies to the owning player's client. Non-owners always get 1.0.
*
* @param entity the energy projectile entity
* @param x camera-relative X (from doRender)
* @param y camera-relative Y (from doRender)
* @param z camera-relative Z (from doRender)
* @return alpha multiplier between ProximityAlphaMin and 1.0
*/
protected float getProximityAlphaFactor(EntityEnergyAbility entity, double x, double y, double z) {
return getProximityAlphaFactor(entity, x, y, z, false);
}
/**
* Overload that allows forcing proximity-only fade (no age fade-out).
* Used for attached beams and lasers that stay connected to the owner.
*
* @param alwaysUseProximity if true, age factor is ignored (proximity fade never expires)
*/
protected float getProximityAlphaFactor(EntityEnergyAbility entity, double x, double y, double z, boolean alwaysUseProximity) {
float minAlpha = ConfigClient.ProximityAlphaMin;
if (minAlpha >= 1.0f) return 1.0f;
// Only apply to the owner's client
EntityPlayer player = Minecraft.getMinecraft().thePlayer;
if (player == null || entity.getOwnerEntityId() != player.getEntityId()) {
return 1.0f;
}
// Distance factor: ramp from minAlpha at 0 to 1.0 at maxDist
float maxDist = ConfigClient.ProximityAlphaDistance;
float dist = (float) Math.sqrt(x * x + y * y + z * z);
float distFactor = Math.min(1.0f, dist / maxDist);
// Age factor: ramp from 0 to 1.0 over ageTicks
// Charging, attached beams/lasers, and alwaysUseProximity skip age fade
float ageFactor;
if (entity.isCharging() || alwaysUseProximity) {
ageFactor = 0.0f; // Always apply full proximity fade
} else {
int ageTicks = ConfigClient.ProximityAlphaAgeTicks;
if (ageTicks <= 0) {
ageFactor = 1.0f; // Age fade disabled
} else {
ageFactor = Math.min(1.0f, (float) entity.ticksExisted / ageTicks);
}
}
// Combined: take the max of both factors (either being far OR being old restores alpha)
float combinedFactor = Math.max(distFactor, ageFactor);
// Lerp between minAlpha and 1.0
return minAlpha + (1.0f - minAlpha) * combinedFactor;
}
@Override
protected ResourceLocation getEntityTexture(Entity entity) {
return WHITE_TEXTURE;
}
}
@@ -0,0 +1,23 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergyBarrier;
/**
* Intermediate renderer base for energy barrier entities (Dome, Panel).
* Provides shared hit flash alpha computation.
*/
@SideOnly(Side.CLIENT)
public abstract class RenderEnergyBarrier extends RenderEnergy {
/**
* Compute the alpha boost from a hit flash effect.
* Flash value decays from 4 to 0, producing alpha from 0.3 to 0.
*/
protected float computeFlashAlpha(EntityEnergyBarrier barrier) {
byte flash = barrier.getHitFlash();
if (flash <= 0) return 0.0f;
return flash / 4.0f * 0.3f;
}
}
@@ -2,9 +2,9 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityBeam;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.Vec3;
import org.lwjgl.opengl.GL11;
@@ -15,26 +15,32 @@ import java.util.List;
/**
* Renders the AbilityBeam entity with a head, tail orb, and curving trail.
* The trail shows the path the head has traveled using laser-style rectangular segments.
*
* <p>
* IMPORTANT: Trail points are stored RELATIVE to the origin position.
* We render by translating to the origin first, then drawing all points relative to that.
*
* <p>
* Trail segments now share vertices at connection points to prevent gaps during curves.
*
* <p>
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityBeam extends RenderAbilityProjectile {
public class RenderEnergyBeam extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityAbilityBeam beam = (EntityAbilityBeam) entity;
setupRenderState();
// Proximity alpha fade for owner (attached beams always use proximity, never age out)
float proximityAlpha = getProximityAlphaFactor(beam, x, y, z, beam.isAttachedToOwner());
// Handle charging state (windup phase) - render only growing orb
if (beam.isCharging()) {
renderChargingOrb(beam, x, y, z, partialTicks);
renderChargingOrb(beam, x, y, z, partialTicks, proximityAlpha);
restoreRenderState();
return;
}
@@ -46,24 +52,25 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
return;
}
// Get interpolated head offset
// Get interpolated head offset (for head/trail rendering relative to origin)
double headOffsetX = beam.getInterpolatedHeadOffsetX(partialTicks);
double headOffsetY = beam.getInterpolatedHeadOffsetY(partialTicks);
double headOffsetZ = beam.getInterpolatedHeadOffsetZ(partialTicks);
// The render system passes x,y,z as the position to render the entity at
// Entity position = origin + headOffset (in world coords)
// So origin render position = x,y,z - headOffset
double renderOriginX = x - headOffsetX;
double renderOriginY = y - headOffsetY;
double renderOriginZ = z - headOffsetZ;
// Compute render origin directly from the world origin and camera position.
// We can't derive it from MC's x,y,z because syncPositionStateToCurrent() snaps
// lastTickPos = posX on every sync packet, killing MC's position interpolation.
// The headOffset interpolation then mismatches, causing the origin to wobble.
double renderOriginX = beam.getOriginX() - RenderManager.renderPosX;
double renderOriginY = beam.getOriginY() - RenderManager.renderPosY;
double renderOriginZ = beam.getOriginZ() - RenderManager.renderPosZ;
// Get beam properties
float beamWidth = beam.getBeamWidth();
float headSize = beam.getHeadSize();
// Get beam properties (lerp-smoothed for smooth size transitions)
float beamWidth = beam.getInterpolatedBeamWidth(partialTicks);
float headSize = beam.getInterpolatedHeadSize(partialTicks);
int innerColor = beam.getInnerColor();
int outerColor = beam.getOuterColor();
float outerAlpha = beam.getOuterColorAlpha();
float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
// Render everything relative to origin position
GL11.glPushMatrix();
@@ -72,21 +79,24 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Calculate head distance from origin (for overlap check)
double headDistFromOrigin = Math.sqrt(headOffsetX * headOffsetX + headOffsetY * headOffsetY + headOffsetZ * headOffsetZ);
// Render tail orb at origin (0,0,0) - only in anchored mode
// Don't render if head is too close to origin (would cause overlap/extra orb appearance)
if (beam.shouldRenderTailOrb() && headDistFromOrigin > headSize * 0.5) {
renderTailOrb(headSize * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha);
float innerAlpha = beam.getInnerAlpha() * proximityAlpha;
// Render trail segments first (with fading for non-anchored)
if (beam.hasFadingTrail()) {
renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha);
} else {
renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), innerAlpha);
}
// Render trail segments with smooth connections (with fading for non-anchored)
if (beam.hasFadingTrail()) {
renderFadingTrail(beam, trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth());
} else {
renderSmoothTrail(trail, beamWidth, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth());
// Render tail orb at origin (0,0,0) AFTER trail so it draws on top
// Don't render if head is too close to origin (would cause overlap/extra orb appearance)
// Use target headSize (not lerped) so the threshold isn't inflated by lerp lag
if (beam.shouldRenderTailOrb() && headDistFromOrigin > beam.getHeadSize() * 0.5) {
renderTailOrb(beam.getHeadSize() * 0.8f, innerColor, outerColor, beam.isOuterColorEnabled(), beam.getOuterColorWidth(), outerAlpha, innerAlpha);
}
// Render head at interpolated offset position
renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, partialTicks);
renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, innerAlpha, partialTicks);
GL11.glPopMatrix();
@@ -97,8 +107,8 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Render the charging orb during windup phase.
* Grows from 0 to headSize based on charge progress.
*/
private void renderChargingOrb(EntityAbilityBeam beam, double x, double y, double z, float partialTicks) {
float headSize = beam.getHeadSize();
private void renderChargingOrb(EntityAbilityBeam beam, double x, double y, double z, float partialTicks, float proximityAlpha) {
float headSize = beam.getInterpolatedHeadSize(partialTicks);
float chargeProgress = beam.getInterpolatedChargeProgress(partialTicks);
float size = headSize * chargeProgress;
@@ -117,7 +127,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render lightning during charging if enabled
if (beam.hasLightningEffect()) {
renderAttachedLightning(beam, scale);
renderAttachedLightning(beam, 0.6f * 0.5f, scale);
}
GL11.glPushMatrix();
@@ -129,7 +139,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render outer glow only if enabled
if (beam.isOuterColorEnabled()) {
float outerScale = innerScale + beam.getOuterColorWidth();
float outerAlpha = beam.getOuterColorAlpha();
float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
@@ -140,7 +150,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
renderCube(innerColor, 1.0f, 0.5f);
renderCube(innerColor, beam.getInnerAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -150,7 +160,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Render the tail orb at the origin (where the beam emanates from).
* This orb does not rotate - it's a stable anchor point.
*/
private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha) {
private void renderTailOrb(float size, int innerColor, int outerColor, boolean outerColorEnabled, float outerColorWidth, float outerAlpha, float innerAlpha) {
GL11.glPushMatrix();
// Already at origin (0,0,0)
@@ -172,7 +182,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render inner core (solid)
GL11.glPushMatrix();
GL11.glScalef(size * innerScale, size * innerScale, size * innerScale);
renderCube(innerColor, 1.0f, 0.5f);
renderCube(innerColor, innerAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -183,7 +193,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Uses averaged perpendicular vectors at connection points to prevent gaps.
*/
private void renderSmoothTrail(List<Vec3> trail, float width, int innerColor, int outerColor,
boolean outerColorEnabled, float outerColorWidth) {
boolean outerColorEnabled, float outerColorWidth, float innerAlpha) {
if (trail.size() < 2) return;
int trailSize = trail.size();
@@ -206,7 +216,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
}
// Render inner core trail
renderTrailTube(trail, perpFrames, innerWidth, innerColor, 0.9f, false);
renderTrailTube(trail, perpFrames, innerWidth, innerColor, innerAlpha, false);
}
/**
@@ -214,7 +224,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Older trail points fade out based on their age.
*/
private void renderFadingTrail(EntityAbilityBeam beam, List<Vec3> trail, float width, int innerColor, int outerColor,
boolean outerColorEnabled, float outerColorWidth) {
boolean outerColorEnabled, float outerColorWidth, float innerAlpha) {
if (trail.size() < 2) return;
List<Integer> ages = beam.getTrailPointAges();
@@ -236,14 +246,14 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
}
// Render inner core trail with fading
renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, 0.9f);
renderFadingTrailTube(trail, perpFrames, ages, fadeTime, innerWidth, innerColor, innerAlpha);
}
/**
* Render trail tube with age-based fading.
*/
private void renderFadingTrailTube(List<Vec3> trail, List<double[]> perpFrames, List<Integer> ages,
int fadeTime, float width, int color, float baseAlpha) {
int fadeTime, float width, int color, float baseAlpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
float halfWidth = width * 0.5f;
@@ -261,8 +271,8 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Calculate alpha based on age (older = more faded)
float age1 = i < ages.size() ? ages.get(i) : 0;
float age2 = (i + 1) < ages.size() ? ages.get(i + 1) : 0;
float fade1 = 1.0f - Math.min(1.0f, age1 / fadeTime);
float fade2 = 1.0f - Math.min(1.0f, age2 / fadeTime);
float fade1 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age1 / fadeTime)) : 0.0f;
float fade2 = fadeTime > 0 ? (1.0f - Math.min(1.0f, age2 / fadeTime)) : 0.0f;
float alpha1 = baseAlpha * fade1;
float alpha2 = baseAlpha * fade2;
@@ -393,13 +403,17 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
dy /= len;
dz /= len;
} else {
dx = 0; dy = 0; dz = 1;
dx = 0;
dy = 0;
dz = 1;
}
// Calculate perpendicular vectors using consistent up reference
double upX = 0, upY = 1, upZ = 0;
if (Math.abs(dy) > 0.9) {
upX = 1; upY = 0; upZ = 0;
upX = 1;
upY = 0;
upZ = 0;
}
// Cross product for horizontal perpendicular
@@ -418,8 +432,12 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
double vertY = dz * horzX - dx * horzZ;
double vertZ = dx * horzY - dy * horzX;
frame[0] = horzX; frame[1] = horzY; frame[2] = horzZ;
frame[3] = vertX; frame[4] = vertY; frame[5] = vertZ;
frame[0] = horzX;
frame[1] = horzY;
frame[2] = horzZ;
frame[3] = vertX;
frame[4] = vertY;
frame[5] = vertZ;
frames.add(frame);
}
@@ -430,7 +448,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Render the trail as a continuous tube using pre-computed perpendicular frames.
*/
private void renderTrailTube(List<Vec3> trail, List<double[]> perpFrames,
float width, int color, float baseAlpha, boolean fadeFromStart) {
float width, int color, float baseAlpha, boolean fadeFromStart) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
float halfWidth = width * 0.5f;
@@ -534,7 +552,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
* Coordinates are relative to origin.
*/
private void renderHead(EntityAbilityBeam beam, double x, double y, double z,
float size, int innerColor, int outerColor, float outerAlpha, float partialTicks) {
float size, int innerColor, int outerColor, float outerAlpha, float innerAlpha, float partialTicks) {
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
@@ -545,7 +563,7 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render lightning BEFORE rotation so it crackles in all directions (only on head)
if (beam.hasLightningEffect()) {
renderAttachedLightning(beam, scale);
renderAttachedLightning(beam, 0.6f * 0.5f, scale);
}
// Rotation
@@ -573,37 +591,10 @@ public class RenderAbilityBeam extends RenderAbilityProjectile {
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
renderCube(innerColor, 1.0f, 0.5f);
renderCube(innerColor, innerAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
}
/**
* Render fading lightning arcs attached to the beam head (in local space).
*/
private void renderAttachedLightning(EntityAbilityBeam beam, float headScale) {
AttachedLightningRenderer.LightningState state = getLightningState(beam);
float density = beam.getLightningDensity();
// Lightning radius extends outward from inner surface (innerScale = 0.6)
float innerRadius = 0.6f * headScale * 0.5f;
float radius = innerRadius + beam.getLightningRadius() * headScale;
int outerColor = beam.getOuterColor();
int innerColor = beam.getInnerColor();
int fadeTime = beam.getLightningFadeTime();
state.update(density, radius, outerColor, innerColor, fadeTime);
state.render();
}
/**
* Get or create the lightning state for an entity.
*/
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityBeam beam) {
if (beam.lightningState == null) {
beam.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) beam.lightningState;
}
}
@@ -2,22 +2,26 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityDisc;
import net.minecraft.entity.Entity;
import net.minecraft.util.Vec3;
import noppes.npcs.util.MathUtil;
import org.lwjgl.opengl.GL11;
/**
* Renders the AbilityDisc entity as a flat spinning square.
* Rotates only on Y axis (flat spin like a saw blade).
*
* <p>
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityDisc extends RenderAbilityProjectile {
public class RenderEnergyDisc extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityAbilityDisc disc = (EntityAbilityDisc) entity;
setupRenderState();
@@ -27,8 +31,8 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
// Get interpolated values
float size = disc.getInterpolatedSize(partialTicks);
float radius = disc.getDiscRadius() * size;
float thickness = disc.getDiscThickness() * size;
float radius = disc.getInterpolatedDiscRadius(partialTicks) * size;
float thickness = disc.getInterpolatedDiscThickness(partialTicks) * size;
// Subtle pulsing effect
float pulseTime = entity.ticksExisted + partialTicks;
@@ -37,7 +41,7 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
// Render lightning BEFORE rotation so it crackles in all directions
if (disc.hasLightningEffect()) {
renderAttachedLightning(disc, radius * scale);
renderAttachedLightning(disc, 0.6f * 0.5f, radius * scale);
}
GL11.glPushMatrix();
@@ -52,23 +56,41 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f);
}
double motionX = entity.motionX;
double motionY = entity.motionY;
double motionZ = entity.motionZ;
double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ;
// Only apply motion-based facing when speed is meaningful.
// Near-zero motion makes atan2 unstable, producing jittery angles.
if (speedSq > 0.0001) {
Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
float motionYaw = MathUtil.getYaw(motionVec);
float motionPitch = MathUtil.getPitch(motionVec);
GL11.glRotatef(motionYaw, 0, 1, 0);
GL11.glRotatef(motionPitch, 1, 0, 0);
}
// Apply Y-axis rotation for spin
GL11.glRotatef(disc.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f);
// Inner scale defines the core size
float innerScale = 0.6f;
// Proximity alpha fade for owner
float proximityAlpha = getProximityAlphaFactor(disc, x, y, z);
// Render outer square (translucent) - only if enabled
// outerColorWidth is an additive offset from inner size
if (disc.isOuterColorEnabled()) {
float outerScale = innerScale + disc.getOuterColorWidth();
GL11.glDepthMask(false);
renderFlatSquare(disc.getOuterColor(), disc.getOuterColorAlpha(), radius * outerScale, thickness);
renderFlatSquare(disc.getOuterColor(), disc.getOuterColorAlpha() * proximityAlpha, radius * outerScale, thickness);
GL11.glDepthMask(true);
}
// Render inner square (solid)
renderFlatSquare(disc.getInnerColor(), 1.0f, radius * innerScale, thickness * 1.2f);
renderFlatSquare(disc.getInnerColor(), disc.getInnerAlpha() * proximityAlpha, radius * innerScale, thickness * 1.2f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -76,34 +98,6 @@ public class RenderAbilityDisc extends RenderAbilityProjectile {
restoreRenderState();
}
/**
* Render fading lightning arcs attached to the disc (in local space).
*/
private void renderAttachedLightning(EntityAbilityDisc disc, float discSize) {
AttachedLightningRenderer.LightningState state = getLightningState(disc);
float density = disc.getLightningDensity();
// Lightning radius extends outward from inner surface (innerScale = 0.6)
float innerRadius = 0.6f * discSize * 0.5f;
float radius = innerRadius + disc.getLightningRadius() * discSize;
int outerColor = disc.getOuterColor();
int innerColor = disc.getInnerColor();
int fadeTime = disc.getLightningFadeTime();
state.update(density, radius, outerColor, innerColor, fadeTime);
state.render();
}
/**
* Get or create the lightning state for an entity.
*/
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityDisc disc) {
if (disc.lightningState == null) {
disc.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) disc.lightningState;
}
/**
* Render a flat square (thin cube) centered at origin.
* The square lies flat on the XZ plane with thin Y height.
@@ -0,0 +1,111 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergyDome;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
/**
* Renders the Dome entity as a translucent sphere.
* Inner layer solid, outer layer translucent glow.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergyDome extends RenderEnergyBarrier {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityEnergyDome dome = (EntityEnergyDome) entity;
float radius = dome.getDomeRadius();
float healthPercent = dome.getHealthPercent();
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
// Lightning BEFORE any rotation (uniform spread)
if (dome.hasLightningEffect()) {
renderAttachedLightning(dome, 0.95f, radius);
}
// Hit flash effect
float flashAlpha = computeFlashAlpha(dome);
float innerScale = 1.0f;
// Render outer dome (translucent glow)
if (dome.isOuterColorEnabled()) {
float outerScale = 1.0f + dome.getOuterColorWidth() * 0.1f;
float outerAlpha = dome.getOuterColorAlpha() * healthPercent;
GL11.glDepthMask(false);
renderSphere(dome.getOuterColor(), outerAlpha + (dome.getOuterColorAlpha() > 0 ? flashAlpha : 0), radius * outerScale, 8);
}
GL11.glDepthMask(true);
// Render inner dome (depth write enabled so inner sphere properly occludes)
renderSphere(dome.getInnerColor(), dome.getInnerAlpha() * healthPercent, radius * innerScale, 8);
GL11.glPopMatrix();
restoreRenderState();
}
/**
* Render a sphere made of quad panels.
* Uses latitude/longitude segments to form a full sphere.
*/
private void renderSphere(int color, float alpha, float radius, int segments) {
float[] rgb = extractRGB(color);
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.setColorRGBA_F(rgb[0], rgb[1], rgb[2], alpha);
for (int lat = 0; lat < segments; lat++) {
float theta1 = (float) (Math.PI * lat / segments - Math.PI * 0.5);
float theta2 = (float) (Math.PI * (lat + 1) / segments - Math.PI * 0.5);
float y1 = (float) Math.sin(theta1) * radius;
float y2 = (float) Math.sin(theta2) * radius;
float r1 = (float) Math.cos(theta1) * radius;
float r2 = (float) Math.cos(theta2) * radius;
for (int lon = 0; lon < segments; lon++) {
float phi1 = (float) (2 * Math.PI * lon / segments);
float phi2 = (float) (2 * Math.PI * (lon + 1) / segments);
float x1 = (float) Math.cos(phi1) * r1;
float z1 = (float) Math.sin(phi1) * r1;
float x2 = (float) Math.cos(phi2) * r1;
float z2 = (float) Math.sin(phi2) * r1;
float x3 = (float) Math.cos(phi2) * r2;
float z3 = (float) Math.sin(phi2) * r2;
float x4 = (float) Math.cos(phi1) * r2;
float z4 = (float) Math.sin(phi1) * r2;
float nx = (x1 + x2 + x3 + x4) * 0.25f;
float ny = (y1 + y1 + y2 + y2) * 0.25f;
float nz = (z1 + z2 + z3 + z4) * 0.25f;
float nLen = (float) Math.sqrt(nx * nx + ny * ny + nz * nz);
if (nLen > 0) {
nx /= nLen;
ny /= nLen;
nz /= nLen;
}
tess.setNormal(nx, ny, nz);
tess.addVertex(x1, y1, z1);
tess.addVertex(x2, y1, z2);
tess.addVertex(x3, y2, z3);
tess.addVertex(x4, y2, z4);
}
}
tess.draw();
}
}
@@ -0,0 +1,211 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergyExplosion;
import net.minecraft.entity.Entity;
import noppes.npcs.config.ConfigClient;
import org.lwjgl.opengl.GL11;
/**
* Voxel-style renderer for {@link EntityEnergyExplosion}.
* Draws expanding cubic shells with a short fade-out.
* Uses batched cube rendering for performance — all cubes of each layer
* are drawn in a single tessellator pass instead of per-cube draw calls.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergyExplosion extends RenderEnergy {
private static final float MAX_OUTER_ALPHA = 0.85f;
private static final float MAX_INNER_ALPHA = 1.0f;
private static final float MAX_SMOKE_CUBE_ALPHA = 0.55f;
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) return;
if (!(entity instanceof EntityEnergyExplosion)) return;
if (ConfigClient.LowResExplosion) return;
EntityEnergyExplosion explosion = (EntityEnergyExplosion) entity;
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
float radius = explosion.getInterpolatedRadius(partialTicks);
float life = explosion.getLifeProgress(partialTicks);
if (radius > 0.01f && life < 1.0f) {
renderVoxelBurst(explosion, radius, life);
if (explosion.hasLightningEffect()) {
renderAttachedLightning(explosion, 0.55f, Math.max(0.7f, radius * 0.45f));
}
}
GL11.glPopMatrix();
restoreRenderState();
}
private void renderVoxelBurst(EntityEnergyExplosion explosion, float radius, float life) {
int outerColor = explosion.getOuterColor();
int innerColor = explosion.getInnerColor();
boolean hasOuter = explosion.isOuterColorEnabled();
float fade = 1.0f - life;
float outerAlpha = Math.min(MAX_OUTER_ALPHA, (0.25f + fade * 0.75f) * explosion.getOuterColorAlpha());
float innerAlpha = Math.min(MAX_INNER_ALPHA, (0.30f + fade * 0.80f) * explosion.getInnerAlpha());
int steps = Math.max(2, Math.min(6, (int) Math.ceil(radius * 0.65f) + 1));
float cell = radius / steps;
float cubeHalf = Math.max(0.04f, cell * 0.22f * (0.90f - life * 0.25f));
float outerScale = hasOuter ? 1.0f + explosion.getOuterColorWidth() * 0.35f : 1.0f;
long seed = explosion.getRenderSeed();
// Pre-extract RGB for batched rendering
float outerR = ((outerColor >> 16) & 0xFF) / 255.0f;
float outerG = ((outerColor >> 8) & 0xFF) / 255.0f;
float outerB = (outerColor & 0xFF) / 255.0f;
float innerR = ((innerColor >> 16) & 0xFF) / 255.0f;
float innerG = ((innerColor >> 8) & 0xFF) / 255.0f;
float innerB = (innerColor & 0xFF) / 255.0f;
GL11.glDepthMask(false);
// Smoke layer — single batched pass
renderSmokeVoxelShell(radius, life, seed);
// Outer color layer — single batched pass
if (hasOuter) {
float outerHalf = cubeHalf * outerScale;
float oa = outerAlpha * fade;
beginCubeBatch();
for (int ix = -steps; ix <= steps; ix++) {
for (int iy = -steps; iy <= steps; iy++) {
for (int iz = -steps; iz <= steps; iz++) {
int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz)));
if (edge != steps) continue;
if (!shouldRenderVoxel(ix, iy, iz, steps, seed, life)) continue;
float px = ix * cell + jitter(ix, iy, iz, seed, 1) * cell * 0.18f;
float py = iy * cell + jitter(ix, iy, iz, seed, 2) * cell * 0.18f;
float pz = iz * cell + jitter(ix, iy, iz, seed, 3) * cell * 0.18f;
addBatchedCube(px, py, pz, outerHalf, outerR, outerG, outerB, oa);
}
}
}
endCubeBatch();
}
// Inner color layer — single batched pass
{
float innerHalf = cubeHalf * 0.9f;
float ia = innerAlpha * fade;
beginCubeBatch();
for (int ix = -steps; ix <= steps; ix++) {
for (int iy = -steps; iy <= steps; iy++) {
for (int iz = -steps; iz <= steps; iz++) {
int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz)));
if (edge != steps) continue;
if (!shouldRenderVoxel(ix, iy, iz, steps, seed, life)) continue;
float px = ix * cell + jitter(ix, iy, iz, seed, 1) * cell * 0.18f;
float py = iy * cell + jitter(ix, iy, iz, seed, 2) * cell * 0.18f;
float pz = iz * cell + jitter(ix, iy, iz, seed, 3) * cell * 0.18f;
addBatchedCube(px, py, pz, innerHalf, innerR, innerG, innerB, ia);
}
}
}
endCubeBatch();
}
renderCoreFlash(innerColor, innerAlpha, radius, cubeHalf, life);
GL11.glDepthMask(true);
}
/**
* Adds large translucent white/gray cubes to fake a smoky volumetric expansion.
* All smoke cubes are batched into a single draw call.
*/
private void renderSmokeVoxelShell(float radius, float life, long seed) {
int smokeSteps = Math.max(2, Math.min(5, (int) Math.ceil(radius * 0.5f) + 1));
float smokeCell = radius / smokeSteps * 1.2f;
float smokeJitter = smokeCell * 0.28f;
float smokeCubeHalf = Math.max(0.07f, smokeCell * 0.24f * (0.95f - life * 0.25f));
float smokeAlpha = Math.min(MAX_SMOKE_CUBE_ALPHA, (0.15f + (1.0f - life) * 0.55f));
// White = 1,1,1 Gray (0xDCDCDC) = 0.863,0.863,0.863
beginCubeBatch();
for (int ix = -smokeSteps; ix <= smokeSteps; ix++) {
for (int iy = -smokeSteps; iy <= smokeSteps; iy++) {
for (int iz = -smokeSteps; iz <= smokeSteps; iz++) {
int edge = Math.max(Math.abs(ix), Math.max(Math.abs(iy), Math.abs(iz)));
if (edge < smokeSteps - 1) continue;
int h = hash(ix * 5, iy * 7, iz * 11, seed ^ 0x4f1bbcdcL);
if ((h & 3) != 0) continue;
if (life > 0.72f && ((h >>> 5) & 7) > 2) continue;
float px = ix * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 1) * smokeJitter;
float py = iy * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 2) * smokeJitter;
float pz = iz * smokeCell + jitter(ix, iy, iz, seed ^ 0x2299aa11L, 3) * smokeJitter;
boolean isWhite = ((h >>> 9) & 1) == 0;
float gray = isWhite ? 1.0f : 0.863f;
float alpha = smokeAlpha * (0.78f + (((h >>> 10) & 15) / 15.0f) * 0.22f);
addBatchedCube(px, py, pz, smokeCubeHalf, gray, gray, gray, alpha);
}
}
}
endCubeBatch();
}
/**
* White-hot core flash pass for the initial frames.
*/
private void renderCoreFlash(int innerColor, float innerAlpha, float radius, float cubeHalf, float life) {
float flash = saturate((0.60f - life) / 0.60f);
if (flash <= 0.0f) return;
float coreHalf = Math.max(cubeHalf, radius * 0.07f) * (1.0f + flash * 0.55f);
float whiteAlpha = Math.min(1.0f, 0.25f + flash * 0.95f);
float innerFlashAlpha = Math.min(1.0f, innerAlpha * (0.45f + flash * 0.95f));
renderCube(0xFFFFFF, whiteAlpha, coreHalf * 1.45f);
renderCube(innerColor, innerFlashAlpha, coreHalf * 0.82f);
}
private float saturate(float value) {
if (value < 0.0f) return 0.0f;
if (value > 1.0f) return 1.0f;
return value;
}
private boolean shouldRenderVoxel(int ix, int iy, int iz, int steps, long seed, float life) {
int h = hash(ix, iy, iz, seed);
int keepMask = steps >= 5 ? 3 : 1;
if ((h & keepMask) != 0) return false;
if (life > 0.55f) {
int decay = (h >>> 3) & 7;
if (decay > 2) return false;
}
return true;
}
private float jitter(int ix, int iy, int iz, long seed, int channel) {
int h = hash(ix + channel * 17, iy - channel * 31, iz + channel * 47, seed);
return (((h >>> 8) & 1023) / 1023.0f) - 0.5f;
}
private int hash(int x, int y, int z, long seed) {
long h = seed;
h ^= (long) x * 73428767L;
h ^= (long) y * 912931L;
h ^= (long) z * 19349663L;
h ^= (h >>> 33);
h *= 0xff51afd7ed558ccdL;
h ^= (h >>> 33);
return (int) h;
}
}
@@ -3,19 +3,23 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityBeam;
import kamkeel.npcs.entity.EntityAbilityLaser;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
import java.util.HashMap;
import java.util.Map;
/**
* Renders the AbilityLaser entity as a rectangular beam with clear inner/outer colors.
*
* <p>
* Design inspired by LouisXIV's energy rendering system.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityLaser extends RenderAbilityProjectile {
public class RenderEnergyLaser extends RenderEnergy {
private final Map<Integer, AttachedLightningRenderer.LightningState> tipLightningStates = new HashMap<>();
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
@@ -23,21 +27,24 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
setupRenderState();
// Proximity alpha fade for owner (lasers are always attached, never age out)
float proximityAlpha = getProximityAlphaFactor(laser, x, y, z, true);
if (laser.isCharging()) {
renderChargingOrb(laser, x, y, z, partialTicks);
renderChargingOrb(laser, x, y, z, partialTicks, proximityAlpha);
restoreRenderState();
return;
}
// Get laser parameters
double startX = laser.getStartX();
double startY = laser.getStartY();
double startZ = laser.getStartZ();
double endX = laser.getEndX();
double endY = laser.getEndY();
double endZ = laser.getEndZ();
float width = laser.getLaserWidth();
float alpha = laser.getLingerAlpha();
// Get interpolated laser positions for smooth rendering between ticks
double startX = laser.getInterpolatedStartX(partialTicks);
double startY = laser.getInterpolatedStartY(partialTicks);
double startZ = laser.getInterpolatedStartZ(partialTicks);
double endX = laser.getInterpolatedEndX(partialTicks);
double endY = laser.getInterpolatedEndY(partialTicks);
double endZ = laser.getInterpolatedEndZ(partialTicks);
float width = laser.getInterpolatedLaserWidth(partialTicks);
float alpha = 1.0f;
// Calculate render offset (entity position is used as reference)
double offsetX = x - laser.posX;
@@ -70,7 +77,9 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Calculate perpendicular vectors (one horizontal, one vertical relative to beam)
double upX = 0, upY = 1, upZ = 0;
if (Math.abs(dy) > 0.9) {
upX = 1; upY = 0; upZ = 0;
upX = 1;
upY = 0;
upZ = 0;
}
// Cross product for horizontal perpendicular
@@ -89,6 +98,25 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
double vertY = dz * horzX - dx * horzZ;
double vertZ = dx * horzY - dy * horzX;
// Rotate perpendicular vectors around beam axis (Rodrigues' rotation)
float rotationSpeed = laser.getRotationSpeed();
if (rotationSpeed != 0.0f) {
double angle = (laser.ticksExisted + partialTicks) * rotationSpeed * Math.PI / 180.0;
double cosA = Math.cos(angle);
double sinA = Math.sin(angle);
double rHorzX = horzX * cosA + vertX * sinA;
double rHorzY = horzY * cosA + vertY * sinA;
double rHorzZ = horzZ * cosA + vertZ * sinA;
double rVertX = -horzX * sinA + vertX * cosA;
double rVertY = -horzY * sinA + vertY * cosA;
double rVertZ = -horzZ * sinA + vertZ * cosA;
horzX = rHorzX; horzY = rHorzY; horzZ = rHorzZ;
vertX = rVertX; vertY = rVertY; vertZ = rVertZ;
}
// Inner scale defines the core width
float innerScale = 0.6f;
float innerWidth = width * innerScale;
@@ -99,36 +127,36 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
float outerWidth = innerWidth + laser.getOuterColorWidth() * width;
GL11.glDepthMask(false);
renderBeamRectangle(renderStartX, renderStartY, renderStartZ,
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
outerWidth, laser.getOuterColor(), alpha * 0.4f);
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
outerWidth, laser.getOuterColor(), alpha * 0.4f * proximityAlpha);
// Render middle layer (halfway between inner and outer)
float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f;
renderBeamRectangle(renderStartX, renderStartY, renderStartZ,
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
midWidth, laser.getOuterColor(), alpha * 0.7f);
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
midWidth, laser.getOuterColor(), alpha * 0.7f * proximityAlpha);
GL11.glDepthMask(true);
}
// Render inner core (solid)
renderBeamRectangle(renderStartX, renderStartY, renderStartZ,
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
innerWidth, laser.getInnerColor(), alpha);
renderEndX, renderEndY, renderEndZ,
horzX, horzY, horzZ, vertX, vertY, vertZ,
innerWidth, laser.getInnerColor(), alpha * laser.getInnerAlpha() * proximityAlpha);
// Render lightning along the laser beam
if (laser.hasLightningEffect() && laser.getCurrentLength() > 0.1f) {
renderLaserLightning(laser, renderStartX, renderStartY, renderStartZ,
renderEndX, renderEndY, renderEndZ, width);
renderEndX, renderEndY, renderEndZ, width);
}
restoreRenderState();
}
private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks) {
float headSize = laser.getLaserWidth() * 1.5f;
private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks, float proximityAlpha) {
float headSize = laser.getInterpolatedLaserWidth(partialTicks) * 0.5f;
float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks);
float size = headSize * chargeProgress;
@@ -147,7 +175,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Render lightning during charging if enabled
if (laser.hasLightningEffect()) {
renderAttachedLightning(laser, scale);
renderAttachedLightning(laser, 0.6f * 0.5f, scale);
}
GL11.glPushMatrix();
@@ -159,7 +187,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Render outer glow only if enabled
if (laser.isOuterColorEnabled()) {
float outerScale = innerScale + laser.getOuterColorWidth();
float outerAlpha = laser.getOuterColorAlpha();
float outerAlpha = laser.getOuterColorAlpha() * proximityAlpha;
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
@@ -170,7 +198,7 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
// Render inner core
GL11.glScalef(innerScale, innerScale, innerScale);
renderCube(innerColor, 1.0f, 0.5f);
renderCube(innerColor, laser.getInnerAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -180,8 +208,8 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
* Render lightning effects along the laser beam at multiple points.
*/
private void renderLaserLightning(EntityAbilityLaser laser,
double startX, double startY, double startZ,
double endX, double endY, double endZ, float width) {
double startX, double startY, double startZ,
double endX, double endY, double endZ, float width) {
AttachedLightningRenderer.LightningState state = getLightningState(laser);
float density = laser.getLightningDensity();
@@ -215,50 +243,28 @@ public class RenderAbilityLaser extends RenderAbilityProjectile {
}
private void renderAttachedLightning(EntityAbilityLaser laser, float headScale) {
AttachedLightningRenderer.LightningState state = getLightningState(laser);
float density = laser.getLightningDensity();
// Lightning radius extends outward from inner surface (innerScale = 0.6)
float innerRadius = 0.6f * headScale * 0.5f;
float radius = innerRadius + laser.getLightningRadius() * headScale;
int outerColor = laser.getOuterColor();
int innerColor = laser.getInnerColor();
int fadeTime = laser.getLightningFadeTime();
state.update(density, radius, outerColor, innerColor, fadeTime);
state.render();
}
/**
* Get or create the main lightning state for the laser.
*/
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityLaser laser) {
if (laser.lightningState == null) {
laser.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) laser.lightningState;
}
/**
* Get or create the tip lightning state for the laser.
* Stored as a secondary object in lightningState2.
* Persisted per entity ID so arcs accumulate and fade properly across frames.
*/
private AttachedLightningRenderer.LightningState getTipLightningState(EntityAbilityLaser laser) {
// Use a simple approach - store in a transient field
// Since lightningState is already used, we'll create a new state each time
// This works because we're updating and rendering immediately
return new AttachedLightningRenderer.LightningState();
int id = laser.getEntityId();
AttachedLightningRenderer.LightningState state = tipLightningStates.get(id);
if (state == null) {
state = new AttachedLightningRenderer.LightningState();
tipLightningStates.put(id, state);
}
return state;
}
/**
* Render a beam as a 3D rectangular prism (box along a line).
*/
private void renderBeamRectangle(double x1, double y1, double z1,
double x2, double y2, double z2,
double horzX, double horzY, double horzZ,
double vertX, double vertY, double vertZ,
float width, int color, float alpha) {
double x2, double y2, double z2,
double horzX, double horzY, double horzZ,
double vertX, double vertY, double vertZ,
float width, int color, float alpha) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
@@ -2,9 +2,10 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityOrb;
import net.minecraft.entity.Entity;
import net.minecraft.util.Vec3;
import noppes.npcs.util.MathUtil;
import org.lwjgl.opengl.GL11;
/**
@@ -12,7 +13,7 @@ import org.lwjgl.opengl.GL11;
* Minecraft-style blocky appearance using Tessellator.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilityOrb extends RenderAbilityProjectile {
public class RenderEnergyOrb extends RenderEnergy {
private static final int LIGHTNING_FADE_TICKS = 6;
@@ -20,6 +21,10 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
EntityAbilityOrb orb = (EntityAbilityOrb) entity;
if (shouldSkipInitialActiveRender(entity)) {
return;
}
setupRenderState();
GL11.glPushMatrix();
@@ -35,7 +40,22 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
// Render lightning BEFORE rotation so it crackles in all directions
if (orb.hasLightningEffect()) {
renderAttachedLightning(orb, scale);
renderAttachedLightning(orb, 0.6f * 0.5f, scale);
}
double motionX = entity.motionX;
double motionY = entity.motionY;
double motionZ = entity.motionZ;
double speedSq = motionX * motionX + motionY * motionY + motionZ * motionZ;
// Only apply motion-based facing when speed is meaningful.
// Near-zero motion makes atan2 unstable, producing jittery angles.
if (speedSq > 0.0001) {
Vec3 motionVec = Vec3.createVectorHelper(motionX, motionY, motionZ);
float motionYaw = MathUtil.getYaw(motionVec);
float motionPitch = MathUtil.getPitch(motionVec);
GL11.glRotatef(motionYaw, 0, 1, 0);
GL11.glRotatef(motionPitch, 1, 0, 0);
}
// Use entity's interpolated rotation for smooth spinning
@@ -49,6 +69,9 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
// Inner scale defines the core size
float innerScale = 0.6f;
// Proximity alpha fade for owner
float proximityAlpha = getProximityAlphaFactor(orb, x, y, z);
// Render outer cube (translucent) - only if enabled
// outerColorWidth is an additive offset from inner size
if (orb.isOuterColorEnabled()) {
@@ -56,14 +79,14 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
GL11.glDepthMask(false);
GL11.glPushMatrix();
GL11.glScalef(outerScale, outerScale, outerScale);
renderCube(orb.getOuterColor(), orb.getOuterColorAlpha(), 0.5f);
renderCube(orb.getOuterColor(), orb.getOuterColorAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glDepthMask(true);
}
// Render inner cube (solid)
GL11.glScalef(innerScale, innerScale, innerScale);
renderCube(orb.getInnerColor(), 1.0f, 0.5f);
renderCube(orb.getInnerColor(), orb.getInnerAlpha() * proximityAlpha, 0.5f);
GL11.glPopMatrix();
GL11.glPopMatrix();
@@ -71,36 +94,4 @@ public class RenderAbilityOrb extends RenderAbilityProjectile {
restoreRenderState();
}
/**
* Render fading lightning arcs attached to the orb (in local space).
* Arcs persist for a few ticks and fade out, while staying attached to the orb.
*/
private void renderAttachedLightning(EntityAbilityOrb orb, float orbScale) {
// Get or create the lightning state for this entity
AttachedLightningRenderer.LightningState state = getLightningState(orb);
float density = orb.getLightningDensity();
// Lightning radius extends outward from inner surface (innerScale = 0.6)
float innerRadius = 0.6f * orbScale * 0.5f; // Half size of inner cube
float radius = innerRadius + orb.getLightningRadius() * orbScale;
int outerColor = orb.getOuterColor();
int innerColor = orb.getInnerColor();
int fadeTime = orb.getLightningFadeTime();
// Update: age existing arcs, spawn new ones based on density
state.update(density, radius, outerColor, innerColor, fadeTime);
// Render all active arcs in local space (they move with the orb)
state.render();
}
/**
* Get or create the lightning state for an entity.
*/
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityOrb orb) {
if (orb.lightningState == null) {
orb.lightningState = new AttachedLightningRenderer.LightningState();
}
return (AttachedLightningRenderer.LightningState) orb.lightningState;
}
}
@@ -0,0 +1,143 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergyPanel;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
/**
* Renders the Energy Panel entity as a flat translucent rectangle.
* Used by both Energy Wall and Energy Shield abilities.
* Voxel-blocky style with inner/outer layers.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergyPanel extends RenderEnergyBarrier {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityEnergyPanel panel = (EntityEnergyPanel) entity;
float width = panel.getPanelData().panelWidth;
float height = panel.getPanelData().panelHeight;
float healthPercent = panel.getHealthPercent();
// Interpolate panel yaw for smooth rotation between ticks
float prevYaw = panel.getPrevPanelYaw();
float currentYaw = panel.getPanelYaw();
float yawDelta = currentYaw - prevYaw;
// Wrap angle delta to -180..180 for shortest rotation path
while (yawDelta > 180.0f) yawDelta -= 360.0f;
while (yawDelta < -180.0f) yawDelta += 360.0f;
float renderYaw = prevYaw + yawDelta * partialTicks;
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
// Lightning BEFORE rotation for uniform spread (like Orb pattern)
if (panel.hasLightningEffect()) {
renderAttachedLightning(panel, 0.9f, Math.max(width, height) * 0.5f);
}
// Rotate panel to face the correct direction (interpolated)
GL11.glRotatef(-renderYaw, 0.0f, 1.0f, 0.0f);
// Hit flash
float flashAlpha = computeFlashAlpha(panel);
// Subtle pulsing
float pulseTime = entity.ticksExisted + partialTicks;
float pulse = (float) Math.sin(pulseTime * 0.08f) * 0.02f;
float scale = 1.0f + pulse;
GL11.glPushMatrix();
GL11.glScalef(scale, scale, scale);
float innerScale = 1.0f;
float panelThickness = 0.1f;
// Render outer panel (translucent glow)
if (panel.isOuterColorEnabled()) {
float outerScale = 1.0f + panel.getOuterColorWidth() * 0.15f;
float outerAlpha = panel.getOuterColorAlpha() * healthPercent;
GL11.glDepthMask(false);
renderPanel(panel.getOuterColor(), outerAlpha + (panel.getOuterColorAlpha() > 0 ? flashAlpha : 0),
width * 0.5f * outerScale, height * 0.5f * outerScale, panelThickness * 1.5f);
GL11.glDepthMask(true);
}
// Render inner panel (uses configurable innerAlpha for semi-transparency)
renderPanel(panel.getInnerColor(), panel.getInnerAlpha(),
width * 0.5f * innerScale, height * 0.5f * innerScale, panelThickness);
GL11.glPopMatrix();
GL11.glPopMatrix();
restoreRenderState();
}
/**
* Render a flat panel (thin box) centered at origin.
* Panel faces along the Z axis (width on X, height on Y).
* All 6 faces batched into a single draw call.
*/
private void renderPanel(int color, float alpha, float halfWidth, float halfHeight, float halfThickness) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
tess.setColorRGBA_F(r, g, b, alpha);
// Front face (z+)
tess.setNormal(0, 0, 1);
tess.addVertex(-halfWidth, -halfHeight, halfThickness);
tess.addVertex(halfWidth, -halfHeight, halfThickness);
tess.addVertex(halfWidth, halfHeight, halfThickness);
tess.addVertex(-halfWidth, halfHeight, halfThickness);
// Back face (z-)
tess.setNormal(0, 0, -1);
tess.addVertex(halfWidth, -halfHeight, -halfThickness);
tess.addVertex(-halfWidth, -halfHeight, -halfThickness);
tess.addVertex(-halfWidth, halfHeight, -halfThickness);
tess.addVertex(halfWidth, halfHeight, -halfThickness);
// Top edge (y+)
tess.setNormal(0, 1, 0);
tess.addVertex(-halfWidth, halfHeight, halfThickness);
tess.addVertex(halfWidth, halfHeight, halfThickness);
tess.addVertex(halfWidth, halfHeight, -halfThickness);
tess.addVertex(-halfWidth, halfHeight, -halfThickness);
// Bottom edge (y-)
tess.setNormal(0, -1, 0);
tess.addVertex(-halfWidth, -halfHeight, -halfThickness);
tess.addVertex(halfWidth, -halfHeight, -halfThickness);
tess.addVertex(halfWidth, -halfHeight, halfThickness);
tess.addVertex(-halfWidth, -halfHeight, halfThickness);
// Right edge (x+)
tess.setNormal(1, 0, 0);
tess.addVertex(halfWidth, -halfHeight, halfThickness);
tess.addVertex(halfWidth, -halfHeight, -halfThickness);
tess.addVertex(halfWidth, halfHeight, -halfThickness);
tess.addVertex(halfWidth, halfHeight, halfThickness);
// Left edge (x-)
tess.setNormal(-1, 0, 0);
tess.addVertex(-halfWidth, -halfHeight, -halfThickness);
tess.addVertex(-halfWidth, -halfHeight, halfThickness);
tess.addVertex(-halfWidth, halfHeight, halfThickness);
tess.addVertex(-halfWidth, halfHeight, -halfThickness);
tess.draw();
}
}
@@ -0,0 +1,131 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityEnergySlicer;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.Entity;
import org.lwjgl.opengl.GL11;
/**
* Renders the Energy Slicer entity as a thin wide blade.
* Oriented perpendicular to travel direction.
* Inner solid core with outer translucent glow.
*/
@SideOnly(Side.CLIENT)
public class RenderEnergySlicer extends RenderEnergy {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
if (shouldSkipInitialActiveRender(entity)) {
return;
}
EntityEnergySlicer slicer = (EntityEnergySlicer) entity;
float width = slicer.getSliceWidth();
float thickness = slicer.getSliceThickness();
// During charging, width/thickness grow from 0.01 to target via updateCharging().
// Use current dimensions directly - no separate sizeRatio needed.
if (width <= 0.01f) return;
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
// Lightning BEFORE rotation for uniform spread (like Orb pattern)
if (slicer.hasLightningEffect()) {
renderAttachedLightning(slicer, 0.7f, width * 0.5f);
}
// Orient perpendicular to travel direction
float travelYaw = slicer.getTravelYaw();
float travelPitch = slicer.getTravelPitch();
GL11.glRotatef(travelYaw, 0.0f, 1.0f, 0.0f);
GL11.glRotatef(travelPitch, 1.0f, 0.0f, 0.0f);
float innerScale = 0.7f;
// Proximity alpha fade for owner
float proximityAlpha = getProximityAlphaFactor(slicer, x, y, z);
// Render outer blade (translucent glow)
if (slicer.isOuterColorEnabled()) {
float outerScale = 1.0f + slicer.getOuterColorWidth() * 0.2f;
GL11.glDepthMask(false);
renderBlade(slicer.getOuterColor(), slicer.getOuterColorAlpha() * proximityAlpha,
width * 0.5f * outerScale, thickness * 2.0f, 0.05f);
GL11.glDepthMask(true);
}
// Render inner blade (solid core)
renderBlade(slicer.getInnerColor(), slicer.getInnerAlpha() * proximityAlpha,
width * 0.5f * innerScale, thickness, 0.03f);
GL11.glPopMatrix();
restoreRenderState();
}
/**
* Render a thin wide blade shape.
* The blade extends along X (width), thin on Y (thickness), and very thin on Z (depth).
* All 6 faces batched into a single draw call.
*/
private void renderBlade(int color, float alpha, float halfWidth, float halfHeight, float halfDepth) {
float[] rgb = extractRGB(color);
float r = rgb[0], g = rgb[1], b = rgb[2];
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
// Front face (z+)
tess.setColorRGBA_F(r, g, b, alpha);
tess.setNormal(0, 0, 1);
tess.addVertex(-halfWidth, -halfHeight, halfDepth);
tess.addVertex(halfWidth, -halfHeight, halfDepth);
tess.addVertex(halfWidth, halfHeight, halfDepth);
tess.addVertex(-halfWidth, halfHeight, halfDepth);
// Back face (z-)
tess.setNormal(0, 0, -1);
tess.addVertex(halfWidth, -halfHeight, -halfDepth);
tess.addVertex(-halfWidth, -halfHeight, -halfDepth);
tess.addVertex(-halfWidth, halfHeight, -halfDepth);
tess.addVertex(halfWidth, halfHeight, -halfDepth);
// Top edge (y+)
tess.setColorRGBA_F(r, g, b, alpha * 0.8f);
tess.setNormal(0, 1, 0);
tess.addVertex(-halfWidth, halfHeight, halfDepth);
tess.addVertex(halfWidth, halfHeight, halfDepth);
tess.addVertex(halfWidth, halfHeight, -halfDepth);
tess.addVertex(-halfWidth, halfHeight, -halfDepth);
// Bottom edge (y-)
tess.setNormal(0, -1, 0);
tess.addVertex(-halfWidth, -halfHeight, -halfDepth);
tess.addVertex(halfWidth, -halfHeight, -halfDepth);
tess.addVertex(halfWidth, -halfHeight, halfDepth);
tess.addVertex(-halfWidth, -halfHeight, halfDepth);
// Right edge (x+)
tess.setColorRGBA_F(r, g, b, alpha * 0.6f);
tess.setNormal(1, 0, 0);
tess.addVertex(halfWidth, -halfHeight, halfDepth);
tess.addVertex(halfWidth, -halfHeight, -halfDepth);
tess.addVertex(halfWidth, halfHeight, -halfDepth);
tess.addVertex(halfWidth, halfHeight, halfDepth);
// Left edge (x-)
tess.setNormal(-1, 0, 0);
tess.addVertex(-halfWidth, -halfHeight, -halfDepth);
tess.addVertex(-halfWidth, -halfHeight, halfDepth);
tess.addVertex(-halfWidth, halfHeight, halfDepth);
tess.addVertex(-halfWidth, halfHeight, -halfDepth);
tess.draw();
}
}
@@ -2,7 +2,7 @@ package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.entity.EntityAbilitySweeper;
import kamkeel.npcs.entity.EntityEnergySweeper;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
@@ -15,16 +15,17 @@ import org.lwjgl.opengl.GL11;
* Uses similar rendering style to the Beam trail for visual consistency.
*/
@SideOnly(Side.CLIENT)
public class RenderAbilitySweeper extends Render {
public class RenderSweeper extends Render {
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
EntityAbilitySweeper sweeper = (EntityAbilitySweeper) entity;
EntityEnergySweeper sweeper = (EntityEnergySweeper) entity;
setupRenderState();
float beamLength = sweeper.getBeamLength();
float beamWidth = sweeper.getBeamWidth();
float beamHeight = sweeper.getBeamHeight();
int innerColor = sweeper.getInnerColor();
int outerColor = sweeper.getOuterColor();
boolean outerColorEnabled = sweeper.isOuterColorEnabled();
@@ -38,7 +39,7 @@ public class RenderAbilitySweeper extends Render {
GL11.glRotatef(-angle, 0, 1, 0); // Negative for correct direction
// Render the beam extending in the +Z direction (like beam trail segments)
renderBeam(beamLength, beamWidth, innerColor, outerColor, outerColorEnabled, outerColorWidth);
renderBeam(beamLength, beamWidth, beamHeight, innerColor, outerColor, outerColorEnabled, outerColorWidth);
GL11.glPopMatrix();
@@ -70,8 +71,10 @@ public class RenderAbilitySweeper extends Render {
/**
* Render beam using the same style as the Beam entity trail.
* Three layers: outer glow, middle, inner core.
* outerColorWidth is an additive offset from inner width (consistent with other renderers).
* Width and height control the rectangular cross-section independently.
*/
private void renderBeam(float length, float width, int innerColor, int outerColor,
private void renderBeam(float length, float width, float height, int innerColor, int outerColor,
boolean outerColorEnabled, float outerColorWidth) {
// Extract colors
float outerR = ((outerColor >> 16) & 0xFF) / 255.0f;
@@ -82,30 +85,40 @@ public class RenderAbilitySweeper extends Render {
float innerG = ((innerColor >> 8) & 0xFF) / 255.0f;
float innerB = (innerColor & 0xFF) / 255.0f;
// Inner scale defines the core size (consistent with other renderers)
float innerScale = 0.6f;
float innerWidth = width * innerScale;
float innerHeight = height * innerScale;
// Render from origin (0,0,0) to (0,0,length) in local coords
// After rotation this extends in the correct world direction
// Outer glow (wider, translucent) - like beam trail - only if enabled
// Outer glow (wider, translucent) - only if enabled
// outerColorWidth is additive offset from inner size
if (outerColorEnabled) {
float outerWidth = innerWidth + outerColorWidth * width;
float outerHeight = innerHeight + outerColorWidth * height;
GL11.glDepthMask(false);
renderBeamSegment(0, 0, 0, 0, 0, length, width * outerColorWidth, outerR, outerG, outerB, 0.3f);
renderBeamSegment(0, 0, 0, 0, 0, length, outerWidth, outerHeight, outerR, outerG, outerB, 0.3f);
GL11.glDepthMask(true);
// Middle layer
renderBeamSegment(0, 0, 0, 0, 0, length, width * 1.3f, outerR, outerG, outerB, 0.6f);
// Middle layer (halfway between inner and outer)
float midWidth = innerWidth + (outerWidth - innerWidth) * 0.5f;
float midHeight = innerHeight + (outerHeight - innerHeight) * 0.5f;
renderBeamSegment(0, 0, 0, 0, 0, length, midWidth, midHeight, outerR, outerG, outerB, 0.6f);
}
// Inner core (solid) - like beam trail inner
renderBeamSegment(0, 0, 0, 0, 0, length, width * 0.6f, innerR, innerG, innerB, 1.0f);
// Inner core (solid)
renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerHeight, innerR, innerG, innerB, 1.0f);
}
/**
* Render a beam segment as a 3D rectangular prism.
* Uses the same approach as RenderAbilityBeam.renderBeamRectangle.
* Render a beam segment as a 3D rectangular prism with independent width and height.
* Uses the same approach as RenderEnergyBeam.renderBeamRectangle.
*/
private void renderBeamSegment(double x1, double y1, double z1,
double x2, double y2, double z2,
float width, float r, float g, float b, float a) {
double x2, double y2, double z2,
float width, float height, float r, float g, float b, float a) {
// Calculate direction
double dx = x2 - x1;
double dy = y2 - y1;
@@ -121,7 +134,9 @@ public class RenderAbilitySweeper extends Render {
// Calculate perpendicular vectors
double upX = 0, upY = 1, upZ = 0;
if (Math.abs(dy) > 0.9) {
upX = 1; upY = 0; upZ = 0;
upX = 1;
upY = 0;
upZ = 0;
}
// Cross product for horizontal perpendicular
@@ -141,39 +156,40 @@ public class RenderAbilitySweeper extends Render {
double vertZ = dx * horzY - dy * horzX;
float halfWidth = width * 0.5f;
float halfHeight = height * 0.5f;
// Calculate 8 corners of the box
double s1x = x1 - horzX * halfWidth - vertX * halfWidth;
double s1y = y1 - horzY * halfWidth - vertY * halfWidth;
double s1z = z1 - horzZ * halfWidth - vertZ * halfWidth;
// Calculate 8 corners of the box (horz scaled by halfWidth, vert scaled by halfHeight)
double s1x = x1 - horzX * halfWidth - vertX * halfHeight;
double s1y = y1 - horzY * halfWidth - vertY * halfHeight;
double s1z = z1 - horzZ * halfWidth - vertZ * halfHeight;
double s2x = x1 + horzX * halfWidth - vertX * halfWidth;
double s2y = y1 + horzY * halfWidth - vertY * halfWidth;
double s2z = z1 + horzZ * halfWidth - vertZ * halfWidth;
double s2x = x1 + horzX * halfWidth - vertX * halfHeight;
double s2y = y1 + horzY * halfWidth - vertY * halfHeight;
double s2z = z1 + horzZ * halfWidth - vertZ * halfHeight;
double s3x = x1 + horzX * halfWidth + vertX * halfWidth;
double s3y = y1 + horzY * halfWidth + vertY * halfWidth;
double s3z = z1 + horzZ * halfWidth + vertZ * halfWidth;
double s3x = x1 + horzX * halfWidth + vertX * halfHeight;
double s3y = y1 + horzY * halfWidth + vertY * halfHeight;
double s3z = z1 + horzZ * halfWidth + vertZ * halfHeight;
double s4x = x1 - horzX * halfWidth + vertX * halfWidth;
double s4y = y1 - horzY * halfWidth + vertY * halfWidth;
double s4z = z1 - horzZ * halfWidth + vertZ * halfWidth;
double s4x = x1 - horzX * halfWidth + vertX * halfHeight;
double s4y = y1 - horzY * halfWidth + vertY * halfHeight;
double s4z = z1 - horzZ * halfWidth + vertZ * halfHeight;
double e1x = x2 - horzX * halfWidth - vertX * halfWidth;
double e1y = y2 - horzY * halfWidth - vertY * halfWidth;
double e1z = z2 - horzZ * halfWidth - vertZ * halfWidth;
double e1x = x2 - horzX * halfWidth - vertX * halfHeight;
double e1y = y2 - horzY * halfWidth - vertY * halfHeight;
double e1z = z2 - horzZ * halfWidth - vertZ * halfHeight;
double e2x = x2 + horzX * halfWidth - vertX * halfWidth;
double e2y = y2 + horzY * halfWidth - vertY * halfWidth;
double e2z = z2 + horzZ * halfWidth - vertZ * halfWidth;
double e2x = x2 + horzX * halfWidth - vertX * halfHeight;
double e2y = y2 + horzY * halfWidth - vertY * halfHeight;
double e2z = z2 + horzZ * halfWidth - vertZ * halfHeight;
double e3x = x2 + horzX * halfWidth + vertX * halfWidth;
double e3y = y2 + horzY * halfWidth + vertY * halfWidth;
double e3z = z2 + horzZ * halfWidth + vertZ * halfWidth;
double e3x = x2 + horzX * halfWidth + vertX * halfHeight;
double e3y = y2 + horzY * halfWidth + vertY * halfHeight;
double e3z = z2 + horzZ * halfWidth + vertZ * halfHeight;
double e4x = x2 - horzX * halfWidth + vertX * halfWidth;
double e4y = y2 - horzY * halfWidth + vertY * halfWidth;
double e4z = z2 - horzZ * halfWidth + vertZ * halfWidth;
double e4x = x2 - horzX * halfWidth + vertX * halfHeight;
double e4y = y2 - horzY * halfWidth + vertY * halfHeight;
double e4z = z2 - horzZ * halfWidth + vertZ * halfHeight;
Tessellator tess = Tessellator.instance;
tess.startDrawingQuads();
@@ -0,0 +1,797 @@
package kamkeel.npcs.client.renderer;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.AttachedLightningRenderer;
import kamkeel.npcs.entity.EntityAbilityZone;
import kamkeel.npcs.entity.EntityAbilityZone.AccentStyle;
import kamkeel.npcs.entity.EntityAbilityZone.ParticleMotion;
import kamkeel.npcs.entity.EntityAbilityZone.ZoneShape;
import kamkeel.npcs.entity.EntityAbilityZone.ZoneType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import noppes.npcs.client.fx.CustomFX;
import noppes.npcs.client.fx.ZoneParticleFX;
import org.lwjgl.opengl.GL11;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@SideOnly(Side.CLIENT)
public class RenderZone extends Render {
private static final int CIRCLE_SEGMENTS = 32;
private static final int ACCENT_LINE_COUNT = 12;
private static final Random RANDOM = new Random();
private final Map<Integer, Integer> lastParticleTick = new HashMap<>();
private final Map<Integer, AttachedLightningRenderer.LightningState> lightningStates = new HashMap<>();
private static final int TRIGGER_REVEAL_TICKS = 10;
private static class Ctx {
EntityAbilityZone zone;
ZoneShape shape;
float radius, height;
float ir, ig, ib;
float outerR, outerG, outerB;
boolean outerEnabled;
float time, pulse, rotation, brightness;
boolean flash, newTick;
float particleDensity, particleScale, animSpeed, lightningDensity;
boolean groundFill, rings, border, accents, lightning, particles;
float groundAlpha, borderSpeed;
int ringCount, accentStyle, particleMotion, particleSize;
boolean particleGlow;
String particleDir;
boolean trapVisible;
boolean triggerReveal;
float revealFade;
}
@Override
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
EntityAbilityZone zone = (EntityAbilityZone) entity;
Ctx c = new Ctx();
c.zone = zone;
c.shape = zone.getShape();
c.radius = zone.getRadius();
c.height = zone.getZoneHeight();
int inner = zone.getInnerColor();
c.ir = ((inner >> 16) & 0xFF) / 255.0f;
c.ig = ((inner >> 8) & 0xFF) / 255.0f;
c.ib = (inner & 0xFF) / 255.0f;
int outer = zone.getOuterColor();
c.outerR = ((outer >> 16) & 0xFF) / 255.0f;
c.outerG = ((outer >> 8) & 0xFF) / 255.0f;
c.outerB = (outer & 0xFF) / 255.0f;
c.outerEnabled = zone.isOuterColorEnabled();
c.particleDensity = zone.getParticleDensity();
c.particleScale = zone.getParticleScale();
c.animSpeed = zone.getAnimSpeed();
c.lightningDensity = zone.getLightningDensity();
c.groundFill = zone.isGroundFill();
c.groundAlpha = zone.getGroundAlpha();
c.rings = zone.isRings();
c.ringCount = zone.getRingCount();
c.border = zone.isBorder();
c.borderSpeed = zone.getBorderSpeed();
c.accents = zone.isAccents();
c.accentStyle = zone.getAccentStyle();
c.lightning = zone.isLightning();
c.particles = zone.isParticles();
c.particleMotion = zone.getParticleMotion();
c.particleDir = zone.getParticleDir();
c.particleSize = zone.getParticleSize();
c.particleGlow = zone.isParticleGlow();
c.time = zone.ticksExisted + partialTicks;
c.pulse = c.time * 0.1f * c.animSpeed;
c.rotation = c.time * 1.5f * c.animSpeed;
c.brightness = 1.0f;
c.trapVisible = true;
c.triggerReveal = false;
c.revealFade = 0.0f;
if (zone.getZoneType() == ZoneType.TRAP) {
c.trapVisible = zone.isVisible();
// Trigger reveal: 10-tick full visual burst that fades out
if (zone.getTriggerFlashTick() >= 0) {
float ticksSinceTrigger = zone.ticksExisted - zone.getTriggerFlashTick() + partialTicks;
if (ticksSinceTrigger < TRIGGER_REVEAL_TICKS) {
c.triggerReveal = true;
c.revealFade = Math.max(0.0f, 1.0f - ticksSinceTrigger / TRIGGER_REVEAL_TICKS);
}
}
// Skip render entirely if invisible and not in reveal
if (!c.trapVisible && !c.triggerReveal) {
return;
}
if (!zone.isArmed()) {
c.brightness = 0.4f;
} else {
c.pulse = c.time * 0.2f;
}
}
// White flash during first 2 ticks of reveal
c.flash = c.triggerReveal && c.revealFade > 0.8f;
c.newTick = isNewTick(zone);
setupRenderState();
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
GL11.glDepthMask(false);
renderZone(c);
GL11.glDepthMask(true);
GL11.glPopMatrix();
restoreRenderState();
}
private boolean isNewTick(EntityAbilityZone zone) {
int id = zone.getEntityId();
int tick = zone.ticksExisted;
Integer last = lastParticleTick.get(id);
if (last == null || last != tick) {
lastParticleTick.put(id, tick);
return true;
}
return false;
}
private AttachedLightningRenderer.LightningState getLightningState(EntityAbilityZone zone) {
int id = zone.getEntityId();
AttachedLightningRenderer.LightningState state = lightningStates.get(id);
if (state == null) {
state = new AttachedLightningRenderer.LightningState();
lightningStates.put(id, state);
}
return state;
}
private void renderZone(Ctx c) {
// During trigger reveal, override visual layers for dramatic burst
if (c.triggerReveal) {
c.brightness = c.revealFade;
c.groundFill = true;
c.groundAlpha = 0.35f * c.revealFade;
c.rings = true;
c.ringCount = 3;
c.accents = true;
c.accentStyle = 2; // FLICKERING
c.border = true;
}
float rR = ringR(c), rG = ringG(c), rB = ringB(c);
if (c.groundFill) {
if (c.flash) {
renderShapeFill(c.shape, c.radius, 1, 1, 1, 0.5f);
} else {
renderShapeFill(c.shape, c.radius,
c.ir, c.ig, c.ib, c.groundAlpha * c.brightness);
}
}
if (c.rings) {
int count = Math.max(1, Math.min(5, c.ringCount));
for (int i = 0; i < count; i++) {
float frac = (i + 1.0f) / (count + 1);
float ra = (0.4f + 0.3f * sin(c.pulse + i * Math.PI / 3)) * c.brightness;
float yOff = 0.02f + i * 0.01f;
renderRingLine(c.shape, c.radius * frac,
rR, rG, rB, ra, yOff);
}
float edgeA = (0.5f + 0.4f * sin(c.pulse + count * Math.PI / 3)) * c.brightness;
renderRingLine(c.shape, c.radius, rR, rG, rB, edgeA, 0.02f + count * 0.01f);
}
if (c.border) {
renderRotatingBorder(c.shape, c.radius, rR, rG, rB,
0.7f * c.brightness, c.rotation * c.borderSpeed, 0.05f);
}
if (c.accents) {
float aa = 0.5f * c.brightness * (0.3f + 0.2f * sin(c.pulse * 0.7f));
AccentStyle style = AccentStyle.values()[Math.max(0, Math.min(c.accentStyle, AccentStyle.values().length - 1))];
switch (style) {
case SWAYING:
renderSwayingAccents(c, c.ir, c.ig, c.ib, aa, c.height);
break;
case FLICKERING:
renderFlickeringAccents(c, c.ir, c.ig, c.ib, aa, c.height);
break;
default:
renderVerticalAccents(c.shape, c.radius, c.ir, c.ig, c.ib, aa, c.height, c.rotation * 0.3f);
break;
}
}
if (c.lightning) {
int innerColor = c.zone.getInnerColor();
int outerColor = c.outerEnabled ? c.zone.getOuterColor() : innerColor;
AttachedLightningRenderer.LightningState state = getLightningState(c.zone);
if (c.newTick) {
state.tick();
float density = 0.4f * c.brightness * c.lightningDensity;
if (RANDOM.nextFloat() < density) {
double[] p1 = randomPosInZone(c);
double[] p2 = randomPosInZone(c);
double y1 = RANDOM.nextDouble() * c.height * 0.4;
double y2 = RANDOM.nextDouble() * c.height * 0.4;
float disp = c.radius * 0.15f;
state.addArc(AttachedLightningRenderer.createArcBetween(
p1[0], y1, p1[2], p2[0], y2, p2[2], disp, outerColor, innerColor, 6));
}
if (RANDOM.nextFloat() < density * 0.5f * c.lightningDensity) {
double[] edgePos = randomEdgePos(c);
double ex = edgePos[0];
double ez = edgePos[1];
float disp = c.radius * 0.12f;
state.addArc(AttachedLightningRenderer.createArcBetween(
ex, 0, ez, ex + (RANDOM.nextDouble() - 0.5) * 0.5,
c.height * (0.3 + RANDOM.nextDouble() * 0.4),
ez + (RANDOM.nextDouble() - 0.5) * 0.5,
disp, outerColor, innerColor, 5));
}
}
state.render();
GL11.glDepthMask(false);
}
if (c.particles && c.newTick && c.particleDensity > 0) {
if (c.particleDir != null && !c.particleDir.isEmpty()) {
if (c.particleDir.startsWith("mc:")) {
spawnVanillaParticle(c);
} else {
spawnCustomFXParticle(c);
}
} else {
spawnDefaultParticles(c);
}
}
}
private void spawnVanillaParticle(Ctx c) {
String particleName = c.particleDir.substring(3);
int count = Math.round(3 * c.particleDensity);
for (int i = 0; i < count; i++) {
double[] pos = randomPosInZone(c);
double[] motion = getMotionForStyle(c.particleMotion);
c.zone.worldObj.spawnParticle(particleName,
c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2],
motion[0], motion[1], motion[2]);
}
}
private void spawnCustomFXParticle(Ctx c) {
int count = Math.round(3 * c.particleDensity);
for (int i = 0; i < count; i++) {
double[] pos = randomPosInZone(c);
double[] motion = getMotionForStyle(c.particleMotion);
CustomFX fx = new CustomFX(c.zone.worldObj, null, c.particleDir,
c.zone.posX + pos[0], c.zone.posY + pos[1], c.zone.posZ + pos[2],
0, 0, 0);
fx.motionX = motion[0];
fx.motionY = motion[1];
fx.motionZ = motion[2];
fx.setMaxAge(20 + RANDOM.nextInt(20));
fx.width = -1;
fx.height = -1;
fx.scaleX1 = c.particleScale * 10.0f;
fx.scaleY1 = c.particleScale * 10.0f;
fx.scaleX2 = fx.scaleX1;
fx.scaleY2 = fx.scaleY1;
fx.scaleXRate = 0;
fx.scaleYRate = 0;
fx.HEXColor = c.zone.getInnerColor();
fx.facePlayer = true;
fx.glows = c.particleGlow;
fx.noClip = true;
fx.alpha1 = 0.8f;
fx.alpha2 = 0.0f;
fx.alphaRate = -0.04f;
Minecraft.getMinecraft().effectRenderer.addEffect(fx);
}
}
private void spawnDefaultParticles(Ctx c) {
int count = Math.round(3 * c.particleDensity);
ParticleMotion motion = ParticleMotion.values()[Math.max(0, Math.min(c.particleMotion, ParticleMotion.values().length - 1))];
for (int i = 0; i < count; i++) {
double[] pos = randomPosInZone(c);
double mx, my, mz;
float gravity;
int age;
switch (motion) {
case DRIFTING:
mx = (RANDOM.nextDouble() - 0.5) * 0.005;
my = 0.005 + RANDOM.nextDouble() * 0.01;
mz = (RANDOM.nextDouble() - 0.5) * 0.005;
gravity = 0;
age = 40 + RANDOM.nextInt(20);
break;
case SPARKS:
mx = (RANDOM.nextDouble() - 0.5) * 0.08;
my = RANDOM.nextDouble() * 0.06;
mz = (RANDOM.nextDouble() - 0.5) * 0.08;
gravity = 0;
age = 4 + RANDOM.nextInt(6);
break;
default: // RISING
mx = (RANDOM.nextDouble() - 0.5) * 0.01;
my = 0.01 + RANDOM.nextDouble() * 0.02;
mz = (RANDOM.nextDouble() - 0.5) * 0.01;
gravity = -0.01f;
age = 30 + RANDOM.nextInt(20);
break;
}
float scale = (1.5f + RANDOM.nextFloat() * 1.0f) * c.particleScale;
spawnParticle(c.zone, pos[0], pos[1], pos[2], mx, my, mz,
c.ir, c.ig, c.ib, 0.7f, scale, age, gravity, c.particleGlow);
}
}
private double[] getMotionForStyle(int motionOrdinal) {
ParticleMotion motion = ParticleMotion.values()[Math.max(0, Math.min(motionOrdinal, ParticleMotion.values().length - 1))];
switch (motion) {
case DRIFTING:
return new double[]{
(RANDOM.nextDouble() - 0.5) * 0.005,
0.005 + RANDOM.nextDouble() * 0.01,
(RANDOM.nextDouble() - 0.5) * 0.005
};
case SPARKS:
return new double[]{
(RANDOM.nextDouble() - 0.5) * 0.08,
RANDOM.nextDouble() * 0.06,
(RANDOM.nextDouble() - 0.5) * 0.08
};
default: // RISING
return new double[]{
(RANDOM.nextDouble() - 0.5) * 0.01,
0.01 + RANDOM.nextDouble() * 0.02,
(RANDOM.nextDouble() - 0.5) * 0.01
};
}
}
private float ringR(Ctx c) {
return c.outerEnabled ? c.outerR : c.ir;
}
private float ringG(Ctx c) {
return c.outerEnabled ? c.outerG : c.ig;
}
private float ringB(Ctx c) {
return c.outerEnabled ? c.outerB : c.ib;
}
private static float sin(double v) {
return (float) Math.sin(v);
}
private void renderSwayingAccents(Ctx c, float r, float g, float b, float a, float height) {
if (height <= 0.1f) return;
float rotRad = (float) Math.toRadians(c.rotation * 0.2f);
Tessellator tess = Tessellator.instance;
if (c.shape == ZoneShape.SQUARE) {
renderSquareSwayingAccents(c, r, g, b, a, height, rotRad, tess);
} else {
for (int i = 0; i < ACCENT_LINE_COUNT; i++) {
float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad;
double lx = Math.cos(baseAngle) * c.radius;
double lz = Math.sin(baseAngle) * c.radius;
float swayX = 0.15f * sin(c.time * 0.08f + i * 1.7f);
float swayZ = 0.15f * sin(c.time * 0.06f + i * 2.3f);
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx + swayX, height, lz + swayZ);
tess.draw();
}
}
}
private void renderSquareSwayingAccents(Ctx c, float r, float g, float b, float a, float height, float rotRad, Tessellator tess) {
int perSide = Math.max(1, ACCENT_LINE_COUNT / 4);
int idx = 0;
for (int side = 0; side < 4; side++) {
for (int j = 0; j < perSide; j++) {
float frac = (j + 0.5f) / perSide;
double lx, lz;
switch (side) {
case 0:
lx = -c.radius + frac * 2 * c.radius;
lz = -c.radius;
break;
case 1:
lx = c.radius;
lz = -c.radius + frac * 2 * c.radius;
break;
case 2:
lx = c.radius - frac * 2 * c.radius;
lz = c.radius;
break;
default:
lx = -c.radius;
lz = c.radius - frac * 2 * c.radius;
break;
}
float swayX = 0.15f * sin(c.time * 0.08f + idx * 1.7f);
float swayZ = 0.15f * sin(c.time * 0.06f + idx * 2.3f);
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx + swayX, height, lz + swayZ);
tess.draw();
idx++;
}
}
}
private void renderFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height) {
if (height <= 0.1f) return;
float rotRad = (float) Math.toRadians(c.rotation * 0.4f);
Tessellator tess = Tessellator.instance;
if (c.shape == ZoneShape.SQUARE) {
renderSquareFlickeringAccents(c, r, g, b, baseAlpha, height, tess);
} else {
for (int i = 0; i < ACCENT_LINE_COUNT; i++) {
float baseAngle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad;
double lx = Math.cos(baseAngle) * c.radius;
double lz = Math.sin(baseAngle) * c.radius;
float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + i * 3.14f));
float lineAlpha = baseAlpha * flicker;
float lineHeight = height * (0.6f + 0.4f * flicker);
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, lineAlpha);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx, lineHeight, lz);
tess.draw();
}
}
}
private void renderSquareFlickeringAccents(Ctx c, float r, float g, float b, float baseAlpha, float height, Tessellator tess) {
int perSide = Math.max(1, ACCENT_LINE_COUNT / 4);
int idx = 0;
for (int side = 0; side < 4; side++) {
for (int j = 0; j < perSide; j++) {
float frac = (j + 0.5f) / perSide;
double lx, lz;
switch (side) {
case 0:
lx = -c.radius + frac * 2 * c.radius;
lz = -c.radius;
break;
case 1:
lx = c.radius;
lz = -c.radius + frac * 2 * c.radius;
break;
case 2:
lx = c.radius - frac * 2 * c.radius;
lz = c.radius;
break;
default:
lx = -c.radius;
lz = c.radius - frac * 2 * c.radius;
break;
}
float flicker = 0.3f + 0.7f * Math.abs(sin(c.time * 0.7f + idx * 3.14f));
float lineAlpha = baseAlpha * flicker;
float lineHeight = height * (0.6f + 0.4f * flicker);
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, lineAlpha);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx, lineHeight, lz);
tess.draw();
idx++;
}
}
}
private double[] randomPosInZone(Ctx c) {
if (c.shape == ZoneShape.SQUARE) {
double px = (RANDOM.nextDouble() * 2 - 1) * c.radius;
double pz = (RANDOM.nextDouble() * 2 - 1) * c.radius;
return new double[]{px, 0, pz};
} else {
double angle = RANDOM.nextDouble() * Math.PI * 2;
double dist = Math.sqrt(RANDOM.nextDouble()) * c.radius;
double px = Math.cos(angle) * dist;
double pz = Math.sin(angle) * dist;
return new double[]{px, 0, pz};
}
}
private double[] randomEdgePos(Ctx c) {
if (c.shape == ZoneShape.SQUARE) {
int side = RANDOM.nextInt(4);
double frac = RANDOM.nextDouble() * 2 - 1;
switch (side) {
case 0:
return new double[]{frac * c.radius, -c.radius};
case 1:
return new double[]{frac * c.radius, c.radius};
case 2:
return new double[]{-c.radius, frac * c.radius};
default:
return new double[]{c.radius, frac * c.radius};
}
} else {
double angle = RANDOM.nextDouble() * Math.PI * 2;
double dist = c.radius * (0.5 + RANDOM.nextDouble() * 0.5);
return new double[]{Math.cos(angle) * dist, Math.sin(angle) * dist};
}
}
private void spawnParticle(EntityAbilityZone zone, double offsetX, double offsetY, double offsetZ,
double mx, double my, double mz,
float r, float g, float b, float alpha,
float scale, int maxAge, float gravity, boolean glow) {
ZoneParticleFX particle = new ZoneParticleFX(
zone.worldObj,
zone.posX + offsetX, zone.posY + offsetY, zone.posZ + offsetZ,
mx, my, mz, r, g, b, alpha, scale, maxAge, gravity, glow);
Minecraft.getMinecraft().effectRenderer.addEffect(particle);
}
private void setupRenderState() {
GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glShadeModel(GL11.GL_SMOOTH);
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0f, 240.0f);
}
private void restoreRenderState() {
GL11.glShadeModel(GL11.GL_FLAT);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glPopAttrib();
}
private void renderShapeFill(ZoneShape shape, float radius, float r, float g, float b, float a) {
GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
GL11.glPolygonOffset(-1.0f, -1.0f);
switch (shape) {
case CIRCLE:
renderCircleFill(radius, r, g, b, a);
break;
case SQUARE:
renderSquareFill(radius, r, g, b, a);
break;
}
GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
}
private void renderCircleFill(float radius, float r, float g, float b, float a) {
Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_TRIANGLE_FAN);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(0, 0, 0);
for (int i = 0; i <= CIRCLE_SEGMENTS; i++) {
double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
tess.addVertex(Math.cos(angle) * radius, 0, Math.sin(angle) * radius);
}
tess.draw();
}
private void renderSquareFill(float radius, float r, float g, float b, float a) {
Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_QUADS);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(-radius, 0, -radius);
tess.addVertex(radius, 0, -radius);
tess.addVertex(radius, 0, radius);
tess.addVertex(-radius, 0, radius);
tess.draw();
}
private void renderRingLine(ZoneShape shape, float radius,
float r, float g, float b, float a, float yOffset) {
switch (shape) {
case CIRCLE:
renderCircleRingLine(radius, r, g, b, a, yOffset);
break;
case SQUARE:
renderSquareRingLine(radius, r, g, b, a, yOffset);
break;
}
}
private void renderCircleRingLine(float radius, float r, float g, float b, float a, float yOffset) {
Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_LINE_LOOP);
tess.setColorRGBA_F(r, g, b, a);
for (int i = 0; i < CIRCLE_SEGMENTS; i++) {
double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
tess.addVertex(Math.cos(angle) * radius, yOffset, Math.sin(angle) * radius);
}
tess.draw();
}
private void renderSquareRingLine(float radius, float r, float g, float b, float a, float yOffset) {
Tessellator tess = Tessellator.instance;
tess.startDrawing(GL11.GL_LINE_LOOP);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(-radius, yOffset, -radius);
tess.addVertex(radius, yOffset, -radius);
tess.addVertex(radius, yOffset, radius);
tess.addVertex(-radius, yOffset, radius);
tess.draw();
}
private void renderRotatingBorder(ZoneShape shape, float radius,
float r, float g, float b, float a,
float rotationDeg, float yOffset) {
int dashCount = 16;
if (shape == ZoneShape.SQUARE) {
float perimeter = radius * 8;
float dashLen = perimeter / dashCount;
float offset = (rotationDeg % 360.0f) / 360.0f * perimeter;
Tessellator tess = Tessellator.instance;
for (int i = 0; i < dashCount; i += 2) {
float startDist = (i * dashLen + offset) % perimeter;
float endDist = startDist + dashLen;
tess.startDrawing(GL11.GL_LINE_STRIP);
tess.setColorRGBA_F(r, g, b, a);
int steps = 4;
for (int s = 0; s <= steps; s++) {
float d = startDist + (endDist - startDist) * s / steps;
double[] pos = perimeterPos(d % perimeter, radius);
tess.addVertex(pos[0], yOffset, pos[1]);
}
tess.draw();
}
} else {
float dashAngle = (float) (Math.PI * 2) / dashCount;
float rotRad = (float) Math.toRadians(rotationDeg);
Tessellator tess = Tessellator.instance;
for (int i = 0; i < dashCount; i += 2) {
float startAngle = i * dashAngle + rotRad;
float endAngle = startAngle + dashAngle;
tess.startDrawing(GL11.GL_LINE_STRIP);
tess.setColorRGBA_F(r, g, b, a);
int steps = 4;
for (int s = 0; s <= steps; s++) {
float segAngle = startAngle + (endAngle - startAngle) * s / steps;
tess.addVertex(Math.cos(segAngle) * radius, yOffset, Math.sin(segAngle) * radius);
}
tess.draw();
}
}
}
private double[] perimeterPos(float dist, float radius) {
float sideLen = radius * 2;
if (dist < sideLen) {
// Bottom edge: (-radius, -radius) to (radius, -radius)
return new double[]{-radius + dist, -radius};
}
dist -= sideLen;
if (dist < sideLen) {
// Right edge: (radius, -radius) to (radius, radius)
return new double[]{radius, -radius + dist};
}
dist -= sideLen;
if (dist < sideLen) {
// Top edge: (radius, radius) to (-radius, radius)
return new double[]{radius - dist, radius};
}
dist -= sideLen;
// Left edge: (-radius, radius) to (-radius, -radius)
return new double[]{-radius, radius - dist};
}
private void renderVerticalAccents(ZoneShape shape, float radius,
float r, float g, float b, float a,
float height, float rotationDeg) {
if (height <= 0.1f) return;
Tessellator tess = Tessellator.instance;
if (shape == ZoneShape.SQUARE) {
int perSide = Math.max(1, ACCENT_LINE_COUNT / 4);
for (int side = 0; side < 4; side++) {
for (int j = 0; j < perSide; j++) {
float frac = (j + 0.5f) / perSide;
double lx, lz;
switch (side) {
case 0:
lx = -radius + frac * 2 * radius;
lz = -radius;
break;
case 1:
lx = radius;
lz = -radius + frac * 2 * radius;
break;
case 2:
lx = radius - frac * 2 * radius;
lz = radius;
break;
default:
lx = -radius;
lz = radius - frac * 2 * radius;
break;
}
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx, height, lz);
tess.draw();
}
}
float[][] corners = {{-radius, -radius}, {radius, -radius}, {radius, radius}, {-radius, radius}};
for (float[] corner : corners) {
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(corner[0], 0.01, corner[1]);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(corner[0], height, corner[1]);
tess.draw();
}
} else {
float rotRad = (float) Math.toRadians(rotationDeg);
for (int i = 0; i < ACCENT_LINE_COUNT; i++) {
float angle = (float) (Math.PI * 2 * i) / ACCENT_LINE_COUNT + rotRad;
double lx = Math.cos(angle) * radius;
double lz = Math.sin(angle) * radius;
tess.startDrawing(GL11.GL_LINES);
tess.setColorRGBA_F(r, g, b, a);
tess.addVertex(lx, 0.01, lz);
tess.setColorRGBA_F(r, g, b, 0.0f);
tess.addVertex(lx, height, lz);
tess.draw();
}
}
}
@Override
protected ResourceLocation getEntityTexture(Entity entity) {
return null;
}
}
@@ -105,11 +105,14 @@ public class TelegraphRenderer {
renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
break;
case CONE:
renderCone(telegraph.getLength(), telegraph.getAngle(), red, green, blue, alpha);
renderCone(telegraph.getLength(), telegraph.getAngle(), telegraph.getInnerRadius(), red, green, blue, alpha);
break;
case POINT:
renderPoint(red, green, blue, alpha);
break;
case SQUARE:
renderSquare(telegraph.getRadius(), red, green, blue, alpha);
break;
default:
break;
}
@@ -204,42 +207,98 @@ public class TelegraphRenderer {
tessellator.draw();
}
private void renderCone(float length, float angle, float r, float g, float b, float a) {
private void renderCone(float length, float angle, float innerRadius, float r, float g, float b, float a) {
float halfAngleRad = (float) Math.toRadians(angle / 2);
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
tessellator.setColorRGBA_F(r, g, b, a);
// Origin point
tessellator.addVertex(0, 0, 0);
if (innerRadius <= 0) {
// Standard cone: triangle fan from origin
tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
tessellator.setColorRGBA_F(r, g, b, a);
// Arc points
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double x = Math.sin(segmentAngle) * length;
double z = Math.cos(segmentAngle) * length;
tessellator.addVertex(x, 0, z);
tessellator.addVertex(0, 0, 0);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double x = Math.sin(segmentAngle) * length;
double z = Math.cos(segmentAngle) * length;
tessellator.addVertex(x, 0, z);
}
tessellator.draw();
// Border
tessellator.startDrawing(GL11.GL_LINE_STRIP);
tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
tessellator.addVertex(0, 0.01, 0);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double x = Math.sin(segmentAngle) * length;
double z = Math.cos(segmentAngle) * length;
tessellator.addVertex(x, 0.01, z);
}
tessellator.addVertex(0, 0.01, 0);
tessellator.draw();
} else {
// Truncated cone: strip between inner and outer arcs
tessellator.startDrawing(GL11.GL_TRIANGLE_STRIP);
tessellator.setColorRGBA_F(r, g, b, a);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double sinA = Math.sin(segmentAngle);
double cosA = Math.cos(segmentAngle);
tessellator.addVertex(sinA * length, 0, cosA * length);
tessellator.addVertex(sinA * innerRadius, 0, cosA * innerRadius);
}
tessellator.draw();
// Border: outer arc
float borderAlpha = Math.min(1.0f, a * 2);
tessellator.startDrawing(GL11.GL_LINE_STRIP);
tessellator.setColorRGBA_F(r, g, b, borderAlpha);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
tessellator.addVertex(Math.sin(segmentAngle) * length, 0.01, Math.cos(segmentAngle) * length);
}
tessellator.draw();
// Border: inner arc
tessellator.startDrawing(GL11.GL_LINE_STRIP);
tessellator.setColorRGBA_F(r, g, b, borderAlpha);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
tessellator.addVertex(Math.sin(segmentAngle) * innerRadius, 0.01, Math.cos(segmentAngle) * innerRadius);
}
tessellator.draw();
// Border: side edges connecting inner and outer arcs
tessellator.startDrawing(GL11.GL_LINES);
tessellator.setColorRGBA_F(r, g, b, borderAlpha);
double sinStart = Math.sin(-halfAngleRad);
double cosStart = Math.cos(-halfAngleRad);
tessellator.addVertex(sinStart * innerRadius, 0.01, cosStart * innerRadius);
tessellator.addVertex(sinStart * length, 0.01, cosStart * length);
double sinEnd = Math.sin(halfAngleRad);
double cosEnd = Math.cos(halfAngleRad);
tessellator.addVertex(sinEnd * innerRadius, 0.01, cosEnd * innerRadius);
tessellator.addVertex(sinEnd * length, 0.01, cosEnd * length);
tessellator.draw();
}
tessellator.draw();
// Draw border
tessellator.startDrawing(GL11.GL_LINE_STRIP);
tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
tessellator.addVertex(0, 0.01, 0);
for (int i = 0; i <= CONE_SEGMENTS; i++) {
float segmentAngle = -halfAngleRad + (halfAngleRad * 2 * i) / CONE_SEGMENTS;
double x = Math.sin(segmentAngle) * length;
double z = Math.cos(segmentAngle) * length;
tessellator.addVertex(x, 0.01, z);
}
tessellator.addVertex(0, 0.01, 0);
tessellator.draw();
}
private void renderPoint(float r, float g, float b, float a) {
@@ -258,6 +317,30 @@ public class TelegraphRenderer {
tessellator.draw();
}
private void renderSquare(float radius, float r, float g, float b, float a) {
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.setColorRGBA_F(r, g, b, a);
tessellator.addVertex(-radius, 0, -radius);
tessellator.addVertex(radius, 0, -radius);
tessellator.addVertex(radius, 0, radius);
tessellator.addVertex(-radius, 0, radius);
tessellator.draw();
// Draw border
tessellator.startDrawing(GL11.GL_LINE_LOOP);
tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
tessellator.addVertex(-radius, 0.01, -radius);
tessellator.addVertex(radius, 0.01, -radius);
tessellator.addVertex(radius, 0.01, radius);
tessellator.addVertex(-radius, 0.01, radius);
tessellator.draw();
}
// ==================== GUI PREVIEW RENDERING ====================
/**
@@ -272,8 +355,8 @@ public class TelegraphRenderer {
* @param partialTicks Partial ticks for interpolation
*/
public void renderTelegraphInGUI(TelegraphInstance instance,
double centerX, double centerY, double centerZ,
float scale, float partialTicks) {
double centerX, double centerY, double centerZ,
float scale, float partialTicks) {
if (instance == null) return;
Telegraph telegraph = instance.getTelegraph();
@@ -317,11 +400,14 @@ public class TelegraphRenderer {
renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
break;
case CONE:
renderCone(telegraph.getLength(), telegraph.getAngle(), red, green, blue, alpha);
renderCone(telegraph.getLength(), telegraph.getAngle(), telegraph.getInnerRadius(), red, green, blue, alpha);
break;
case POINT:
renderPoint(red, green, blue, alpha);
break;
case SQUARE:
renderSquare(telegraph.getRadius(), red, green, blue, alpha);
break;
default:
break;
}
@@ -3,7 +3,6 @@ package kamkeel.npcs.client.renderer.lightning;
import net.minecraft.client.renderer.Tessellator;
import org.lwjgl.opengl.GL11;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -37,6 +36,7 @@ public class AttachedLightningRenderer {
public float getAlphaMultiplier() {
// Fade out over lifetime
if (maxAge <= 0) return 0.0f;
return 1.0f - ((float) age / (float) maxAge);
}
@@ -85,6 +85,28 @@ public class AttachedLightningRenderer {
}
}
/**
* Age existing arcs and remove dead ones without spawning new arcs.
* Use with addArc() for custom arc generation.
*/
public void tick() {
Iterator<LightningArc> iter = arcs.iterator();
while (iter.hasNext()) {
LightningArc arc = iter.next();
arc.tick();
if (arc.isDead()) {
iter.remove();
}
}
}
/**
* Add a custom arc to the state.
*/
public void addArc(LightningArc arc) {
arcs.add(arc);
}
/**
* Render all active arcs in local space.
* Call this after glTranslated to entity position.
@@ -143,8 +165,8 @@ public class AttachedLightningRenderer {
* Generate a jagged lightning path between two points.
*/
private static List<double[]> generateLightningPath(double x1, double y1, double z1,
double x2, double y2, double z2,
int segments, float displacement) {
double x2, double y2, double z2,
int segments, float displacement) {
List<double[]> points = new ArrayList<>();
points.add(new double[]{x1, y1, z1});
@@ -186,10 +208,9 @@ public class AttachedLightningRenderer {
private static void renderBoltPath(Tessellator tess, List<double[]> points, int color, float width, float alpha) {
if (alpha <= 0.01f) return;
Color c = new Color(color);
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int r = (color >> 16) & 0xFF;
int g = (color >> 8) & 0xFF;
int b = color & 0xFF;
int a = Math.min(255, Math.max(0, (int) (alpha * 255)));
for (int i = 0; i < points.size() - 1; i++) {
@@ -231,6 +252,17 @@ public class AttachedLightningRenderer {
}
}
/**
* Create a lightning arc between two arbitrary points.
*/
public static LightningArc createArcBetween(double x1, double y1, double z1,
double x2, double y2, double z2,
float displacement, int outerColor, int innerColor, int maxAge) {
int segments = 4 + rand.nextInt(3);
List<double[]> points = generateLightningPath(x1, y1, z1, x2, y2, z2, segments, displacement);
return new LightningArc(points, maxAge, outerColor, innerColor);
}
// ==================== INSTANT RENDERING (no persistence) ====================
/**
@@ -56,7 +56,7 @@ public class LightningBolt {
this.numSegments0 = 1;
this.length = end.copy().subtract(start).mag();
this.particleMaxAge = FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2;
this.particleMaxAge = Math.max(1, FADE_TIME + rand.nextInt(FADE_TIME) - FADE_TIME / 2);
this.particleAge = -(int) (length * speed);
segments.add(new Segment(start, end));
@@ -243,7 +243,7 @@ public class LightningBolt {
public Segment(Vec3d start, Vec3d end) {
this(new BoltPoint(start, new Vec3d(0, 0, 0)),
new BoltPoint(end, new Vec3d(0, 0, 0)), 1, 0, 0);
new BoltPoint(end, new Vec3d(0, 0, 0)), 1, 0, 0);
}
public void calcDiff() {
@@ -5,7 +5,6 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import kamkeel.npcs.client.renderer.lightning.LightningBolt.Segment;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ActiveRenderInfo;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.entity.Entity;
@@ -19,7 +18,7 @@ import java.awt.Color;
/**
* Handles rendering of lightning bolts in the world.
* Adapted from Botania's LightningHandler by Vazkii/ChickenBones.
*
* <p>
* Register this handler with: MinecraftForge.EVENT_BUS.register(new LightningHandler());
*/
@SideOnly(Side.CLIENT)
@@ -168,13 +167,13 @@ public class LightningHandler {
/**
* Spawn a lightning bolt between two points.
*
* @param world The world
* @param start Start position
* @param end End position
* @param world The world
* @param start Start position
* @param end End position
* @param ticksPerMeter Speed of bolt expansion
* @param seed Random seed for consistent appearance
* @param colorOuter Outer glow color (ARGB)
* @param colorInner Inner core color (ARGB)
* @param seed Random seed for consistent appearance
* @param colorOuter Outer glow color (ARGB)
* @param colorInner Inner core color (ARGB)
*/
public static void spawnLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, long seed, int colorOuter, int colorInner) {
LightningBolt bolt = new LightningBolt(world, start, end, ticksPerMeter, seed, colorOuter, colorInner);
@@ -1,12 +1,14 @@
package kamkeel.npcs.command;
import kamkeel.npcs.controllers.AbilityController;
import kamkeel.npcs.controllers.data.ability.Ability;
import kamkeel.npcs.controllers.data.ability.AbilityController;
import kamkeel.npcs.controllers.data.ability.UserType;
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
import kamkeel.npcs.controllers.data.ability.enums.UserType;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import noppes.npcs.NoppesUtilServer;
import noppes.npcs.controllers.PlayerDataController;
import noppes.npcs.controllers.data.PlayerAbilityData;
import noppes.npcs.controllers.data.PlayerData;
import java.util.ArrayList;
@@ -33,20 +35,19 @@ public class AbilityCommand extends CommandKamkeelBase {
desc = "List all custom abilities"
)
public void list(ICommandSender sender, String[] args) {
Set<String> uuids = AbilityController.Instance.getCustomAbilityIds();
if (uuids.isEmpty()) {
Set<String> names = AbilityController.Instance.getCustomAbilityNames();
if (names.isEmpty()) {
sendResult(sender, "No custom abilities found.");
return;
}
sendResult(sender, "Custom Abilities (" + uuids.size() + "):");
for (String uuid : uuids) {
Ability ability = AbilityController.Instance.getCustomAbility(uuid);
sendResult(sender, "Custom Abilities (" + names.size() + "):");
for (String name : names) {
Ability ability = AbilityController.Instance.getCustomAbility(name);
if (ability != null) {
String name = ability.getName() != null ? ability.getName() : uuid;
sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ") [" + uuid + "]");
sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ")");
} else {
sendResult(sender, " - \u00A7b" + uuid);
sendResult(sender, " - \u00A7b" + name);
}
}
}
@@ -78,27 +79,27 @@ public class AbilityCommand extends CommandKamkeelBase {
)
public void reload(ICommandSender sender, String[] args) {
AbilityController.Instance.load();
sendResult(sender, "Abilities reloaded from disk.");
sendResult(sender, "Abilities and chained abilities reloaded from disk.");
}
@SubCommand(
desc = "Delete a custom ability by UUID",
usage = "<uuid>"
desc = "Delete a custom ability by name",
usage = "<name>"
)
public void delete(ICommandSender sender, String[] args) {
if (args.length < 1) {
sendError(sender, "Usage: /kam ability delete <uuid>");
sendError(sender, "Usage: /kam ability delete <name>");
return;
}
String uuid = args[0];
if (!AbilityController.Instance.hasCustomAbility(uuid)) {
sendError(sender, "No custom ability with UUID: " + uuid);
String name = joinArgs(args, 0);
if (!AbilityController.Instance.hasCustomAbilityName(name)) {
sendError(sender, "No custom ability with name: " + name);
return;
}
AbilityController.Instance.deleteCustomAbility(uuid);
sendResult(sender, "Deleted ability: \u00A7b" + uuid);
AbilityController.Instance.deleteCustomAbility(name);
sendResult(sender, "Deleted ability: \u00A7b" + name);
}
@SubCommand(
@@ -111,14 +112,15 @@ public class AbilityCommand extends CommandKamkeelBase {
return;
}
String key = args[0];
String key = joinArgs(args, 0);
Ability ability = AbilityController.Instance.resolveAbility(key);
if (ability == null) {
sendError(sender, "No ability found for: " + key);
return;
}
sendResult(sender, "Ability: \u00A7b" + ability.getName());
sendResult(sender, "Ability: \u00A7b" + ability.getDisplayName());
sendResult(sender, " Name: \u00A77" + ability.getName());
sendResult(sender, " Type: \u00A7d" + ability.getTypeId());
sendResult(sender, " Cooldown: \u00A7e" + ability.getCooldownTicks() + " ticks");
sendResult(sender, " Wind Up: \u00A7e" + ability.getWindUpTicks() + " ticks");
@@ -163,26 +165,24 @@ public class AbilityCommand extends CommandKamkeelBase {
}
@SubCommand(
desc = "Unlock an ability for a player",
desc = "Give an ability to a player",
usage = "<player> <ability>"
)
public void unlock(ICommandSender sender, String[] args) {
public void give(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability unlock <player> <ability>");
sendError(sender, "Usage: /kam ability give <player> <ability>");
return;
}
String playerName = args[0];
String abilityKey = joinArgs(args, 1);
// Find player
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
// Resolve ability
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
if (ability == null) {
sendError(sender, "Ability not found: " + abilityKey);
@@ -192,17 +192,15 @@ public class AbilityCommand extends CommandKamkeelBase {
// Use the ability's canonical ID for storage (registry key for built-in, UUID for custom)
String canonicalKey = ability.getId();
if (canonicalKey == null || canonicalKey.isEmpty()) {
canonicalKey = abilityKey; // Fallback to user-provided key
canonicalKey = abilityKey;
}
String displayName = ability.getName() != null ? ability.getName() : canonicalKey;
String displayName = ability.getDisplayName();
// Check if ability allows players
if (!ability.getAllowedBy().allowsPlayer()) {
sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players.");
return;
}
// Get player data and unlock
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (data.abilityData.hasUnlockedAbility(canonicalKey)) {
sendError(sender, "Player already has ability: " + displayName);
@@ -210,39 +208,36 @@ public class AbilityCommand extends CommandKamkeelBase {
}
data.abilityData.unlockAbility(canonicalKey);
sendResult(sender, "Unlocked ability '\u00A7b" + displayName + "\u00A77' for player \u00A7a" + playerName);
sendResult(sender, "Gave ability '\u00A7b" + displayName + "\u00A77' to player \u00A7a" + playerName);
}
@SubCommand(
desc = "Lock (revoke) an ability from a player",
desc = "Remove an ability from a player",
usage = "<player> <ability>"
)
public void lock(ICommandSender sender, String[] args) {
public void remove(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability lock <player> <ability>");
sendError(sender, "Usage: /kam ability remove <player> <ability>");
return;
}
String playerName = args[0];
String abilityKey = joinArgs(args, 1);
// Find player
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
// Resolve ability to get canonical key
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
String canonicalKey = abilityKey;
String displayName = abilityKey;
if (ability != null) {
canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
displayName = ability.getName() != null ? ability.getName() : canonicalKey;
if (ability == null) {
sendError(sender, "Ability not found: " + abilityKey);
return;
}
String canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
String displayName = ability.getDisplayName();
// Get player data and lock
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (!data.abilityData.hasUnlockedAbility(canonicalKey)) {
sendError(sender, "Player doesn't have ability: " + displayName);
@@ -250,7 +245,98 @@ public class AbilityCommand extends CommandKamkeelBase {
}
data.abilityData.lockAbility(canonicalKey);
sendResult(sender, "Locked ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName);
sendResult(sender, "Removed ability '\u00A7b" + displayName + "\u00A77' from player \u00A7a" + playerName);
}
@SubCommand(
desc = "Give a chained ability to a player",
usage = "<player> <chain>"
)
public void giveChain(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability giveChain <player> <chain>");
return;
}
String playerName = args[0];
String chainKey = joinArgs(args, 1);
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey);
if (chain == null) {
sendError(sender, "Chained ability not found: " + chainKey);
return;
}
if (!chain.getAllowedBy().allowsPlayer()) {
sendError(sender, "Chained ability '\u00A7b" + chain.getDisplayName() + "\u00A7c' is NPC-only and cannot be given to players.");
return;
}
String chainId = chain.getId();
if (chainId == null || chainId.isEmpty()) {
sendError(sender, "Chained ability has no ID: " + chain.getDisplayName());
return;
}
// Store by UUID: chain:<uuid>
String storageKey = PlayerAbilityData.CHAIN_PREFIX + chainId;
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (data.abilityData.hasUnlockedAbility(storageKey)) {
sendError(sender, "Player already has chained ability: " + chain.getDisplayName());
return;
}
data.abilityData.unlockAbility(storageKey);
sendResult(sender, "Gave chained ability '\u00A7b" + chain.getDisplayName() + "\u00A77' to player \u00A7a" + playerName);
}
@SubCommand(
desc = "Remove a chained ability from a player",
usage = "<player> <chain>"
)
public void removeChain(ICommandSender sender, String[] args) {
if (args.length < 2) {
sendError(sender, "Usage: /kam ability removeChain <player> <chain>");
return;
}
String playerName = args[0];
String chainKey = joinArgs(args, 1);
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
if (player == null) {
sendError(sender, "Player not found: " + playerName);
return;
}
ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainKey);
if (chain == null) {
sendError(sender, "Chained ability not found: " + chainKey);
return;
}
String chainId = chain.getId();
if (chainId == null || chainId.isEmpty()) {
sendError(sender, "Chained ability has no ID: " + chain.getDisplayName());
return;
}
// Storage uses UUID: chain:<uuid>
String storageKey = PlayerAbilityData.CHAIN_PREFIX + chainId;
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
if (!data.abilityData.hasUnlockedAbility(storageKey)) {
sendError(sender, "Player doesn't have chained ability: " + chain.getDisplayName());
return;
}
data.abilityData.lockAbility(storageKey);
sendResult(sender, "Removed chained ability '\u00A7b" + chain.getDisplayName() + "\u00A77' from player \u00A7a" + playerName);
}
@SubCommand(
@@ -284,14 +370,23 @@ public class AbilityCommand extends CommandKamkeelBase {
int selected = data.abilityData.getSelectedIndex();
for (int i = 0; i < abilityKeys.length; i++) {
String key = abilityKeys[i];
Ability ability = AbilityController.Instance.resolveAbility(key);
String displayName = ability != null && ability.getName() != null ? ability.getName() : key;
String prefix = (i == selected) ? "\u00A7e> " : " ";
// Show display name and key if different
if (!displayName.equals(key)) {
sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]");
if (key.startsWith(PlayerAbilityData.CHAIN_PREFIX)) {
// Chained ability
String chainName = key.substring(PlayerAbilityData.CHAIN_PREFIX.length());
ChainedAbility chain = AbilityController.Instance.resolveChainedAbility(chainName);
String display = chain != null ? chain.getDisplayName() : chainName;
sendResult(sender, prefix + "\u00A7d[Chain] \u00A7b" + display);
} else {
sendResult(sender, prefix + "\u00A7b" + displayName);
// Regular ability
Ability ability = AbilityController.Instance.resolveAbility(key);
String displayName = ability != null ? ability.getDisplayName() : key;
if (!displayName.equals(key)) {
sendResult(sender, prefix + "\u00A7b" + displayName + " \u00A78[" + key + "]");
} else {
sendResult(sender, prefix + "\u00A7b" + displayName);
}
}
}
}
@@ -306,13 +401,34 @@ public class AbilityCommand extends CommandKamkeelBase {
}
/**
* Get list of player-usable ability keys (for tab completion).
* Uses registry keys for built-in abilities (no spaces) and UUIDs for custom.
* Used by CommandKamkeel for <ability> usage token.
* Get list of player-usable ability names (for tab completion).
* Resolves UUIDs to names so tab completion shows human-readable names.
* Used by CommandKamkeel for {@code <ability>} usage token.
*/
public static List<String> getPlayerAbilityNames() {
List<String> keys = new ArrayList<>(AbilityController.Instance.getPlayerAbilityKeys());
Collections.sort(keys);
return keys;
Set<String> keys = AbilityController.Instance.getPlayerAbilityKeys();
List<String> names = new ArrayList<>();
for (String key : keys) {
Ability a = AbilityController.Instance.resolveAbility(key);
names.add(a != null ? a.getName() : key);
}
Collections.sort(names);
return names;
}
/**
* Get list of player-usable chained ability names (for tab completion).
* Used by CommandKamkeel for {@code <chain>} usage token.
*/
public static List<String> getPlayerChainNames() {
List<String> names = new ArrayList<>();
for (String chainName : AbilityController.Instance.getChainedAbilityNamesSet()) {
ChainedAbility chain = AbilityController.Instance.getChainedAbility(chainName);
if (chain != null && chain.getAllowedBy().allowsPlayer()) {
names.add(chainName);
}
}
Collections.sort(names);
return names;
}
}
@@ -20,6 +20,7 @@ import static kamkeel.npcs.util.ColorUtil.sendMessage;
import static kamkeel.npcs.util.ColorUtil.sendResult;
public class AuctionCommand extends CommandKamkeelBase {
private static final int COMMAND_PAGE_SIZE = 10;
public AuctionCommand() {
super();
@@ -62,9 +63,10 @@ public class AuctionCommand extends CommandKamkeelBase {
}
}
List<AuctionListing> listings = controller.getActiveListings(null, page - 1, 10);
page = Math.max(1, page);
List<AuctionListing> listings = controller.getActiveListings(null, page - 1, COMMAND_PAGE_SIZE);
int total = controller.getTotalActiveListings(null);
int totalPages = Math.max(1, (int) Math.ceil((double) total / 10));
int totalPages = Math.max(1, (int) Math.ceil((double) total / COMMAND_PAGE_SIZE));
if (listings.isEmpty()) {
sendMessage(sender, "\u00A77No active auctions found");
@@ -98,6 +100,10 @@ public class AuctionCommand extends CommandKamkeelBase {
return;
}
if (args.length < 1) {
throw new CommandException("Usage: /auction view <player>");
}
String playername = args[0];
List<PlayerData> dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
@@ -21,6 +21,7 @@ import java.util.List;
import java.util.Map;
import static kamkeel.npcs.command.AbilityCommand.getPlayerAbilityNames;
import static kamkeel.npcs.command.AbilityCommand.getPlayerChainNames;
import static kamkeel.npcs.command.EffectCommand.getSortedEffectNames;
public class CommandKamkeel extends CommandBase {
@@ -51,6 +52,7 @@ public class CommandKamkeel extends CommandBase {
registerCommand(new AuctionCommand());
if (ConfigMain.AttributesEnabled)
registerCommand(new AttributeCommand());
registerCommand(new DebugCommand());
}
public void registerCommand(CommandKamkeelBase command) {
@@ -134,10 +136,13 @@ public class CommandKamkeel extends CommandBase {
List<String> keys = new ArrayList<>(RequirementCheckerRegistry.getAllKeys());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("<effectName>")) {
List<String> keys = getSortedEffectNames();
List<String> keys = stripColorCodes(getSortedEffectNames());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("<ability>")) {
List<String> keys = getPlayerAbilityNames();
List<String> keys = stripColorCodes(getPlayerAbilityNames());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
} else if (usage.equals("<chain>")) {
List<String> keys = stripColorCodes(getPlayerChainNames());
return CommandBase.getListOfStringsMatchingLastWord(args, keys.toArray(new String[keys.size()]));
}
}
@@ -145,6 +150,14 @@ public class CommandKamkeel extends CommandBase {
return command.addTabCompletionOptions(sender, Arrays.copyOfRange(args, 1, args.length));
}
private static List<String> stripColorCodes(List<String> list) {
List<String> result = new ArrayList<>(list.size());
for (String s : list) {
result.add(s.replaceAll("\u00A7[0-9a-fk-or]", ""));
}
return result;
}
public CommandKamkeelBase getCommand(String[] args) {
if (args.length == 0)
return null;
Loaded 100 of 791 files, more files were not shown because too many files have changed in this diff. Show more