mirror of
https://github.com/KAMKEEL/CustomNPC-Plus.git
synced 2026-11-26 16:13:07 +00:00
851 files changed
+162965
-7132
No files matched your search
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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; }
|
||||
@@ -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>
|
||||
Generated
+1679
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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); }
|
||||
}
|
||||
@@ -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:
|
||||
<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; }
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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']
|
||||
@@ -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); }
|
||||
@@ -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>
|
||||
)
|
||||
@@ -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 }
|
||||
@@ -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,
|
||||
}
|
||||
})
|
||||
@@ -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"
|
||||
)
|
||||
@@ -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."
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -10,6 +10,8 @@
|
||||
.project
|
||||
/bin/
|
||||
/config/
|
||||
/copilot/
|
||||
/buildSrc/build/
|
||||
/crash-reports/
|
||||
/logs/
|
||||
options.txt
|
||||
@@ -39,3 +41,10 @@ addon.late.local.gradle.kts
|
||||
layout.json
|
||||
out
|
||||
run
|
||||
src/main/resources/assets/customnpcs/api
|
||||
df/
|
||||
tmp/
|
||||
src/test
|
||||
node_modules
|
||||
.github/pages-dist
|
||||
|
||||
@@ -2,3 +2,6 @@
|
||||
path = src/api
|
||||
url = https://github.com/KAMKEEL/CustomNPC-Plus-API.git
|
||||
branch = dev
|
||||
[submodule "gradle-plugins"]
|
||||
path = gradle-plugins
|
||||
url = https://github.com/bigguy345/dts-gradle-plugin
|
||||
@@ -0,0 +1,92 @@
|
||||
# CNPC+ 1.11 Beta - The Scripting Update
|
||||
|
||||
🟡 **In Testing**
|
||||
|
||||
|
||||
|
||||
## Features: ⚒️
|
||||
|
||||
- **Syntax Highlighting:**
|
||||
|
||||
> Full color-coded script editor. Keywords, types, variables, methods, strings, and comments are all distinct. Scope-aware coloring distinguishes local fields from globals and chained method calls.
|
||||
|
||||
|
||||
|
||||
- **Autocomplete:**
|
||||
|
||||
> Smart suggestions as you type. Context-aware for static vs instance access, shows method parameters, resolves chained calls, and suggests auto imports for classes. Frequently used members prioritized.
|
||||
|
||||
|
||||
|
||||
- **Error Detection:**
|
||||
|
||||
> Catch mistakes before running. Type mismatches, wrong arguments, missing methods, unused imports, duplicate definitions, and more -- all underlined with hover messages explaining the issue.
|
||||
|
||||
|
||||
|
||||
- **Hover Information:**
|
||||
|
||||
> Hover any symbol to see its type, documentation, and declaration. Works on methods, fields, classes, and even generics. Click to pin tooltips in place.
|
||||
|
||||
|
||||
|
||||
- **Script Editor Overhaul:**
|
||||
|
||||
> - **Line Numbers** - Gutter with current line highlighting.
|
||||
> - **Go To Line** - CTRL+G to jump to any line.
|
||||
> - **Search & Replace** - CTRL+F / CTRL+H with real-time highlighting.
|
||||
> - **Go To Definition** - CTRL+Click to jump to any symbol.
|
||||
> - **Smart Undo/Redo** - Word-level instead of character-level.
|
||||
> - **Line Operations** - Duplicate, delete, move up/down.
|
||||
> - **Comment Toggle** - CTRL+/ for selected lines.
|
||||
> - **Rename** - Rename a symbol across all occurrences.
|
||||
> - **Smooth Scrolling** - Eased scroll animation.
|
||||
> - **Indent Guides** - Scope-highlighted vertical indent lines.
|
||||
> - **Brace Matching** - Highlighted pairs, red for unclosed.
|
||||
> - **Smart Brackets** - Auto-pairing for `{}`, `()`, `[]`, `""`, `''`.
|
||||
> - **Fullscreen Mode** - Expand editor to fill the game window.
|
||||
> - **Shortcut Overlay** - View all keyboard shortcuts at a glance.
|
||||
|
||||
|
||||
|
||||
- **Java Scripting (Janino):**
|
||||
|
||||
> Write scripts in real Java compiled at runtime. Name methods after hooks for automatic wiring. Language selector per tab to switch between Java and JavaScript. External `.java` file support.
|
||||
|
||||
|
||||
|
||||
- **Client-Side Scripting:**
|
||||
|
||||
> Run scripts on the client for responsive experiences. Server-controlled -- off by default, must be explicitly enabled. Script files sync automatically on login and reload.
|
||||
|
||||
|
||||
|
||||
- **Cloner Tab Overhaul:**
|
||||
|
||||
> Folder-based organization for saved NPCs, items, and entries. Full-width directory browser for large collections. Improved tab navigation.
|
||||
|
||||
|
||||
|
||||
- **Addon API Support:**
|
||||
|
||||
> Addons can ship type definitions that load into the script editor automatically. Full autocomplete, hover info, and documentation for addon APIs. Addons can extend existing CNPC+ types with new methods.
|
||||
|
||||
|
||||
|
||||
- **Animation Improvements:**
|
||||
|
||||
> Data store for passing data across animation events and frames. New consumer-based task system for animation lifecycle. Expanded scripting API for animation control.
|
||||
|
||||
|
||||
|
||||
**Extras**
|
||||
|
||||
- Player Dialog Events now work like NPC Dialog Events.
|
||||
- Attack speed configuration for linked items.
|
||||
- Client-side balance prediction during Trader interactions.
|
||||
- Right-click cycling on multi-option NPC buttons (Hair, Eyes, Fur, etc.).
|
||||
- Fixed quest cooldown for MC Custom and RL Custom timer types.
|
||||
- Fixed Bard music restarting when opening dialogs.
|
||||
- Fixed NPC biome spawn settings not saving after editing.
|
||||
- Fixed block waypoint issues.
|
||||
- Fixed script config syncing between server and client.
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
# ✏️ CustomNPC+ 1.11 - The Scripting Update ✏️
|
||||
|
||||
---
|
||||
|
||||
The **Scripting Update** completely transforms how you write scripts in CNPC+! A brand new **Script Editor** with **syntax highlighting**, **autocomplete**, and **error detection** makes scripting feel like a real IDE. Write scripts in **Java** with the new Janino engine, enable **client-side scripting** for responsive experiences, and organize your Cloner with **folders**!
|
||||
|
||||
---
|
||||
|
||||
## Script Editor 📝
|
||||
|
||||
The script editor has been rebuilt from the ground up into a **full-featured code editor** right inside Minecraft.
|
||||
|
||||
### Writing Code
|
||||
|
||||
- **Syntax Highlighting** - Keywords, types, variables, methods, strings, and comments are all color-coded automatically. The editor understands your code -- local variables, global fields, and chained method calls each get their own color
|
||||
- **Autocomplete** - Start typing and get smart suggestions for methods, fields, and classes. Suggestions know whether you're in a static or instance context, and frequently used members appear first
|
||||
- **Auto Imports** - Type a class name and the editor suggests the correct import for you
|
||||
- **Error Detection** - Catch mistakes before you even run your script! Wrong argument types, missing methods, type mismatches, unused imports, and more are all underlined with detailed error messages on hover
|
||||
|
||||
> Hover over any symbol to see its **full type information**, documentation, and declaration -- just like a desktop IDE.
|
||||
|
||||
---
|
||||
|
||||
### Navigation
|
||||
|
||||
- **Go To Line** - `CTRL+G` jumps to any line instantly
|
||||
- **Search & Replace** - `CTRL+F` to search, `CTRL+H` to replace. All matches highlight in real-time
|
||||
- **Go To Definition** - `CTRL+Click` any method, field, or type to jump straight to its definition
|
||||
- **Fullscreen Mode** - Expand the editor to fill your entire game window for maximum workspace
|
||||
|
||||
### Editing
|
||||
|
||||
- **Undo/Redo** - Smart undo that works on whole words at a time, not individual characters
|
||||
- **Line Operations** - Duplicate lines with `CTRL+D`, delete lines, and move lines up or down with shortcuts
|
||||
- **Comment Toggle** - `CTRL+/` to comment or uncomment selected lines
|
||||
- **Rename** - Rename a variable or method and every occurrence updates at once
|
||||
- **Copy Whole Line** - Copy with nothing selected grabs the entire line
|
||||
- **Triple Click** - Select an entire line instantly
|
||||
|
||||
### Visual Polish
|
||||
|
||||
- **Line Numbers** - A clean gutter with line numbers and current line highlighting
|
||||
- **Smooth Scrolling** - Eased scroll animations for a polished feel
|
||||
- **Indent Guides** - Vertical lines show your code's nesting depth, with the current scope highlighted in green
|
||||
- **Brace Matching** - Matching `{}` braces light up, and unclosed braces turn red
|
||||
- **Smart Brackets** - Typing `{` automatically creates the closing `}` with correct indentation. Same for `()`, `[]`, `""`, and `''`
|
||||
- **Keyboard Shortcut Overlay** - Press a button to see all available shortcuts at a glance
|
||||
|
||||
---
|
||||
|
||||
## Java Scripting ☕
|
||||
|
||||
Write scripts in **real Java** instead of JavaScript! Powered by the **Janino** compiler, your Java code is compiled and runs natively.
|
||||
|
||||
- **Full Java Language** - Use classes, interfaces, enums, generics, lambdas, and everything you know from Java
|
||||
- **Automatic Hook Resolution** - Just name your methods after the hook you want (e.g., `init`, `tick`, `interact`) and they're wired up automatically
|
||||
- **Language Selector** - Each script tab has a dropdown to choose between JavaScript and Java. Mix and match across tabs
|
||||
- **External Files** - Write `.java` scripts in an external editor and they're loaded automatically
|
||||
|
||||
> Java and JavaScript scripts coexist side by side. Pick whichever language fits your workflow!
|
||||
|
||||
---
|
||||
|
||||
## Client-Side Scripting 🖥️
|
||||
|
||||
Scripts can now run **on the client** for responsive, visual experiences!
|
||||
|
||||
- **Server Controlled** - Server owners decide whether client scripting is allowed. Players can't enable it on their own
|
||||
- **Automatic Sync** - Script files are sent from the server to all connected clients on login, and re-synced whenever scripts are reloaded
|
||||
- **Safe by Default** - Client scripting is off by default and must be explicitly enabled in the server config
|
||||
|
||||
> Client-side scripts open the door to custom UI effects, visual feedback, and client-only hooks -- all while the server stays in full control.
|
||||
|
||||
---
|
||||
|
||||
## Cloner Tab Overhaul 📂
|
||||
|
||||
The Cloner now supports **folders** for organizing your saved NPCs, items, and entries!
|
||||
|
||||
- **Folder System** - Create folders and subfolders to keep your cloner organized however you like
|
||||
- **Full Screen Browser** - A new full-width directory view makes browsing large collections much easier
|
||||
- **Improved Tabs** - Better tab navigation for switching between cloner categories
|
||||
|
||||
---
|
||||
|
||||
## Addon API Support 📘
|
||||
|
||||
Addon developers can now ship **type definitions** alongside their mods, giving scripters full autocomplete and documentation for addon APIs!
|
||||
|
||||
- **Automatic Loading** - Any mod can include API definitions and they'll appear in the script editor automatically
|
||||
- **Patch Support** - Addons can extend existing CNPC+ types with new methods (e.g., a DBC addon adding `getDBCPlayer()` to the Player type)
|
||||
- **Full Documentation** - Parameter names, return types, and descriptions all show up in autocomplete and hover info
|
||||
|
||||
> If you're a scripter using addons, you get autocomplete for their APIs with zero setup. If you're an addon developer, just include your definitions and everything works.
|
||||
|
||||
---
|
||||
|
||||
## Animation Improvements 🎬
|
||||
|
||||
- **Data Store** - Animations can now store and pass data across events and frames for more complex animation logic
|
||||
- **Task System** - A new consumer-based system for reacting to animation lifecycle events, replacing the old approach
|
||||
- **Expanded API** - More animation control exposed to the scripting API
|
||||
|
||||
---
|
||||
|
||||
## Additional Changes 🔧
|
||||
|
||||
- **Player Dialog Events** - Now work the same way as NPC Dialog Events for consistency
|
||||
- **Linked Item Attack Speed** - Added attack speed configuration to linked items
|
||||
- **Trader Balance Preview** - Client-side balance prediction shows your expected balance during trades
|
||||
- **Right-Click Cycling** - Multi-option NPC buttons (Hair, Eyes, Fur, etc.) can now be right-clicked to cycle backwards
|
||||
- **Quest Cooldown Fix** - Fixed cooldown not working for MC Custom and RL Custom timer types
|
||||
- **Bard Music Fix** - Fixed music restarting or duplicating when opening dialogs
|
||||
- **Biome Spawn Fix** - Fixed NPC biome spawn settings not saving after editing
|
||||
- **Block Waypoint Fix** - Fixed issues with block waypoints
|
||||
- **Script Config Fix** - Fixed script configuration not syncing properly between server and client
|
||||
|
||||
---
|
||||
@@ -0,0 +1,368 @@
|
||||
# ⚔️ 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, set **traps** and **hazards**, chain abilities into devastating combos, 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. Supports both a **universal cooldown** and **per-ability cooldowns**
|
||||
- **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
|
||||
- **Invulnerability** - Make the caster invulnerable during Wind-up, Active, or both phases
|
||||
- **Ignore I-Frames** - Bypass Minecraft's damage immunity timer, allowing rapid consecutive hits
|
||||
- **Free on Cast** - The ability enters cooldown the moment it launches, freeing the caster while spawned entities (projectiles, zones, barriers) persist independently
|
||||
- **Magic Damage** - Abilities can deal magic damage as a separate damage type, with configurable damage values and split ratios
|
||||
|
||||
> 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. Air slams deal reduced damage based on required leap height
|
||||
- **Heavy Hit** - A single powerful melee strike with bonus knockback and a configurable hit delay
|
||||
- **Cutter** - A slashing arc attack in a cone. Configurable angle and reach
|
||||
|
||||
> 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. Energy projectiles use a **Variant System** — each base type (Orb, Beam, Disc) can be configured with variants like dual-fire or barrage patterns, all from within the same ability type.
|
||||
|
||||
### Orbs
|
||||
|
||||
Homing energy spheres that track their target through the air. Configurable with variants for dual or barrage firing patterns.
|
||||
|
||||
### Discs
|
||||
|
||||
Flat spinning projectiles with optional **boomerang** behavior. Supports both vertical and horizontal orientation.
|
||||
|
||||
### Beams
|
||||
|
||||
Sustained energy beams that connect the caster to their target. Supports a **Free Aim** mode for manual aiming without homing.
|
||||
|
||||
### Laser Shot
|
||||
|
||||
An **instant-fire** hitscan projectile with configurable width and speed. No homing — pure aim.
|
||||
|
||||
### 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. Supports custom offset anchors and a **Launch From Anchor** setting
|
||||
- **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
|
||||
- **Hit Type** - Choose how the projectile interacts with targets: **Single** (hits one), **Pierce** (passes through), or **Multi** (hits multiple)
|
||||
- **Lifespan** - Projectile speed, max age, and max travel distance (up to 150 blocks)
|
||||
- **Explosions** - Energy projectiles can detonate on impact with configurable explosion radius. Block damage can be toggled in the Energy Config
|
||||
|
||||
---
|
||||
|
||||
## Energy Barriers 🛡️
|
||||
|
||||
Defensive energy constructs that block incoming projectiles and attacks.
|
||||
|
||||
- **Dome** - A spherical barrier centered on the caster. Blocks incoming energy projectiles with configurable per-type damage multipliers, HP/durability, and duration
|
||||
- **Wall** - A placeable flat energy panel with configurable dimensions and height offset. Has an optional **launch mode** that fires the wall forward, dealing damage and knockback
|
||||
- **Shield** - A held energy panel that follows the caster's facing direction for directional blocking
|
||||
|
||||
**Barrier Properties:**
|
||||
- **HP & Durability** - Barriers have health and break when depleted
|
||||
- **Melee Vulnerability** - Barriers can be configured to take damage from melee attacks
|
||||
- **Damage Absorption** - Attacks aimed at the caster can be redirected to damage the barrier instead
|
||||
- **Ally/Target Filtering** - Configure which projectiles are blocked based on ownership
|
||||
- **Offset Support** - Position barriers with custom offsets from the caster
|
||||
|
||||
---
|
||||
|
||||
## Defensive Abilities 🏰
|
||||
|
||||
Reactive defensive stances that protect the caster when hit.
|
||||
|
||||
- **Guard** - Enter a defensive stance that **reduces incoming damage** by a configurable percentage. Lasts until duration expires or a max hit count is reached
|
||||
- **Counter** - Absorb incoming attacks and **counter-attack the attacker**. Counter damage can be a flat value or a percentage of the absorbed damage. Plays a counter-attack animation on each successful counter
|
||||
- **Dodge** - Fully **evade incoming attacks**, negating all damage. Plays randomized dodge animations from up to three configurable animation slots
|
||||
|
||||
> All defensive abilities support configurable duration and maximum hit counts before they break.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
- **Shockwave** - An AOE burst radiating outward from the caster, dealing damage and knockback in a configurable radius
|
||||
- **Sweeper** - A wide rotational sweep attack around the caster with configurable radius and rotation speed. Can run concurrently with other abilities in chains
|
||||
- **Vortex** - Creates a pulling force that drags nearby entities toward the center while dealing damage
|
||||
|
||||
---
|
||||
|
||||
## Hazards & Traps 🪤
|
||||
|
||||
Ground-based zone abilities for area denial and ambush tactics.
|
||||
|
||||
### Hazards
|
||||
|
||||
Persistent damaging areas that continuously hurt entities standing inside them. Configurable damage interval, zone count (up to 20), shape (circle or square), zone height, and duration. Can optionally affect the caster.
|
||||
|
||||
**Zone Visual Presets:** Default, Toxic, Inferno, Arcane, Electric, Frost — each with themed colors, particles, and visual effects.
|
||||
|
||||
### Traps
|
||||
|
||||
Proximity-triggered burst abilities that sit dormant until an entity enters the trigger radius. Support configurable arm time, multiple triggers before expiring, trigger cooldown, damage radius, and knockback. Traps can be **hidden** (invisible) until triggered, revealing with a brief burst effect.
|
||||
|
||||
**Trap Presets:**
|
||||
- **Hidden** - Minimal visibility, no effects — a pure stealth trap
|
||||
- **Venom** - Applies Poison with toxic green visuals
|
||||
- **Explosive** - Applies Fire with fiery orange particles
|
||||
- **Cursed** - Applies Weakness with purple arcane effects
|
||||
- **Shock** - Applies Mining Fatigue with blue electrical sparks
|
||||
- **Snare** - Applies Slowness with icy blue visuals
|
||||
|
||||
### Zone Visuals
|
||||
|
||||
Both hazards and traps share a rich visual system with configurable layers: ground fill, concentric rings, rotating borders, accents (static, swaying, or flickering), lightning arcs, and particle effects with multiple motion types (rising, drifting, sparks).
|
||||
|
||||
---
|
||||
|
||||
## Ability Effect 💫
|
||||
|
||||
A support ability for applying buffs, debuffs, healing, and custom effects to allies or enemies.
|
||||
|
||||
**Targeting:**
|
||||
- **Self** - Affect only the caster (self-buffs, self-healing)
|
||||
- **AOE Self** - Area-of-effect centered on the caster with a configurable radius
|
||||
|
||||
**Target Filter (AOE):**
|
||||
- **Allies** - Only affect friendly entities
|
||||
- **Enemies** - Only affect hostile entities
|
||||
- **All** - Affect everyone in range
|
||||
|
||||
Allies are determined by **Party** for players and **Faction** for NPCs. A toggle controls whether the caster is included in AOE effects.
|
||||
|
||||
**Effect Types:**
|
||||
- Flat and percentage-based healing (instant or over time)
|
||||
- Vanilla potion effects
|
||||
- Custom effects from the Custom Effect system
|
||||
- Mod-registered effect actions
|
||||
|
||||
**Built-in Variants:** Self Heal, Healing Aura, Poison Debuff.
|
||||
|
||||
---
|
||||
|
||||
## Custom Ability 🔧
|
||||
|
||||
A blank-slate ability type designed for **scripters** to build fully custom abilities through script hooks.
|
||||
|
||||
**Script Hooks:**
|
||||
- **Start** - Fired when the ability begins
|
||||
- **Execute** - Fired when entering the active phase
|
||||
- **Tick** - Fired every game tick with phase and tick count
|
||||
- **Complete** - Fired when the ability finishes
|
||||
- **Toggle / Toggle Tick** - For toggle-mode abilities with multiple states
|
||||
|
||||
**Features:**
|
||||
- Full telegraph control with all shape types (Circle, Ring, Line, Cone, Point, Square)
|
||||
- Configurable telegraph dimensions, colors, and duration
|
||||
- Supports both instant execution and multi-state toggle modes
|
||||
|
||||
---
|
||||
|
||||
## Burst System 🔁
|
||||
|
||||
Abilities can be configured to **fire multiple times in rapid succession** as a single use.
|
||||
|
||||
- **Burst Amount** - Number of additional repetitions after the initial cast
|
||||
- **Burst Delay** - Ticks between each burst iteration
|
||||
- **Replay Animations** - Optionally replay the wind-up animation on each burst
|
||||
- **Overlap Mode** - Previous entities can persist while the next burst fires, allowing stacking effects
|
||||
|
||||
> Burst is available on most ability types including energy projectiles, melee abilities, and movement abilities.
|
||||
|
||||
---
|
||||
|
||||
## Chained Abilities ⛓️
|
||||
|
||||
Chain multiple abilities together into **sequential combos** that execute one after another.
|
||||
|
||||
- **Ordered Entries** - Each entry in the chain references an ability with a configurable delay before it fires
|
||||
- **Wind-up All** - Optionally wind up all abilities simultaneously before the chain begins
|
||||
- **Chain Cooldown** - A single cooldown applied after the entire chain completes
|
||||
- **Chain Conditions** - Conditions checked once for the whole chain, not per-ability
|
||||
|
||||
### Concurrency
|
||||
|
||||
Specific ability types can be marked to run **concurrently** within a chain — executing alongside the primary ability instead of waiting in sequence. Concurrent-capable types include Effect, Hazard, Trap, and Sweeper.
|
||||
|
||||
> Chained abilities work with the ability hotbar and support live previewing in the editor.
|
||||
|
||||
---
|
||||
|
||||
## Telegraph System 📍
|
||||
|
||||
**Telegraphs** are visual ground indicators that warn players before an ability lands. They appear during the wind-up phase and transition into a warning state before 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
|
||||
- **Square** - Square area 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
|
||||
- **Height Handling** - Telegraphs properly handle ground and air positioning
|
||||
- **Custom Controls** - Full telegraph configuration available on Custom Abilities
|
||||
|
||||
> 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
|
||||
- **Dazed Animation** - Plays during the dazed recovery state
|
||||
- **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
|
||||
- **Multiple Animations** - Multiple animations can be registered under one common name
|
||||
|
||||
> 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. Supports both preset effect types and **manual potion IDs** for custom or modded effects with amplification up to 255.
|
||||
|
||||
**Available Preset Effects:**
|
||||
Fire, Slowness, Weakness, Poison, Wither, Blindness, Nausea, Hunger, Mining Fatigue
|
||||
|
||||
### Conditions
|
||||
|
||||
Abilities support a **condition system** that controls when they can be used. Each condition can be checked on the **Caster**, the **Target**, or **Both**.
|
||||
|
||||
**Condition Types:**
|
||||
- **HP Threshold** - Check if an entity's health is above, below, or equal to a value (supports flat or percentage)
|
||||
- **Hit Count** - Require the caster to have been hit a certain number of times within a time window
|
||||
- **Has Item** - Check if an entity is holding, wearing, or carrying a specific item
|
||||
- **Quest Completed** - Check if a player has completed a specific quest
|
||||
- **Has Effect** - Check if an entity has a specific custom effect applied
|
||||
|
||||
---
|
||||
|
||||
## Player Abilities 🧑
|
||||
|
||||
Players can unlock and use abilities with a full hotbar and management system!
|
||||
|
||||
### Ability Hotbar
|
||||
|
||||
The **Ability Hotbar** is a 12-slot bar for equipping and switching between unlocked abilities. Hold the **HUD Key** and use the **scroll wheel** to cycle through your equipped abilities. The hotbar displays ability icons with cooldown progress and supports horizontal or vertical layouts with 3, 5, or 7 visible slots.
|
||||
|
||||
Configure your hotbar through drag-and-drop in the **CNPC+ Inventory Ability Tab**, and customize its appearance in the **HUD Editor** under CNPC+ Inventory Settings.
|
||||
|
||||
### Player Features
|
||||
- **Unlock System** - Players receive abilities via scripting or commands
|
||||
- **Per-Ability Cooldowns** - Each ability can have its own cooldown in addition to the universal cooldown
|
||||
- **Cancel on Double-Tap** - Double-tap the ability key during wind-up to cancel and immediately enter cooldown
|
||||
- **Ability Visibility** - Hide or show specific abilities in the HUD and usage
|
||||
- **State Management** - Abilities are properly cancelled on logout, dimension change, death, and respawn. Movement input is suppressed during ability locks
|
||||
- **Flight Safety** - Abilities do not affect players who are flying
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
- **PlayerAbilityEvent** - Events for player ability actions
|
||||
|
||||
### Energy Projectile Scripting
|
||||
|
||||
Full scripting interfaces for all energy projectile types with 5 event hooks:
|
||||
- **Fired** - When the projectile launches
|
||||
- **Update** - Every tick during flight
|
||||
- **EntityImpact** - On hitting an entity
|
||||
- **BlockImpact** - On hitting a block
|
||||
- **Expired** - When the projectile's lifespan ends
|
||||
|
||||
### Ability Extender System
|
||||
|
||||
Register custom **lifecycle hooks** on abilities with the Ability Extender system:
|
||||
- **onAbilityStart** - When the ability begins
|
||||
- **onAbilityTick** - Every tick during execution
|
||||
- **onAbilityComplete** - When the ability finishes
|
||||
- **onAbilityDamage** - When the ability deals damage
|
||||
|
||||
Multiple extenders can be registered per ability. Ability scripts are **instanced** — every use gets its own fresh set of variables for optimal performance.
|
||||
|
||||
> 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, projectile visuals, burst patterns, and chained ability sequences 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 prebuilts` - List all built-in abilities
|
||||
- `/kam ability info <name>` - View ability details
|
||||
- `/kam ability delete <name>` - Delete a custom ability
|
||||
- `/kam ability reload` - Reload abilities from disk
|
||||
- `/kam ability give` - Give an ability to a player
|
||||
- `/kam ability remove` - Remove an ability from a player
|
||||
- `/kam ability giveChain` - Give a chained ability to a player
|
||||
- `/kam ability removeChain` - Remove a chained ability from a player
|
||||
- `/kam ability player` - Manage player abilities
|
||||
|
||||
---
|
||||
@@ -0,0 +1,167 @@
|
||||
# 🏪 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!
|
||||
|
||||
### 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 with a configurable **minimum listing price**.
|
||||
|
||||
> 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 configurable **cancellation penalty** is charged (default 10%).
|
||||
|
||||
> Claims expire after **20 days**. Make sure to collect your items and currency before they're gone!
|
||||
|
||||
### Search & Sorting
|
||||
|
||||
Find what you're looking for with search and sort tools. Search filters by both **item name** and **seller name** simultaneously.
|
||||
|
||||
**Sort Options:**
|
||||
- Newest
|
||||
- Ending Soon
|
||||
- Price (Low to High)
|
||||
- Price (High to Low)
|
||||
- Most Bids
|
||||
|
||||
### Notifications
|
||||
|
||||
Get notified immediately when:
|
||||
- Your item **sells**
|
||||
- You get **outbid**
|
||||
- You **win** an auction
|
||||
- Your auction **expires** with no bids
|
||||
- A **claim is ready** for pickup
|
||||
|
||||
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, or grant **unlimited slots** with the `customnpcs.auction.trades.unlimited` permission.
|
||||
|
||||
---
|
||||
|
||||
## 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!
|
||||
|
||||
**Blacklist Commands:**
|
||||
- `/kam auction blacklist add <item|mod|nbt> <value>` - Add to the blacklist
|
||||
- `/kam auction blacklist remove <item|mod|nbt> <value>` - Remove from the blacklist
|
||||
- `/kam auction blacklist list [item|mod|nbt]` - View blacklisted entries
|
||||
- `/kam auction blacklist reload` - Reload blacklist from config
|
||||
- `/kam auction blacklist check` - Check if your held item is blacklisted
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
---
|
||||
|
||||
## Admin Tools 🔨
|
||||
|
||||
### Admin Auction GUI
|
||||
|
||||
A dedicated management interface for server admins with three tabs:
|
||||
|
||||
- **Listings** - View and search all active auctions. Stop or cancel any listing
|
||||
- **Create** - Create server-managed listings with custom seller names, prices, and durations
|
||||
- **Claims** - Manage the global admin claims pool
|
||||
|
||||
### Auction Commands
|
||||
|
||||
**Player Commands:**
|
||||
- `/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. Each log type can be toggled individually.
|
||||
|
||||
---
|
||||
|
||||
## Scripting API 📜
|
||||
|
||||
Full event support for auction interactions. All events are **cancelable**, allowing scripts to intercept and control auction behavior:
|
||||
|
||||
- **CreateEvent** - Before an auction is created
|
||||
- **BidEvent** - Before a bid is placed
|
||||
- **BuyoutEvent** - Before an instant purchase
|
||||
- **CancelEvent** - Before a listing is cancelled
|
||||
- **ClaimEvent** - Before a claim is collected
|
||||
|
||||
---
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
# ✏️ CustomNPC+ 1.11 - The Scripting Update ✏️
|
||||
|
||||
---
|
||||
|
||||
The **Scripting Update** completely transforms how you write scripts in CNPC+! A brand new **Script Editor** with **syntax highlighting**, **autocomplete**, and **error detection** makes scripting feel like a real IDE. Write scripts in **Java** with the new Janino engine, enable **client-side scripting** for responsive experiences, and organize your Cloner with **folders**!
|
||||
|
||||
---
|
||||
|
||||
## Script Editor 📝
|
||||
|
||||
The script editor has been rebuilt from the ground up into a **full-featured code editor** right inside Minecraft.
|
||||
|
||||
### Writing Code
|
||||
|
||||
- **Syntax Highlighting** - Keywords, types, variables, methods, strings, and comments are all color-coded automatically. The editor understands your code -- local variables, global fields, and chained method calls each get their own color
|
||||
- **Autocomplete** - Start typing and get smart suggestions for methods, fields, and classes. Suggestions know whether you're in a static or instance context, and frequently used members appear first. Smart cursor placement inserts methods with the cursor between parentheses when parameters exist
|
||||
- **Auto Imports** - Type a class name and the editor suggests the correct import for you
|
||||
- **Error Detection** - Catch mistakes before you even run your script! Wrong argument types, missing methods, type mismatches, unused imports, and more are all underlined with detailed error messages on hover
|
||||
- **ECMAScript 5.1 Globals** - Built-in objects like `Math`, `JSON`, `Date`, and `Number` are recognized automatically in JavaScript mode
|
||||
- **Global Script Variables** - Variables like `npc`, `world`, and `event` are recognized in the syntax highlighter and autocomplete as global definitions
|
||||
|
||||
> Hover over any symbol to see its **full type information**, documentation, and declaration -- just like a desktop IDE. Hover tooltips render **JSDoc with markdown formatting**, headings, and code blocks, and support **scrolling and panning** for long documentation.
|
||||
|
||||
---
|
||||
|
||||
### Navigation
|
||||
|
||||
- **Go To Line** - `CTRL+G` jumps to any line instantly
|
||||
- **Search & Replace** - `CTRL+F` to search, `CTRL+H` to replace. All matches highlight in real-time
|
||||
- **Go To Definition** - `CTRL+Click` any method, field, or type to jump straight to its definition
|
||||
- **Fullscreen Mode** - Expand the editor to fill your entire game window for maximum workspace
|
||||
|
||||
### Editing
|
||||
|
||||
- **Undo/Redo** - Smart undo that works on whole words at a time, not individual characters
|
||||
- **Line Operations** - Duplicate lines with `CTRL+D`, delete lines, and move lines up or down with shortcuts
|
||||
- **Comment Toggle** - `CTRL+/` to comment or uncomment selected lines
|
||||
- **Rename** - Rename a variable or method and every occurrence updates at once
|
||||
- **Copy Whole Line** - Copy with nothing selected grabs the entire line
|
||||
- **Triple Click** - Select an entire line instantly
|
||||
|
||||
### Visual Polish
|
||||
|
||||
- **Line Numbers** - A clean gutter with line numbers and current line highlighting
|
||||
- **Smooth Scrolling** - Eased scroll animations for a polished feel
|
||||
- **Indent Guides** - Vertical lines show your code's nesting depth, with the current scope highlighted in green
|
||||
- **Brace Matching** - Matching `{}` braces light up, and unclosed braces turn red
|
||||
- **Smart Brackets** - Typing `{` automatically creates the closing `}` with correct indentation. Same for `()`, `[]`, `""`, and `''`
|
||||
- **Resizable Panels** - Autocomplete and hover info panels can be resized and panned to fit your workspace
|
||||
- **Keyboard Shortcut Overlay** - Press a button to see all available shortcuts at a glance
|
||||
|
||||
---
|
||||
|
||||
## Java Scripting ☕
|
||||
|
||||
Write scripts in **real Java** instead of JavaScript! Powered by the **Janino** compiler, your Java code is compiled and runs natively.
|
||||
|
||||
- **Full Java Language** - Use classes, interfaces, enums, generics, lambdas, and everything you know from Java
|
||||
- **Automatic Hook Resolution** - Just name your methods after the hook you want (e.g., `init`, `tick`, `interact`) and they're wired up automatically
|
||||
- **Language Selector** - Each script tab has a dropdown to choose between JavaScript and Java. Mix and match across tabs
|
||||
- **External Files** - Write `.java` scripts in an external editor and they're loaded automatically
|
||||
|
||||
> Java and JavaScript scripts coexist side by side. Pick whichever language fits your workflow!
|
||||
|
||||
---
|
||||
|
||||
## Client-Side Scripting 🖥️
|
||||
|
||||
Scripts can now run **on the client** for responsive, visual experiences!
|
||||
|
||||
- **Server Controlled** - Server owners decide whether client scripting is allowed. Players can't enable it on their own
|
||||
- **Automatic Sync** - Script files are sent from the server to all connected clients on login, and re-synced whenever scripts are reloaded
|
||||
- **Safe by Default** - Client scripting is off by default and must be explicitly enabled in the server config
|
||||
|
||||
> Client-side scripts open the door to custom UI effects, visual feedback, and client-only hooks -- all while the server stays in full control.
|
||||
|
||||
---
|
||||
|
||||
## Cloner Tab Overhaul 📂
|
||||
|
||||
The Cloner now supports **folders** for organizing your saved NPCs, items, and entries!
|
||||
|
||||
- **Folder System** - Create folders and subfolders to keep your cloner organized however you like
|
||||
- **Full Screen Browser** - A new full-width directory view makes browsing large collections much easier
|
||||
- **Improved Tabs** - Better tab navigation for switching between cloner categories
|
||||
|
||||
---
|
||||
|
||||
## Addon API Support 📘
|
||||
|
||||
Addon developers can now ship **type definitions** alongside their mods, giving scripters full autocomplete and documentation for addon APIs!
|
||||
|
||||
- **Automatic Loading** - Any mod can include API definitions and they'll appear in the script editor automatically
|
||||
- **Patch Support** - Addons can extend existing CNPC+ types with new methods (e.g., a DBC addon adding `getDBCPlayer()` to the Player type)
|
||||
- **Full Documentation** - Parameter names, return types, and descriptions all show up in autocomplete and hover info
|
||||
|
||||
> If you're a scripter using addons, you get autocomplete for their APIs with zero setup. If you're an addon developer, just include your definitions and everything works.
|
||||
|
||||
---
|
||||
|
||||
## Animation Improvements 🎬
|
||||
|
||||
- **Data Store** - Animations can now store and pass data across events and frames for more complex animation logic
|
||||
- **Task System** - A new consumer-based system for reacting to animation lifecycle events, replacing the old approach
|
||||
- **Expanded API** - More animation control exposed to the scripting API
|
||||
|
||||
---
|
||||
|
||||
## Animated Textures 🖼️
|
||||
|
||||
Items and effects now support **frame-based animated textures**!
|
||||
|
||||
- **Linked & Scripted Items** - Configure animated textures with custom frame count and frame time
|
||||
- **Custom Effects** - Custom effect icons support animation with the same frame system
|
||||
- **Configurable** - Set frames per row, ticks per frame, and interpolation between frames
|
||||
|
||||
---
|
||||
|
||||
## NPC API Additions 🧩
|
||||
|
||||
New scripting API properties for finer control over NPC behavior and appearance:
|
||||
|
||||
- **Hitbox Data** - Scale NPC hitbox width and height independently via `IHitboxData`
|
||||
- **Tint Data** - Control hurt tint (damage flash) and apply persistent color tints with alpha via `ITintData`
|
||||
- **Behavior Properties** - Sprint, swim, door interaction, and walking range are now scriptable
|
||||
- **Sound Control** - Full sound management via `ISound` with volume, pitch, repeat, and position
|
||||
- **Error Reporting** - Script action exceptions now report to the Script Console with full stack traces instead of failing silently
|
||||
|
||||
---
|
||||
|
||||
## Additional Changes 🔧
|
||||
|
||||
- **Player Dialog Events** - Now work the same way as NPC Dialog Events for consistency
|
||||
- **Linked Item Attack Speed** - Added attack speed configuration to linked items
|
||||
- **Trader Balance Preview** - Client-side balance prediction shows your expected balance during trades
|
||||
- **Right-Click Cycling** - Multi-option NPC buttons (Hair, Eyes, Fur, etc.) can now be right-clicked to cycle backwards
|
||||
- **Quest Cooldown Fix** - Fixed cooldown not working for MC Custom and RL Custom timer types
|
||||
- **Bard Music Fix** - Fixed music restarting or duplicating when opening dialogs
|
||||
- **Biome Spawn Fix** - Fixed NPC biome spawn settings not saving after editing
|
||||
- **Block Waypoint Fix** - Fixed issues with block waypoints
|
||||
- **Script Config Fix** - Fixed script configuration not syncing properly between server and client
|
||||
|
||||
---
|
||||
+69
-1
@@ -3,9 +3,10 @@
|
||||
plugins {
|
||||
id 'com.gtnewhorizons.gtnhconvention'
|
||||
id 'idea'
|
||||
id "dts.typescript-generator"
|
||||
}
|
||||
|
||||
version = "1.10.3"
|
||||
version = "1.11"
|
||||
group= "kamkeel.customnpc-plus"
|
||||
archivesBaseName = "CustomNPC-Plus"
|
||||
|
||||
@@ -31,6 +32,21 @@ tasks.create('buildNoMixin', Exec) {
|
||||
commandLine gradleWrapper, 'build', '-Pnomixin'
|
||||
}
|
||||
|
||||
// No Nashorn Run Tasks
|
||||
tasks.create('runClientNoNashorn', Exec) {
|
||||
description 'Runs the client without Nashorn'
|
||||
group 'CustomNPC+'
|
||||
workingDir project.rootDir
|
||||
commandLine gradleWrapper, 'runClient', '-PnoNashorn'
|
||||
}
|
||||
|
||||
tasks.create('runServerNoNashorn', Exec) {
|
||||
description 'Runs the server without Nashorn'
|
||||
group 'CustomNPC+'
|
||||
workingDir project.rootDir
|
||||
commandLine gradleWrapper, 'runServer', '-PnoNashorn'
|
||||
}
|
||||
|
||||
sourceSets.main.java {
|
||||
def apiDir = file('src/api/java')
|
||||
|
||||
@@ -41,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'
|
||||
+12
-2
@@ -35,8 +35,18 @@
|
||||
*/
|
||||
def embedMixin = !project.hasProperty("nomixin");
|
||||
dependencies {
|
||||
runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.5.4-GTNH:dev")
|
||||
runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946")
|
||||
runtimeOnlyNonPublishable("com.github.GTNewHorizons:NotEnoughItems:2.8.44-GTNH:dev")
|
||||
if (!project.hasProperty("noNashorn")) {
|
||||
runtimeOnlyNonPublishable("curse.maven:Nashorn-374413:2924946")
|
||||
}
|
||||
|
||||
// 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"))
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
|
||||
if(embedMixin){
|
||||
// Normal Jar will include built in Mixins
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Vendored
+126
@@ -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;
|
||||
}
|
||||
Vendored
+36
@@ -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;
|
||||
}
|
||||
Vendored
+168
@@ -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;
|
||||
}
|
||||
Vendored
+81
@@ -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
@@ -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;
|
||||
}
|
||||
Vendored
+100
@@ -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;
|
||||
}
|
||||
Vendored
+128
@@ -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;
|
||||
}
|
||||
Vendored
+74
@@ -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;
|
||||
}
|
||||
Vendored
+105
@@ -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;
|
||||
|
||||
}
|
||||
Vendored
+94
@@ -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;
|
||||
}
|
||||
Vendored
+82
@@ -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;
|
||||
}
|
||||
Submodule
+1
Submodule gradle-plugins added at 19dc9a8361.
+1
-1
@@ -199,7 +199,7 @@ disableCheckstyle = true
|
||||
# ideaCheckSpotlessOnBuild = true
|
||||
|
||||
# Non-GTNH properties
|
||||
modVersion = 1.10.3
|
||||
modVersion = 1.11.0
|
||||
|
||||
# Increase Gradle's JVM memory usage to avoid daemon expiration due to
|
||||
# insufficient heap space on CI builds.
|
||||
|
||||
@@ -5,4 +5,7 @@ repositories {
|
||||
name = "sponge"
|
||||
url = "https://repo.spongepowered.org/maven/"
|
||||
}
|
||||
flatDir {
|
||||
dirs 'lib'
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -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: 305a3778c8...efce1a99b7.
@@ -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,9 +2,16 @@ package foxz.command;
|
||||
|
||||
import net.minecraft.command.CommandBase;
|
||||
import net.minecraft.command.ICommandSender;
|
||||
import net.minecraft.util.ChatComponentText;
|
||||
import net.minecraft.util.EnumChatFormatting;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @deprecated The /noppes command is deprecated and no longer supported.
|
||||
* Please use the /kam command instead for all CNPC+ operations.
|
||||
*/
|
||||
@Deprecated
|
||||
public class CommandNoppes extends CommandBase {
|
||||
|
||||
public CmdNoppes noppes = new CmdNoppes(this);
|
||||
@@ -21,6 +28,15 @@ public class CommandNoppes extends CommandBase {
|
||||
|
||||
@Override
|
||||
public void processCommand(ICommandSender var1, String[] var2) {
|
||||
// Send deprecation warning
|
||||
var1.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + "[DEPRECATED] " +
|
||||
EnumChatFormatting.YELLOW + "The /noppes command is deprecated and no longer supported."));
|
||||
var1.addChatMessage(new ChatComponentText(EnumChatFormatting.YELLOW +
|
||||
"Please use " + EnumChatFormatting.GREEN + "/kam" + EnumChatFormatting.YELLOW + " commands instead."));
|
||||
var1.addChatMessage(new ChatComponentText(EnumChatFormatting.GRAY +
|
||||
"Type " + EnumChatFormatting.WHITE + "/kam help" + EnumChatFormatting.GRAY + " for available commands."));
|
||||
|
||||
// Still execute the command for backwards compatibility
|
||||
noppes.processCommand(var1, var2);
|
||||
}
|
||||
|
||||
|
||||
@@ -31,9 +31,6 @@ public class Market {
|
||||
NBTTagCompound roleCompound = r.writeNBT(new NBTTagCompound());
|
||||
roleCompound.setString("SaveName", name);
|
||||
putMarketCache(name, roleCompound);
|
||||
if (r.recordHistory)
|
||||
return;
|
||||
|
||||
saveFile(roleCompound);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,597 @@
|
||||
package kamkeel.npcs.client.renderer;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.entity.EntityAbilityBeam;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.util.Vec3;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.util.ArrayList;
|
||||
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 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, proximityAlpha);
|
||||
restoreRenderState();
|
||||
return;
|
||||
}
|
||||
|
||||
// Get trail points (these are RELATIVE to origin)
|
||||
List<Vec3> trail = beam.getTrailPoints();
|
||||
if (trail.isEmpty()) {
|
||||
restoreRenderState();
|
||||
return;
|
||||
}
|
||||
|
||||
// Get interpolated head offset
|
||||
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;
|
||||
|
||||
// Get beam properties
|
||||
float beamWidth = beam.getBeamWidth();
|
||||
float headSize = beam.getHeadSize();
|
||||
int innerColor = beam.getInnerColor();
|
||||
int outerColor = beam.getOuterColor();
|
||||
float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
|
||||
|
||||
// Render everything relative to origin position
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(renderOriginX, renderOriginY, renderOriginZ);
|
||||
|
||||
// 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, beam.getInnerAlpha() * proximityAlpha);
|
||||
}
|
||||
|
||||
float innerAlpha = beam.getInnerAlpha() * proximityAlpha;
|
||||
|
||||
// Render trail segments with smooth connections (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 head at interpolated offset position
|
||||
renderHead(beam, headOffsetX, headOffsetY, headOffsetZ, headSize, innerColor, outerColor, outerAlpha, innerAlpha, partialTicks);
|
||||
|
||||
GL11.glPopMatrix();
|
||||
|
||||
restoreRenderState();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 proximityAlpha) {
|
||||
float headSize = beam.getHeadSize();
|
||||
float chargeProgress = beam.getInterpolatedChargeProgress(partialTicks);
|
||||
float size = headSize * chargeProgress;
|
||||
|
||||
if (size <= 0.01f) return;
|
||||
|
||||
int innerColor = beam.getInnerColor();
|
||||
int outerColor = beam.getOuterColor();
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(x, y, z);
|
||||
|
||||
// Pulsing effect
|
||||
float pulseTime = beam.ticksExisted + partialTicks;
|
||||
float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.08f;
|
||||
float scale = size * (1.0f + scaleModifier);
|
||||
|
||||
// Render lightning during charging if enabled
|
||||
if (beam.hasLightningEffect()) {
|
||||
renderAttachedLightning(beam, 0.6f * 0.5f, scale);
|
||||
}
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(scale, scale, scale);
|
||||
|
||||
// Inner scale defines the core size
|
||||
float innerScale = 0.6f;
|
||||
|
||||
// Render outer glow only if enabled
|
||||
if (beam.isOuterColorEnabled()) {
|
||||
float outerScale = innerScale + beam.getOuterColorWidth();
|
||||
float outerAlpha = beam.getOuterColorAlpha() * proximityAlpha;
|
||||
GL11.glDepthMask(false);
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(outerScale, outerScale, outerScale);
|
||||
renderCube(outerColor, outerAlpha, 0.5f);
|
||||
GL11.glPopMatrix();
|
||||
GL11.glDepthMask(true);
|
||||
}
|
||||
|
||||
// Render inner core
|
||||
GL11.glScalef(innerScale, innerScale, innerScale);
|
||||
renderCube(innerColor, beam.getInnerAlpha() * proximityAlpha, 0.5f);
|
||||
|
||||
GL11.glPopMatrix();
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, float innerAlpha) {
|
||||
GL11.glPushMatrix();
|
||||
// Already at origin (0,0,0)
|
||||
|
||||
// Inner scale defines the core size
|
||||
float innerScale = 0.6f;
|
||||
|
||||
// Render outer glow only if enabled
|
||||
// outerColorWidth is an additive offset from inner size
|
||||
if (outerColorEnabled) {
|
||||
float outerScale = innerScale + outerColorWidth;
|
||||
GL11.glDepthMask(false);
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(size * outerScale, size * outerScale, size * outerScale);
|
||||
renderCube(outerColor, outerAlpha, 0.5f);
|
||||
GL11.glPopMatrix();
|
||||
GL11.glDepthMask(true);
|
||||
}
|
||||
|
||||
// Render inner core (solid)
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(size * innerScale, size * innerScale, size * innerScale);
|
||||
renderCube(innerColor, innerAlpha, 0.5f);
|
||||
GL11.glPopMatrix();
|
||||
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the beam trail with smooth connections between segments.
|
||||
* 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, float innerAlpha) {
|
||||
if (trail.size() < 2) return;
|
||||
|
||||
int trailSize = trail.size();
|
||||
|
||||
// Pre-compute perpendicular frames at each point
|
||||
// At connection points, average the perpendiculars for smooth transitions
|
||||
List<double[]> perpFrames = computePerpendiculars(trail);
|
||||
|
||||
// Inner scale defines the core width
|
||||
float innerScale = 0.6f;
|
||||
float innerWidth = width * innerScale;
|
||||
|
||||
// Render outer glow trail (wider, translucent) - only if enabled
|
||||
// outerColorWidth is an additive offset from inner width
|
||||
if (outerColorEnabled) {
|
||||
float outerWidth = innerWidth + outerColorWidth * width;
|
||||
GL11.glDepthMask(false);
|
||||
renderTrailTube(trail, perpFrames, outerWidth, outerColor, 0.3f, true);
|
||||
GL11.glDepthMask(true);
|
||||
}
|
||||
|
||||
// Render inner core trail
|
||||
renderTrailTube(trail, perpFrames, innerWidth, innerColor, innerAlpha, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render trail with fading effect (comet style) for non-anchored beams.
|
||||
* 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, float innerAlpha) {
|
||||
if (trail.size() < 2) return;
|
||||
|
||||
List<Integer> ages = beam.getTrailPointAges();
|
||||
int fadeTime = beam.getTrailFadeTime();
|
||||
|
||||
// Pre-compute perpendicular frames
|
||||
List<double[]> perpFrames = computePerpendiculars(trail);
|
||||
|
||||
// Inner scale defines the core width
|
||||
float innerScale = 0.6f;
|
||||
float innerWidth = width * innerScale;
|
||||
|
||||
// Render outer glow trail with fading
|
||||
if (outerColorEnabled) {
|
||||
float outerWidth = innerWidth + outerColorWidth * width;
|
||||
GL11.glDepthMask(false);
|
||||
renderFadingTrailTube(trail, perpFrames, ages, fadeTime, outerWidth, outerColor, 0.3f);
|
||||
GL11.glDepthMask(true);
|
||||
}
|
||||
|
||||
// Render inner core trail with fading
|
||||
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) {
|
||||
float[] rgb = extractRGB(color);
|
||||
float r = rgb[0], g = rgb[1], b = rgb[2];
|
||||
float halfWidth = width * 0.5f;
|
||||
int size = trail.size();
|
||||
|
||||
Tessellator tess = Tessellator.instance;
|
||||
tess.startDrawingQuads();
|
||||
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
Vec3 p1 = trail.get(i);
|
||||
Vec3 p2 = trail.get(i + 1);
|
||||
double[] frame1 = perpFrames.get(i);
|
||||
double[] frame2 = perpFrames.get(i + 1);
|
||||
|
||||
// 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 = 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;
|
||||
|
||||
// Skip fully faded segments
|
||||
if (alpha1 <= 0.01f && alpha2 <= 0.01f) continue;
|
||||
|
||||
// Calculate 4 corners at start
|
||||
double s1x = p1.xCoord - frame1[0] * halfWidth - frame1[3] * halfWidth;
|
||||
double s1y = p1.yCoord - frame1[1] * halfWidth - frame1[4] * halfWidth;
|
||||
double s1z = p1.zCoord - frame1[2] * halfWidth - frame1[5] * halfWidth;
|
||||
|
||||
double s2x = p1.xCoord + frame1[0] * halfWidth - frame1[3] * halfWidth;
|
||||
double s2y = p1.yCoord + frame1[1] * halfWidth - frame1[4] * halfWidth;
|
||||
double s2z = p1.zCoord + frame1[2] * halfWidth - frame1[5] * halfWidth;
|
||||
|
||||
double s3x = p1.xCoord + frame1[0] * halfWidth + frame1[3] * halfWidth;
|
||||
double s3y = p1.yCoord + frame1[1] * halfWidth + frame1[4] * halfWidth;
|
||||
double s3z = p1.zCoord + frame1[2] * halfWidth + frame1[5] * halfWidth;
|
||||
|
||||
double s4x = p1.xCoord - frame1[0] * halfWidth + frame1[3] * halfWidth;
|
||||
double s4y = p1.yCoord - frame1[1] * halfWidth + frame1[4] * halfWidth;
|
||||
double s4z = p1.zCoord - frame1[2] * halfWidth + frame1[5] * halfWidth;
|
||||
|
||||
// Calculate 4 corners at end
|
||||
double e1x = p2.xCoord - frame2[0] * halfWidth - frame2[3] * halfWidth;
|
||||
double e1y = p2.yCoord - frame2[1] * halfWidth - frame2[4] * halfWidth;
|
||||
double e1z = p2.zCoord - frame2[2] * halfWidth - frame2[5] * halfWidth;
|
||||
|
||||
double e2x = p2.xCoord + frame2[0] * halfWidth - frame2[3] * halfWidth;
|
||||
double e2y = p2.yCoord + frame2[1] * halfWidth - frame2[4] * halfWidth;
|
||||
double e2z = p2.zCoord + frame2[2] * halfWidth - frame2[5] * halfWidth;
|
||||
|
||||
double e3x = p2.xCoord + frame2[0] * halfWidth + frame2[3] * halfWidth;
|
||||
double e3y = p2.yCoord + frame2[1] * halfWidth + frame2[4] * halfWidth;
|
||||
double e3z = p2.zCoord + frame2[2] * halfWidth + frame2[5] * halfWidth;
|
||||
|
||||
double e4x = p2.xCoord - frame2[0] * halfWidth + frame2[3] * halfWidth;
|
||||
double e4y = p2.yCoord - frame2[1] * halfWidth + frame2[4] * halfWidth;
|
||||
double e4z = p2.zCoord - frame2[2] * halfWidth + frame2[5] * halfWidth;
|
||||
|
||||
// Bottom face
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s1x, s1y, s1z);
|
||||
tess.addVertex(s2x, s2y, s2z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha2);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
|
||||
// Top face
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s4x, s4y, s4z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha2);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s3x, s3y, s3z);
|
||||
|
||||
// Left face
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s1x, s1y, s1z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha2);
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s4x, s4y, s4z);
|
||||
|
||||
// Right face
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s2x, s2y, s2z);
|
||||
tess.addVertex(s3x, s3y, s3z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha2);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
}
|
||||
|
||||
tess.draw();
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute perpendicular frames for each point in the trail.
|
||||
* At interior points, average the perpendiculars from both directions for smooth curves.
|
||||
* Returns list of [horzX, horzY, horzZ, vertX, vertY, vertZ] for each point.
|
||||
*/
|
||||
private List<double[]> computePerpendiculars(List<Vec3> trail) {
|
||||
List<double[]> frames = new ArrayList<>();
|
||||
int size = trail.size();
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
double[] frame = new double[6];
|
||||
|
||||
// Calculate direction at this point
|
||||
double dx, dy, dz;
|
||||
if (i == 0) {
|
||||
// First point - use direction to next
|
||||
Vec3 p1 = trail.get(0);
|
||||
Vec3 p2 = trail.get(1);
|
||||
dx = p2.xCoord - p1.xCoord;
|
||||
dy = p2.yCoord - p1.yCoord;
|
||||
dz = p2.zCoord - p1.zCoord;
|
||||
} else if (i == size - 1) {
|
||||
// Last point - use direction from previous
|
||||
Vec3 p1 = trail.get(size - 2);
|
||||
Vec3 p2 = trail.get(size - 1);
|
||||
dx = p2.xCoord - p1.xCoord;
|
||||
dy = p2.yCoord - p1.yCoord;
|
||||
dz = p2.zCoord - p1.zCoord;
|
||||
} else {
|
||||
// Interior point - average directions
|
||||
Vec3 p0 = trail.get(i - 1);
|
||||
Vec3 p1 = trail.get(i);
|
||||
Vec3 p2 = trail.get(i + 1);
|
||||
double dx1 = p1.xCoord - p0.xCoord;
|
||||
double dy1 = p1.yCoord - p0.yCoord;
|
||||
double dz1 = p1.zCoord - p0.zCoord;
|
||||
double dx2 = p2.xCoord - p1.xCoord;
|
||||
double dy2 = p2.yCoord - p1.yCoord;
|
||||
double dz2 = p2.zCoord - p1.zCoord;
|
||||
// Average the directions
|
||||
dx = (dx1 + dx2) * 0.5;
|
||||
dy = (dy1 + dy2) * 0.5;
|
||||
dz = (dz1 + dz2) * 0.5;
|
||||
}
|
||||
|
||||
// Normalize direction
|
||||
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
if (len > 0.001) {
|
||||
dx /= len;
|
||||
dy /= len;
|
||||
dz /= len;
|
||||
} else {
|
||||
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;
|
||||
}
|
||||
|
||||
// Cross product for horizontal perpendicular
|
||||
double horzX = dy * upZ - dz * upY;
|
||||
double horzY = dz * upX - dx * upZ;
|
||||
double horzZ = dx * upY - dy * upX;
|
||||
double horzLen = Math.sqrt(horzX * horzX + horzY * horzY + horzZ * horzZ);
|
||||
if (horzLen > 0) {
|
||||
horzX /= horzLen;
|
||||
horzY /= horzLen;
|
||||
horzZ /= horzLen;
|
||||
}
|
||||
|
||||
// Cross product for vertical perpendicular
|
||||
double vertX = dy * horzZ - dz * horzY;
|
||||
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;
|
||||
frames.add(frame);
|
||||
}
|
||||
|
||||
return frames;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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[] rgb = extractRGB(color);
|
||||
float r = rgb[0], g = rgb[1], b = rgb[2];
|
||||
float halfWidth = width * 0.5f;
|
||||
int size = trail.size();
|
||||
|
||||
Tessellator tess = Tessellator.instance;
|
||||
tess.startDrawingQuads();
|
||||
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
Vec3 p1 = trail.get(i);
|
||||
Vec3 p2 = trail.get(i + 1);
|
||||
double[] frame1 = perpFrames.get(i);
|
||||
double[] frame2 = perpFrames.get(i + 1);
|
||||
|
||||
// Calculate alpha based on position (fade from start or constant)
|
||||
float alpha1, alpha2;
|
||||
if (fadeFromStart) {
|
||||
float progress1 = (float) i / size;
|
||||
float progress2 = (float) (i + 1) / size;
|
||||
alpha1 = baseAlpha * progress1;
|
||||
alpha2 = baseAlpha * progress2;
|
||||
} else {
|
||||
alpha1 = baseAlpha;
|
||||
alpha2 = baseAlpha;
|
||||
}
|
||||
|
||||
// Calculate 4 corners at start
|
||||
double s1x = p1.xCoord - frame1[0] * halfWidth - frame1[3] * halfWidth;
|
||||
double s1y = p1.yCoord - frame1[1] * halfWidth - frame1[4] * halfWidth;
|
||||
double s1z = p1.zCoord - frame1[2] * halfWidth - frame1[5] * halfWidth;
|
||||
|
||||
double s2x = p1.xCoord + frame1[0] * halfWidth - frame1[3] * halfWidth;
|
||||
double s2y = p1.yCoord + frame1[1] * halfWidth - frame1[4] * halfWidth;
|
||||
double s2z = p1.zCoord + frame1[2] * halfWidth - frame1[5] * halfWidth;
|
||||
|
||||
double s3x = p1.xCoord + frame1[0] * halfWidth + frame1[3] * halfWidth;
|
||||
double s3y = p1.yCoord + frame1[1] * halfWidth + frame1[4] * halfWidth;
|
||||
double s3z = p1.zCoord + frame1[2] * halfWidth + frame1[5] * halfWidth;
|
||||
|
||||
double s4x = p1.xCoord - frame1[0] * halfWidth + frame1[3] * halfWidth;
|
||||
double s4y = p1.yCoord - frame1[1] * halfWidth + frame1[4] * halfWidth;
|
||||
double s4z = p1.zCoord - frame1[2] * halfWidth + frame1[5] * halfWidth;
|
||||
|
||||
// Calculate 4 corners at end
|
||||
double e1x = p2.xCoord - frame2[0] * halfWidth - frame2[3] * halfWidth;
|
||||
double e1y = p2.yCoord - frame2[1] * halfWidth - frame2[4] * halfWidth;
|
||||
double e1z = p2.zCoord - frame2[2] * halfWidth - frame2[5] * halfWidth;
|
||||
|
||||
double e2x = p2.xCoord + frame2[0] * halfWidth - frame2[3] * halfWidth;
|
||||
double e2y = p2.yCoord + frame2[1] * halfWidth - frame2[4] * halfWidth;
|
||||
double e2z = p2.zCoord + frame2[2] * halfWidth - frame2[5] * halfWidth;
|
||||
|
||||
double e3x = p2.xCoord + frame2[0] * halfWidth + frame2[3] * halfWidth;
|
||||
double e3y = p2.yCoord + frame2[1] * halfWidth + frame2[4] * halfWidth;
|
||||
double e3z = p2.zCoord + frame2[2] * halfWidth + frame2[5] * halfWidth;
|
||||
|
||||
double e4x = p2.xCoord - frame2[0] * halfWidth + frame2[3] * halfWidth;
|
||||
double e4y = p2.yCoord - frame2[1] * halfWidth + frame2[4] * halfWidth;
|
||||
double e4z = p2.zCoord - frame2[2] * halfWidth + frame2[5] * halfWidth;
|
||||
|
||||
// Bottom face (s1-s2-e2-e1)
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s1x, s1y, s1z);
|
||||
tess.addVertex(s2x, s2y, s2z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha2);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
|
||||
// Top face (s4-e4-e3-s3)
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s4x, s4y, s4z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha2);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s3x, s3y, s3z);
|
||||
|
||||
// Left face (s1-e1-e4-s4)
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s1x, s1y, s1z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha2);
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s4x, s4y, s4z);
|
||||
|
||||
// Right face (s2-s3-e3-e2)
|
||||
tess.setColorRGBA_F(r, g, b, alpha1);
|
||||
tess.addVertex(s2x, s2y, s2z);
|
||||
tess.addVertex(s3x, s3y, s3z);
|
||||
tess.setColorRGBA_F(r, g, b, alpha2);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
}
|
||||
|
||||
tess.draw();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the beam head as a glowing cube.
|
||||
* 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 innerAlpha, float partialTicks) {
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(x, y, z);
|
||||
|
||||
// Pulsing effect
|
||||
float pulseTime = beam.ticksExisted + partialTicks;
|
||||
float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.1f;
|
||||
float scale = size * (1.0f + scaleModifier);
|
||||
|
||||
// Render lightning BEFORE rotation so it crackles in all directions (only on head)
|
||||
if (beam.hasLightningEffect()) {
|
||||
renderAttachedLightning(beam, 0.6f * 0.5f, scale);
|
||||
}
|
||||
|
||||
// Rotation
|
||||
GL11.glRotatef(beam.getInterpolatedRotationX(partialTicks), 1.0f, 0.0f, 0.0f);
|
||||
GL11.glRotatef(beam.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f);
|
||||
GL11.glRotatef(beam.getInterpolatedRotationZ(partialTicks), 0.0f, 0.0f, 1.0f);
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(scale, scale, scale);
|
||||
|
||||
// Inner scale defines the core size
|
||||
float innerScale = 0.6f;
|
||||
|
||||
// Render outer glow only if enabled
|
||||
// outerColorWidth is an additive offset from inner size
|
||||
if (beam.isOuterColorEnabled()) {
|
||||
float outerScale = innerScale + beam.getOuterColorWidth();
|
||||
GL11.glDepthMask(false);
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(outerScale, outerScale, outerScale);
|
||||
renderCube(outerColor, outerAlpha, 0.5f);
|
||||
GL11.glPopMatrix();
|
||||
GL11.glDepthMask(true);
|
||||
}
|
||||
|
||||
// Render inner core
|
||||
GL11.glScalef(innerScale, innerScale, innerScale);
|
||||
renderCube(innerColor, innerAlpha, 0.5f);
|
||||
|
||||
GL11.glPopMatrix();
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package kamkeel.npcs.client.renderer;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
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 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();
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(x, y, z);
|
||||
|
||||
// Get interpolated values
|
||||
float size = disc.getInterpolatedSize(partialTicks);
|
||||
float radius = disc.getDiscRadius() * size;
|
||||
float thickness = disc.getDiscThickness() * size;
|
||||
|
||||
// Subtle pulsing effect
|
||||
float pulseTime = entity.ticksExisted + partialTicks;
|
||||
float scaleModifier = (float) Math.sin(pulseTime * 0.1f) * 0.03f;
|
||||
float scale = 1.0f + scaleModifier;
|
||||
|
||||
// Render lightning BEFORE rotation so it crackles in all directions
|
||||
if (disc.hasLightningEffect()) {
|
||||
renderAttachedLightning(disc, 0.6f * 0.5f, radius * scale);
|
||||
}
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(scale, scale, scale);
|
||||
|
||||
if (disc.isVertical()) {
|
||||
// Vertical mode: thin edge faces direction of travel (like a saw blade)
|
||||
// 1. Spin in local space (Y-axis)
|
||||
// 2. Tilt 90° to stand up (X-axis)
|
||||
// 3. Orient to face travel direction (Y-axis world yaw)
|
||||
GL11.glRotatef(disc.getTravelYaw(), 0.0f, 1.0f, 0.0f);
|
||||
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() * proximityAlpha, radius * outerScale, thickness);
|
||||
GL11.glDepthMask(true);
|
||||
}
|
||||
|
||||
// Render inner square (solid)
|
||||
renderFlatSquare(disc.getInnerColor(), disc.getInnerAlpha() * proximityAlpha, radius * innerScale, thickness * 1.2f);
|
||||
|
||||
GL11.glPopMatrix();
|
||||
GL11.glPopMatrix();
|
||||
|
||||
restoreRenderState();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a flat square (thin cube) centered at origin.
|
||||
* The square lies flat on the XZ plane with thin Y height.
|
||||
*/
|
||||
private void renderFlatSquare(int color, float alpha, float halfSize, float thickness) {
|
||||
float halfThick = thickness * 0.5f;
|
||||
|
||||
// Render as a thin cube
|
||||
renderCubeCustom(color, alpha, halfSize, halfThick, halfSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a cube with custom dimensions.
|
||||
*/
|
||||
private void renderCubeCustom(int color, float alpha, float halfX, float halfY, float halfZ) {
|
||||
float[] rgb = extractRGB(color);
|
||||
float r = rgb[0], g = rgb[1], b = rgb[2];
|
||||
|
||||
net.minecraft.client.renderer.Tessellator tess = net.minecraft.client.renderer.Tessellator.instance;
|
||||
|
||||
// Top face (y+)
|
||||
tess.startDrawingQuads();
|
||||
tess.setColorRGBA_F(r, g, b, alpha);
|
||||
tess.setNormal(0, 1, 0);
|
||||
tess.addVertex(-halfX, halfY, halfZ);
|
||||
tess.addVertex(halfX, halfY, halfZ);
|
||||
tess.addVertex(halfX, halfY, -halfZ);
|
||||
tess.addVertex(-halfX, halfY, -halfZ);
|
||||
tess.draw();
|
||||
|
||||
// Bottom face (y-)
|
||||
tess.startDrawingQuads();
|
||||
tess.setColorRGBA_F(r, g, b, alpha);
|
||||
tess.setNormal(0, -1, 0);
|
||||
tess.addVertex(-halfX, -halfY, -halfZ);
|
||||
tess.addVertex(halfX, -halfY, -halfZ);
|
||||
tess.addVertex(halfX, -halfY, halfZ);
|
||||
tess.addVertex(-halfX, -halfY, halfZ);
|
||||
tess.draw();
|
||||
|
||||
// Front face (z+)
|
||||
tess.startDrawingQuads();
|
||||
tess.setColorRGBA_F(r, g, b, alpha);
|
||||
tess.setNormal(0, 0, 1);
|
||||
tess.addVertex(-halfX, -halfY, halfZ);
|
||||
tess.addVertex(halfX, -halfY, halfZ);
|
||||
tess.addVertex(halfX, halfY, halfZ);
|
||||
tess.addVertex(-halfX, halfY, halfZ);
|
||||
tess.draw();
|
||||
|
||||
// Back face (z-)
|
||||
tess.startDrawingQuads();
|
||||
tess.setColorRGBA_F(r, g, b, alpha);
|
||||
tess.setNormal(0, 0, -1);
|
||||
tess.addVertex(halfX, -halfY, -halfZ);
|
||||
tess.addVertex(-halfX, -halfY, -halfZ);
|
||||
tess.addVertex(-halfX, halfY, -halfZ);
|
||||
tess.addVertex(halfX, halfY, -halfZ);
|
||||
tess.draw();
|
||||
|
||||
// Right face (x+)
|
||||
tess.startDrawingQuads();
|
||||
tess.setColorRGBA_F(r, g, b, alpha);
|
||||
tess.setNormal(1, 0, 0);
|
||||
tess.addVertex(halfX, -halfY, halfZ);
|
||||
tess.addVertex(halfX, -halfY, -halfZ);
|
||||
tess.addVertex(halfX, halfY, -halfZ);
|
||||
tess.addVertex(halfX, halfY, halfZ);
|
||||
tess.draw();
|
||||
|
||||
// Left face (x-)
|
||||
tess.startDrawingQuads();
|
||||
tess.setColorRGBA_F(r, g, b, alpha);
|
||||
tess.setNormal(-1, 0, 0);
|
||||
tess.addVertex(-halfX, -halfY, -halfZ);
|
||||
tess.addVertex(-halfX, -halfY, halfZ);
|
||||
tess.addVertex(-halfX, halfY, halfZ);
|
||||
tess.addVertex(-halfX, halfY, -halfZ);
|
||||
tess.draw();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
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.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 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) {
|
||||
EntityAbilityLaser laser = (EntityAbilityLaser) entity;
|
||||
|
||||
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, proximityAlpha);
|
||||
restoreRenderState();
|
||||
return;
|
||||
}
|
||||
|
||||
// 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.getLaserWidth();
|
||||
float alpha = 1.0f;
|
||||
|
||||
// Calculate render offset (entity position is used as reference)
|
||||
double offsetX = x - laser.posX;
|
||||
double offsetY = y - laser.posY;
|
||||
double offsetZ = z - laser.posZ;
|
||||
|
||||
// Render start relative to camera
|
||||
double renderStartX = startX + offsetX;
|
||||
double renderStartY = startY + offsetY;
|
||||
double renderStartZ = startZ + offsetZ;
|
||||
double renderEndX = endX + offsetX;
|
||||
double renderEndY = endY + offsetY;
|
||||
double renderEndZ = endZ + offsetZ;
|
||||
|
||||
// Calculate perpendicular vectors for the beam rectangle
|
||||
double dx = renderEndX - renderStartX;
|
||||
double dy = renderEndY - renderStartY;
|
||||
double dz = renderEndZ - renderStartZ;
|
||||
double len = Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
if (len < 0.001) {
|
||||
restoreRenderState();
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalize direction
|
||||
dx /= len;
|
||||
dy /= len;
|
||||
dz /= len;
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// Cross product for horizontal perpendicular
|
||||
double horzX = dy * upZ - dz * upY;
|
||||
double horzY = dz * upX - dx * upZ;
|
||||
double horzZ = dx * upY - dy * upX;
|
||||
double horzLen = Math.sqrt(horzX * horzX + horzY * horzY + horzZ * horzZ);
|
||||
if (horzLen > 0) {
|
||||
horzX /= horzLen;
|
||||
horzY /= horzLen;
|
||||
horzZ /= horzLen;
|
||||
}
|
||||
|
||||
// Cross product for vertical perpendicular
|
||||
double vertX = dy * horzZ - dz * horzY;
|
||||
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;
|
||||
|
||||
// Render outer rectangle (larger, outer color, translucent) - only if enabled
|
||||
// outerColorWidth is an additive offset from inner width
|
||||
if (laser.isOuterColorEnabled()) {
|
||||
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 * 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 * 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 * 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);
|
||||
}
|
||||
|
||||
restoreRenderState();
|
||||
}
|
||||
|
||||
private void renderChargingOrb(EntityAbilityLaser laser, double x, double y, double z, float partialTicks, float proximityAlpha) {
|
||||
float headSize = laser.getLaserWidth() * 0.5f;
|
||||
float chargeProgress = laser.getInterpolatedChargeProgress(partialTicks);
|
||||
float size = headSize * chargeProgress;
|
||||
|
||||
if (size <= 0.01f) return;
|
||||
|
||||
int innerColor = laser.getInnerColor();
|
||||
int outerColor = laser.getOuterColor();
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(x, y, z);
|
||||
|
||||
// Pulsing effect
|
||||
float pulseTime = laser.ticksExisted + partialTicks;
|
||||
float scaleModifier = (float) Math.sin(pulseTime * 0.2f) * 0.08f;
|
||||
float scale = size * (1.0f + scaleModifier);
|
||||
|
||||
// Render lightning during charging if enabled
|
||||
if (laser.hasLightningEffect()) {
|
||||
renderAttachedLightning(laser, 0.6f * 0.5f, scale);
|
||||
}
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(scale, scale, scale);
|
||||
|
||||
// Inner scale defines the core size
|
||||
float innerScale = 0.6f;
|
||||
|
||||
// Render outer glow only if enabled
|
||||
if (laser.isOuterColorEnabled()) {
|
||||
float outerScale = innerScale + laser.getOuterColorWidth();
|
||||
float outerAlpha = laser.getOuterColorAlpha() * proximityAlpha;
|
||||
GL11.glDepthMask(false);
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(outerScale, outerScale, outerScale);
|
||||
renderCube(outerColor, outerAlpha, 0.5f);
|
||||
GL11.glPopMatrix();
|
||||
GL11.glDepthMask(true);
|
||||
}
|
||||
|
||||
// Render inner core
|
||||
GL11.glScalef(innerScale, innerScale, innerScale);
|
||||
renderCube(innerColor, laser.getInnerAlpha() * proximityAlpha, 0.5f);
|
||||
|
||||
GL11.glPopMatrix();
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
AttachedLightningRenderer.LightningState state = getLightningState(laser);
|
||||
|
||||
float density = laser.getLightningDensity();
|
||||
// Lightning radius extends outward from inner width
|
||||
float innerRadius = width * 0.6f * 0.5f;
|
||||
float radius = innerRadius + laser.getLightningRadius() * width;
|
||||
int outerColor = laser.getOuterColor();
|
||||
int innerColor = laser.getInnerColor();
|
||||
int fadeTime = laser.getLightningFadeTime();
|
||||
|
||||
// Render lightning at multiple points along the laser
|
||||
// Start, middle, and end points
|
||||
double midX = (startX + endX) * 0.5;
|
||||
double midY = (startY + endY) * 0.5;
|
||||
double midZ = (startZ + endZ) * 0.5;
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(midX, midY, midZ);
|
||||
state.update(density, radius, outerColor, innerColor, fadeTime);
|
||||
state.render();
|
||||
GL11.glPopMatrix();
|
||||
|
||||
// Also render at the tip
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(endX, endY, endZ);
|
||||
// Use a secondary state for the tip
|
||||
AttachedLightningRenderer.LightningState tipState = getTipLightningState(laser);
|
||||
tipState.update(density * 0.7f, radius * 0.8f, outerColor, innerColor, fadeTime);
|
||||
tipState.render();
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get or create the tip lightning state for the laser.
|
||||
* Persisted per entity ID so arcs accumulate and fade properly across frames.
|
||||
*/
|
||||
private AttachedLightningRenderer.LightningState getTipLightningState(EntityAbilityLaser laser) {
|
||||
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) {
|
||||
float[] rgb = extractRGB(color);
|
||||
float r = rgb[0], g = rgb[1], b = rgb[2];
|
||||
|
||||
float halfWidth = width * 0.5f;
|
||||
|
||||
// Calculate 8 corners of the box
|
||||
// Start corners
|
||||
double s1x = x1 - horzX * halfWidth - vertX * halfWidth;
|
||||
double s1y = y1 - horzY * halfWidth - vertY * halfWidth;
|
||||
double s1z = z1 - horzZ * halfWidth - vertZ * halfWidth;
|
||||
|
||||
double s2x = x1 + horzX * halfWidth - vertX * halfWidth;
|
||||
double s2y = y1 + horzY * halfWidth - vertY * halfWidth;
|
||||
double s2z = z1 + horzZ * halfWidth - vertZ * halfWidth;
|
||||
|
||||
double s3x = x1 + horzX * halfWidth + vertX * halfWidth;
|
||||
double s3y = y1 + horzY * halfWidth + vertY * halfWidth;
|
||||
double s3z = z1 + horzZ * halfWidth + vertZ * halfWidth;
|
||||
|
||||
double s4x = x1 - horzX * halfWidth + vertX * halfWidth;
|
||||
double s4y = y1 - horzY * halfWidth + vertY * halfWidth;
|
||||
double s4z = z1 - horzZ * halfWidth + vertZ * halfWidth;
|
||||
|
||||
// End corners
|
||||
double e1x = x2 - horzX * halfWidth - vertX * halfWidth;
|
||||
double e1y = y2 - horzY * halfWidth - vertY * halfWidth;
|
||||
double e1z = z2 - horzZ * halfWidth - vertZ * halfWidth;
|
||||
|
||||
double e2x = x2 + horzX * halfWidth - vertX * halfWidth;
|
||||
double e2y = y2 + horzY * halfWidth - vertY * halfWidth;
|
||||
double e2z = z2 + horzZ * halfWidth - vertZ * halfWidth;
|
||||
|
||||
double e3x = x2 + horzX * halfWidth + vertX * halfWidth;
|
||||
double e3y = y2 + horzY * halfWidth + vertY * halfWidth;
|
||||
double e3z = z2 + horzZ * halfWidth + vertZ * halfWidth;
|
||||
|
||||
double e4x = x2 - horzX * halfWidth + vertX * halfWidth;
|
||||
double e4y = y2 - horzY * halfWidth + vertY * halfWidth;
|
||||
double e4z = z2 - horzZ * halfWidth + vertZ * halfWidth;
|
||||
|
||||
Tessellator tess = Tessellator.instance;
|
||||
tess.startDrawingQuads();
|
||||
tess.setColorRGBA_F(r, g, b, alpha);
|
||||
|
||||
// Bottom face
|
||||
tess.addVertex(s1x, s1y, s1z);
|
||||
tess.addVertex(s2x, s2y, s2z);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
|
||||
// Top face
|
||||
tess.addVertex(s4x, s4y, s4z);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.addVertex(s3x, s3y, s3z);
|
||||
|
||||
// Left face
|
||||
tess.addVertex(s1x, s1y, s1z);
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
tess.addVertex(s4x, s4y, s4z);
|
||||
|
||||
// Right face
|
||||
tess.addVertex(s2x, s2y, s2z);
|
||||
tess.addVertex(s3x, s3y, s3z);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
|
||||
// Start cap
|
||||
tess.addVertex(s1x, s1y, s1z);
|
||||
tess.addVertex(s4x, s4y, s4z);
|
||||
tess.addVertex(s3x, s3y, s3z);
|
||||
tess.addVertex(s2x, s2y, s2z);
|
||||
|
||||
// End cap
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
|
||||
tess.draw();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package kamkeel.npcs.client.renderer;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Renders the AbilityOrb entity as a cube with inner and outer layers.
|
||||
* Minecraft-style blocky appearance using Tessellator.
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
public class RenderEnergyOrb extends RenderEnergy {
|
||||
|
||||
private static final int LIGHTNING_FADE_TICKS = 6;
|
||||
|
||||
@Override
|
||||
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();
|
||||
GL11.glTranslated(x, y, z);
|
||||
|
||||
// Get interpolated size for smooth rendering
|
||||
float size = orb.getInterpolatedSize(partialTicks);
|
||||
|
||||
// Pulsing scale effect
|
||||
float pulseTime = entity.ticksExisted + partialTicks;
|
||||
float scaleModifier = (float) Math.sin(pulseTime * 0.15f) * 0.05f;
|
||||
float scale = size * (1.0f + scaleModifier);
|
||||
|
||||
// Render lightning BEFORE rotation so it crackles in all directions
|
||||
if (orb.hasLightningEffect()) {
|
||||
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
|
||||
GL11.glRotatef(orb.getInterpolatedRotationX(partialTicks), 1.0f, 0.0f, 0.0f);
|
||||
GL11.glRotatef(orb.getInterpolatedRotationY(partialTicks), 0.0f, 1.0f, 0.0f);
|
||||
GL11.glRotatef(orb.getInterpolatedRotationZ(partialTicks), 0.0f, 0.0f, 1.0f);
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(scale, scale, scale);
|
||||
|
||||
// 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()) {
|
||||
float outerScale = innerScale + orb.getOuterColorWidth();
|
||||
GL11.glDepthMask(false);
|
||||
GL11.glPushMatrix();
|
||||
GL11.glScalef(outerScale, outerScale, outerScale);
|
||||
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(), orb.getInnerAlpha() * proximityAlpha, 0.5f);
|
||||
|
||||
GL11.glPopMatrix();
|
||||
GL11.glPopMatrix();
|
||||
|
||||
restoreRenderState();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package kamkeel.npcs.client.renderer;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.entity.EntityEnergySweeper;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Renders the Sweeper beam as a thin rotating laser attached to the NPC.
|
||||
* Uses similar rendering style to the Beam trail for visual consistency.
|
||||
*/
|
||||
@SideOnly(Side.CLIENT)
|
||||
public class RenderSweeper extends Render {
|
||||
|
||||
@Override
|
||||
public void doRender(Entity entity, double x, double y, double z, float yaw, float partialTicks) {
|
||||
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();
|
||||
float outerColorWidth = sweeper.getOuterColorWidth();
|
||||
float angle = sweeper.getInterpolatedAngle(partialTicks);
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(x, y, z);
|
||||
|
||||
// Rotate the beam around Y axis (angle already includes baseYaw)
|
||||
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, beamHeight, innerColor, outerColor, outerColorEnabled, outerColorWidth);
|
||||
|
||||
GL11.glPopMatrix();
|
||||
|
||||
restoreRenderState();
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
// Force full brightness - prevents world lighting from darkening sweeper
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, float height, int innerColor, int outerColor,
|
||||
boolean outerColorEnabled, float outerColorWidth) {
|
||||
// Extract colors
|
||||
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;
|
||||
|
||||
// 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) - 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, outerWidth, outerHeight, outerR, outerG, outerB, 0.3f);
|
||||
GL11.glDepthMask(true);
|
||||
|
||||
// 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)
|
||||
renderBeamSegment(0, 0, 0, 0, 0, length, innerWidth, innerHeight, innerR, innerG, innerB, 1.0f);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 height, float r, float g, float b, float a) {
|
||||
// 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;
|
||||
|
||||
// Normalize direction
|
||||
dx /= len;
|
||||
dy /= len;
|
||||
dz /= len;
|
||||
|
||||
// Calculate perpendicular vectors
|
||||
double upX = 0, upY = 1, upZ = 0;
|
||||
if (Math.abs(dy) > 0.9) {
|
||||
upX = 1;
|
||||
upY = 0;
|
||||
upZ = 0;
|
||||
}
|
||||
|
||||
// Cross product for horizontal perpendicular
|
||||
double horzX = dy * upZ - dz * upY;
|
||||
double horzY = dz * upX - dx * upZ;
|
||||
double horzZ = dx * upY - dy * upX;
|
||||
double horzLen = Math.sqrt(horzX * horzX + horzY * horzY + horzZ * horzZ);
|
||||
if (horzLen > 0) {
|
||||
horzX /= horzLen;
|
||||
horzY /= horzLen;
|
||||
horzZ /= horzLen;
|
||||
}
|
||||
|
||||
// Cross product for vertical perpendicular
|
||||
double vertX = dy * horzZ - dz * horzY;
|
||||
double vertY = dz * horzX - dx * horzZ;
|
||||
double vertZ = dx * horzY - dy * horzX;
|
||||
|
||||
float halfWidth = width * 0.5f;
|
||||
float halfHeight = height * 0.5f;
|
||||
|
||||
// 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 * halfHeight;
|
||||
double s2y = y1 + horzY * halfWidth - vertY * halfHeight;
|
||||
double s2z = z1 + horzZ * halfWidth - vertZ * halfHeight;
|
||||
|
||||
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 * halfHeight;
|
||||
double s4y = y1 - horzY * halfWidth + vertY * halfHeight;
|
||||
double s4z = z1 - horzZ * halfWidth + vertZ * halfHeight;
|
||||
|
||||
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 * halfHeight;
|
||||
double e2y = y2 + horzY * halfWidth - vertY * halfHeight;
|
||||
double e2z = z2 + horzZ * halfWidth - vertZ * halfHeight;
|
||||
|
||||
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 * halfHeight;
|
||||
double e4y = y2 - horzY * halfWidth + vertY * halfHeight;
|
||||
double e4z = z2 - horzZ * halfWidth + vertZ * halfHeight;
|
||||
|
||||
Tessellator tess = Tessellator.instance;
|
||||
tess.startDrawingQuads();
|
||||
tess.setColorRGBA_F(r, g, b, a);
|
||||
|
||||
// Bottom face
|
||||
tess.addVertex(s1x, s1y, s1z);
|
||||
tess.addVertex(s2x, s2y, s2z);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
|
||||
// Top face
|
||||
tess.addVertex(s4x, s4y, s4z);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.addVertex(s3x, s3y, s3z);
|
||||
|
||||
// Left face
|
||||
tess.addVertex(s1x, s1y, s1z);
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
tess.addVertex(s4x, s4y, s4z);
|
||||
|
||||
// Right face
|
||||
tess.addVertex(s2x, s2y, s2z);
|
||||
tess.addVertex(s3x, s3y, s3z);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
|
||||
// End cap (tip of beam)
|
||||
tess.addVertex(e1x, e1y, e1z);
|
||||
tess.addVertex(e2x, e2y, e2z);
|
||||
tess.addVertex(e3x, e3y, e3z);
|
||||
tess.addVertex(e4x, e4y, e4z);
|
||||
|
||||
tess.draw();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ResourceLocation getEntityTexture(Entity entity) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
package kamkeel.npcs.client.renderer;
|
||||
|
||||
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
|
||||
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
|
||||
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
|
||||
import kamkeel.npcs.controllers.data.telegraph.TelegraphManager;
|
||||
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraftforge.client.event.RenderWorldLastEvent;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
/**
|
||||
* Renders telegraph warning shapes in the world.
|
||||
* Register this as an event handler on the Forge event bus.
|
||||
*/
|
||||
public class TelegraphRenderer {
|
||||
|
||||
public static TelegraphRenderer Instance;
|
||||
|
||||
private static final int CIRCLE_SEGMENTS = 32;
|
||||
private static final int CONE_SEGMENTS = 16;
|
||||
|
||||
public TelegraphRenderer() {
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onRenderWorldLast(RenderWorldLastEvent event) {
|
||||
if (TelegraphManager.ClientInstance == null || !TelegraphManager.ClientInstance.hasTelegraphs()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Minecraft mc = Minecraft.getMinecraft();
|
||||
EntityPlayer player = mc.thePlayer;
|
||||
if (player == null) return;
|
||||
|
||||
float partialTicks = event.partialTicks;
|
||||
|
||||
// Get player interpolated position for camera offset
|
||||
double playerX = player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTicks;
|
||||
double playerY = player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTicks;
|
||||
double playerZ = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTicks;
|
||||
|
||||
// Setup GL state for transparent rendering
|
||||
GL11.glPushMatrix();
|
||||
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.glDepthMask(false);
|
||||
|
||||
// Render each telegraph
|
||||
for (TelegraphInstance instance : TelegraphManager.ClientInstance.getTelegraphs()) {
|
||||
renderTelegraph(instance, playerX, playerY, playerZ, partialTicks);
|
||||
}
|
||||
|
||||
// Restore GL state
|
||||
GL11.glDepthMask(true);
|
||||
GL11.glEnable(GL11.GL_LIGHTING);
|
||||
GL11.glDisable(GL11.GL_BLEND);
|
||||
GL11.glEnable(GL11.GL_CULL_FACE);
|
||||
GL11.glEnable(GL11.GL_TEXTURE_2D);
|
||||
|
||||
GL11.glPopAttrib();
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
|
||||
private void renderTelegraph(TelegraphInstance instance, double playerX, double playerY, double playerZ, float partialTicks) {
|
||||
Telegraph telegraph = instance.getTelegraph();
|
||||
if (telegraph == null || telegraph.getType() == TelegraphType.NONE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Calculate render position relative to camera using interpolated positions for smooth movement
|
||||
double renderX = instance.getInterpolatedX(partialTicks) - playerX;
|
||||
double renderY = instance.getInterpolatedY(partialTicks) - playerY + telegraph.getHeightOffset();
|
||||
double renderZ = instance.getInterpolatedZ(partialTicks) - playerZ;
|
||||
|
||||
// Get animated color
|
||||
int color = instance.getAnimatedColor(partialTicks);
|
||||
float alpha = ((color >> 24) & 0xFF) / 255.0f;
|
||||
float red = ((color >> 16) & 0xFF) / 255.0f;
|
||||
float green = ((color >> 8) & 0xFF) / 255.0f;
|
||||
float blue = (color & 0xFF) / 255.0f;
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(renderX, renderY, renderZ);
|
||||
|
||||
// Rotate for directional shapes using interpolated yaw for smooth rotation
|
||||
GL11.glRotatef(-instance.getInterpolatedYaw(partialTicks), 0, 1, 0);
|
||||
|
||||
switch (telegraph.getType()) {
|
||||
case CIRCLE:
|
||||
renderCircle(telegraph.getRadius(), red, green, blue, alpha);
|
||||
break;
|
||||
case RING:
|
||||
renderRing(telegraph.getRadius(), telegraph.getInnerRadius(), red, green, blue, alpha);
|
||||
break;
|
||||
case LINE:
|
||||
renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
|
||||
break;
|
||||
case CONE:
|
||||
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;
|
||||
}
|
||||
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
|
||||
private void renderCircle(float radius, float r, float g, float b, float a) {
|
||||
Tessellator tessellator = Tessellator.instance;
|
||||
tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
|
||||
tessellator.setColorRGBA_F(r, g, b, a);
|
||||
|
||||
// Center point
|
||||
tessellator.addVertex(0, 0, 0);
|
||||
|
||||
// Circle points
|
||||
for (int i = 0; i <= CIRCLE_SEGMENTS; i++) {
|
||||
double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
|
||||
double x = Math.cos(angle) * radius;
|
||||
double z = Math.sin(angle) * radius;
|
||||
tessellator.addVertex(x, 0, z);
|
||||
}
|
||||
|
||||
tessellator.draw();
|
||||
|
||||
// Draw border
|
||||
renderCircleBorder(radius, r, g, b, Math.min(1.0f, a * 2));
|
||||
}
|
||||
|
||||
private void renderCircleBorder(float radius, float r, float g, float b, float a) {
|
||||
Tessellator tessellator = Tessellator.instance;
|
||||
tessellator.startDrawing(GL11.GL_LINE_LOOP);
|
||||
tessellator.setColorRGBA_F(r, g, b, a);
|
||||
|
||||
for (int i = 0; i < CIRCLE_SEGMENTS; i++) {
|
||||
double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
|
||||
double x = Math.cos(angle) * radius;
|
||||
double z = Math.sin(angle) * radius;
|
||||
tessellator.addVertex(x, 0.01, z);
|
||||
}
|
||||
|
||||
tessellator.draw();
|
||||
}
|
||||
|
||||
private void renderRing(float outerRadius, float innerRadius, float r, float g, float b, float a) {
|
||||
Tessellator tessellator = Tessellator.instance;
|
||||
tessellator.startDrawing(GL11.GL_TRIANGLE_STRIP);
|
||||
tessellator.setColorRGBA_F(r, g, b, a);
|
||||
|
||||
for (int i = 0; i <= CIRCLE_SEGMENTS; i++) {
|
||||
double angle = (Math.PI * 2 * i) / CIRCLE_SEGMENTS;
|
||||
double cosA = Math.cos(angle);
|
||||
double sinA = Math.sin(angle);
|
||||
|
||||
// Outer point
|
||||
tessellator.addVertex(cosA * outerRadius, 0, sinA * outerRadius);
|
||||
// Inner point
|
||||
tessellator.addVertex(cosA * innerRadius, 0, sinA * innerRadius);
|
||||
}
|
||||
|
||||
tessellator.draw();
|
||||
|
||||
// Draw borders
|
||||
renderCircleBorder(outerRadius, r, g, b, Math.min(1.0f, a * 2));
|
||||
renderCircleBorder(innerRadius, r, g, b, Math.min(1.0f, a * 2));
|
||||
}
|
||||
|
||||
private void renderLine(float length, float width, float r, float g, float b, float a) {
|
||||
float halfWidth = width / 2;
|
||||
|
||||
Tessellator tessellator = Tessellator.instance;
|
||||
tessellator.startDrawingQuads();
|
||||
tessellator.setColorRGBA_F(r, g, b, a);
|
||||
|
||||
// Rectangle from origin forward
|
||||
tessellator.addVertex(-halfWidth, 0, 0);
|
||||
tessellator.addVertex(halfWidth, 0, 0);
|
||||
tessellator.addVertex(halfWidth, 0, length);
|
||||
tessellator.addVertex(-halfWidth, 0, length);
|
||||
|
||||
tessellator.draw();
|
||||
|
||||
// Draw border
|
||||
tessellator.startDrawing(GL11.GL_LINE_LOOP);
|
||||
tessellator.setColorRGBA_F(r, g, b, Math.min(1.0f, a * 2));
|
||||
|
||||
tessellator.addVertex(-halfWidth, 0.01, 0);
|
||||
tessellator.addVertex(halfWidth, 0.01, 0);
|
||||
tessellator.addVertex(halfWidth, 0.01, length);
|
||||
tessellator.addVertex(-halfWidth, 0.01, length);
|
||||
|
||||
tessellator.draw();
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
if (innerRadius <= 0) {
|
||||
// Standard cone: triangle fan from origin
|
||||
tessellator.startDrawing(GL11.GL_TRIANGLE_FAN);
|
||||
tessellator.setColorRGBA_F(r, g, b, a);
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
private void renderPoint(float r, float g, float b, float a) {
|
||||
float size = 0.5f;
|
||||
|
||||
Tessellator tessellator = Tessellator.instance;
|
||||
tessellator.startDrawingQuads();
|
||||
tessellator.setColorRGBA_F(r, g, b, a);
|
||||
|
||||
// Diamond shape
|
||||
tessellator.addVertex(0, 0, -size);
|
||||
tessellator.addVertex(size, 0, 0);
|
||||
tessellator.addVertex(0, 0, size);
|
||||
tessellator.addVertex(-size, 0, 0);
|
||||
|
||||
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 ====================
|
||||
|
||||
/**
|
||||
* Render a telegraph in GUI space for ability preview.
|
||||
* This is used by the Manage Abilities GUI to show telegraph shapes.
|
||||
*
|
||||
* @param instance The telegraph instance to render
|
||||
* @param centerX X center position in GUI space
|
||||
* @param centerY Y center position in GUI space
|
||||
* @param centerZ Z center position in GUI space
|
||||
* @param scale Scale factor for the telegraph
|
||||
* @param partialTicks Partial ticks for interpolation
|
||||
*/
|
||||
public void renderTelegraphInGUI(TelegraphInstance instance,
|
||||
double centerX, double centerY, double centerZ,
|
||||
float scale, float partialTicks) {
|
||||
if (instance == null) return;
|
||||
|
||||
Telegraph telegraph = instance.getTelegraph();
|
||||
if (telegraph == null || telegraph.getType() == TelegraphType.NONE) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get animated color
|
||||
int color = instance.getAnimatedColor(partialTicks);
|
||||
float alpha = ((color >> 24) & 0xFF) / 255.0f;
|
||||
float red = ((color >> 16) & 0xFF) / 255.0f;
|
||||
float green = ((color >> 8) & 0xFF) / 255.0f;
|
||||
float blue = (color & 0xFF) / 255.0f;
|
||||
|
||||
// Setup GL state
|
||||
GL11.glPushMatrix();
|
||||
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.glDepthMask(false);
|
||||
|
||||
GL11.glTranslated(centerX, centerY, centerZ);
|
||||
GL11.glScalef(scale, scale, scale);
|
||||
|
||||
// Rotate for directional shapes
|
||||
GL11.glRotatef(-instance.getInterpolatedYaw(partialTicks), 0, 1, 0);
|
||||
|
||||
// Render based on type
|
||||
switch (telegraph.getType()) {
|
||||
case CIRCLE:
|
||||
renderCircle(telegraph.getRadius(), red, green, blue, alpha);
|
||||
break;
|
||||
case RING:
|
||||
renderRing(telegraph.getRadius(), telegraph.getInnerRadius(), red, green, blue, alpha);
|
||||
break;
|
||||
case LINE:
|
||||
renderLine(telegraph.getLength(), telegraph.getWidth(), red, green, blue, alpha);
|
||||
break;
|
||||
case CONE:
|
||||
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;
|
||||
}
|
||||
|
||||
// Restore GL state
|
||||
GL11.glDepthMask(true);
|
||||
GL11.glEnable(GL11.GL_LIGHTING);
|
||||
GL11.glDisable(GL11.GL_BLEND);
|
||||
GL11.glEnable(GL11.GL_CULL_FACE);
|
||||
GL11.glEnable(GL11.GL_TEXTURE_2D);
|
||||
|
||||
GL11.glPopAttrib();
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
package kamkeel.npcs.client.renderer.lightning;
|
||||
|
||||
import net.minecraft.client.renderer.Tessellator;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Renders lightning arcs attached to an entity (in local space).
|
||||
* Supports both instant arcs and fading persistent bolts that move with the entity.
|
||||
*/
|
||||
public class AttachedLightningRenderer {
|
||||
|
||||
private static final Random rand = new Random();
|
||||
|
||||
/**
|
||||
* Data for a single lightning bolt with fading support.
|
||||
*/
|
||||
public static class LightningArc {
|
||||
public List<double[]> points;
|
||||
public int age;
|
||||
public int maxAge;
|
||||
public int outerColor;
|
||||
public int innerColor;
|
||||
|
||||
public LightningArc(List<double[]> points, int maxAge, int outerColor, int innerColor) {
|
||||
this.points = points;
|
||||
this.age = 0;
|
||||
this.maxAge = maxAge;
|
||||
this.outerColor = outerColor;
|
||||
this.innerColor = innerColor;
|
||||
}
|
||||
|
||||
public float getAlphaMultiplier() {
|
||||
// Fade out over lifetime
|
||||
if (maxAge <= 0) return 0.0f;
|
||||
return 1.0f - ((float) age / (float) maxAge);
|
||||
}
|
||||
|
||||
public boolean isDead() {
|
||||
return age >= maxAge;
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
age++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Storage for persistent lightning arcs per entity.
|
||||
* Call updateAndRender() each frame from the entity's renderer.
|
||||
*/
|
||||
public static class LightningState {
|
||||
private final List<LightningArc> arcs = new ArrayList<>();
|
||||
private float spawnAccumulator = 0;
|
||||
|
||||
/**
|
||||
* Update arc ages, remove dead arcs, spawn new ones based on density.
|
||||
*
|
||||
* @param density Arcs per tick (can be fractional)
|
||||
* @param radius Max arc distance from center
|
||||
* @param outerColor Outer glow color
|
||||
* @param innerColor Inner core color
|
||||
* @param maxAge How many ticks arcs live (for fading)
|
||||
*/
|
||||
public void update(float density, float radius, int outerColor, int innerColor, int maxAge) {
|
||||
// Age existing arcs and remove dead ones
|
||||
Iterator<LightningArc> iter = arcs.iterator();
|
||||
while (iter.hasNext()) {
|
||||
LightningArc arc = iter.next();
|
||||
arc.tick();
|
||||
if (arc.isDead()) {
|
||||
iter.remove();
|
||||
}
|
||||
}
|
||||
|
||||
// Spawn new arcs based on density
|
||||
spawnAccumulator += density;
|
||||
while (spawnAccumulator >= 1.0f) {
|
||||
spawnAccumulator -= 1.0f;
|
||||
arcs.add(createArc(radius, outerColor, innerColor, maxAge));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Note: Expects the caller to have already set up GL state (disabled textures,
|
||||
* disabled lighting, disabled culling, enabled blending). This avoids nesting
|
||||
* glPushAttrib calls which can overflow the GL attrib stack (depth 16) when
|
||||
* other mods also push attribs during entity rendering.
|
||||
*/
|
||||
public void render() {
|
||||
if (arcs.isEmpty()) return;
|
||||
|
||||
GL11.glDepthMask(false);
|
||||
|
||||
Tessellator tess = Tessellator.instance;
|
||||
|
||||
for (LightningArc arc : arcs) {
|
||||
float alphaMult = arc.getAlphaMultiplier();
|
||||
|
||||
// Render outer glow
|
||||
renderBoltPath(tess, arc.points, arc.outerColor, 0.025f, 0.35f * alphaMult);
|
||||
|
||||
// Render inner core
|
||||
renderBoltPath(tess, arc.points, arc.innerColor, 0.012f, 0.7f * alphaMult);
|
||||
}
|
||||
|
||||
GL11.glDepthMask(true);
|
||||
}
|
||||
|
||||
public int getArcCount() {
|
||||
return arcs.size();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new lightning arc from center to a random point.
|
||||
*/
|
||||
private static LightningArc createArc(float radius, int outerColor, int innerColor, int maxAge) {
|
||||
// Random end point on sphere
|
||||
double theta = rand.nextDouble() * Math.PI * 2;
|
||||
double phi = Math.acos(2 * rand.nextDouble() - 1);
|
||||
double r = radius * (0.5 + rand.nextDouble() * 0.5);
|
||||
|
||||
double endX = r * Math.sin(phi) * Math.cos(theta);
|
||||
double endY = r * Math.sin(phi) * Math.sin(theta);
|
||||
double endZ = r * Math.cos(phi);
|
||||
|
||||
int segments = 4 + rand.nextInt(3);
|
||||
float displacement = radius * 0.25f;
|
||||
|
||||
List<double[]> points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement);
|
||||
|
||||
return new LightningArc(points, maxAge, outerColor, innerColor);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
List<double[]> points = new ArrayList<>();
|
||||
points.add(new double[]{x1, y1, z1});
|
||||
|
||||
double dx = x2 - x1;
|
||||
double dy = y2 - y1;
|
||||
double dz = z2 - z1;
|
||||
|
||||
// Create perpendicular vectors for displacement
|
||||
Vec3d dir = new Vec3d(dx, dy, dz);
|
||||
Vec3d perp1 = dir.copy().perpendicular().normalize();
|
||||
Vec3d perp2 = dir.copy().crossProduct(perp1).normalize();
|
||||
|
||||
for (int i = 1; i < segments; i++) {
|
||||
double t = (double) i / segments;
|
||||
|
||||
double px = x1 + dx * t;
|
||||
double py = y1 + dy * t;
|
||||
double pz = z1 + dz * t;
|
||||
|
||||
// Displacement strongest in middle
|
||||
float strength = (float) (1.0 - Math.abs(t - 0.5) * 2.0) * displacement;
|
||||
double offset1 = (rand.nextDouble() - 0.5) * 2 * strength;
|
||||
double offset2 = (rand.nextDouble() - 0.5) * 2 * strength;
|
||||
|
||||
px += perp1.x * offset1 + perp2.x * offset2;
|
||||
py += perp1.y * offset1 + perp2.y * offset2;
|
||||
pz += perp1.z * offset1 + perp2.z * offset2;
|
||||
|
||||
points.add(new double[]{px, py, pz});
|
||||
}
|
||||
|
||||
points.add(new double[]{x2, y2, z2});
|
||||
return points;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the lightning path as quads.
|
||||
*/
|
||||
private static void renderBoltPath(Tessellator tess, List<double[]> points, int color, float width, float alpha) {
|
||||
if (alpha <= 0.01f) return;
|
||||
|
||||
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++) {
|
||||
double[] p1 = points.get(i);
|
||||
double[] p2 = points.get(i + 1);
|
||||
|
||||
double segDx = p2[0] - p1[0];
|
||||
double segDy = p2[1] - p1[1];
|
||||
double segDz = p2[2] - p1[2];
|
||||
|
||||
Vec3d segDir = new Vec3d(segDx, segDy, segDz);
|
||||
Vec3d perp = segDir.copy().perpendicular().normalize().multiply(width);
|
||||
|
||||
// First quad
|
||||
tess.startDrawingQuads();
|
||||
tess.setBrightness(0xF000F0);
|
||||
tess.setColorRGBA(r, g, b, a);
|
||||
|
||||
tess.addVertex(p1[0] - perp.x, p1[1] - perp.y, p1[2] - perp.z);
|
||||
tess.addVertex(p1[0] + perp.x, p1[1] + perp.y, p1[2] + perp.z);
|
||||
tess.addVertex(p2[0] + perp.x, p2[1] + perp.y, p2[2] + perp.z);
|
||||
tess.addVertex(p2[0] - perp.x, p2[1] - perp.y, p2[2] - perp.z);
|
||||
|
||||
tess.draw();
|
||||
|
||||
// Second quad (perpendicular for 3D look)
|
||||
Vec3d perp2 = segDir.copy().crossProduct(perp).normalize().multiply(width);
|
||||
|
||||
tess.startDrawingQuads();
|
||||
tess.setBrightness(0xF000F0);
|
||||
tess.setColorRGBA(r, g, b, a);
|
||||
|
||||
tess.addVertex(p1[0] - perp2.x, p1[1] - perp2.y, p1[2] - perp2.z);
|
||||
tess.addVertex(p1[0] + perp2.x, p1[1] + perp2.y, p1[2] + perp2.z);
|
||||
tess.addVertex(p2[0] + perp2.x, p2[1] + perp2.y, p2[2] + perp2.z);
|
||||
tess.addVertex(p2[0] - perp2.x, p2[1] - perp2.y, p2[2] - perp2.z);
|
||||
|
||||
tess.draw();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) ====================
|
||||
|
||||
/**
|
||||
* Render a single instant lightning arc (no fading, drawn this frame only).
|
||||
* Expects the caller to have already set up GL state (disabled textures,
|
||||
* disabled lighting, disabled culling, enabled blending).
|
||||
*/
|
||||
public static void renderInstantArc(float radius, int outerColor, int innerColor) {
|
||||
double theta = rand.nextDouble() * Math.PI * 2;
|
||||
double phi = Math.acos(2 * rand.nextDouble() - 1);
|
||||
double r = radius * (0.5 + rand.nextDouble() * 0.5);
|
||||
|
||||
double endX = r * Math.sin(phi) * Math.cos(theta);
|
||||
double endY = r * Math.sin(phi) * Math.sin(theta);
|
||||
double endZ = r * Math.cos(phi);
|
||||
|
||||
int segments = 4 + rand.nextInt(3);
|
||||
float displacement = radius * 0.25f;
|
||||
|
||||
List<double[]> points = generateLightningPath(0, 0, 0, endX, endY, endZ, segments, displacement);
|
||||
|
||||
GL11.glDepthMask(false);
|
||||
|
||||
Tessellator tess = Tessellator.instance;
|
||||
renderBoltPath(tess, points, outerColor, 0.025f, 0.35f);
|
||||
renderBoltPath(tess, points, innerColor, 0.012f, 0.7f);
|
||||
|
||||
GL11.glDepthMask(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render multiple instant arcs.
|
||||
*/
|
||||
public static void renderCracklingLightning(int count, float radius, int outerColor, int innerColor) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
renderInstantArc(radius, outerColor, innerColor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package kamkeel.npcs.client.renderer.lightning;
|
||||
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
/**
|
||||
* Lightning bolt data model with fractal segment generation.
|
||||
* Adapted from Botania's LightningBolt by Vazkii/ChickenBones.
|
||||
*/
|
||||
public class LightningBolt {
|
||||
|
||||
public static ConcurrentLinkedQueue<LightningBolt> boltList = new ConcurrentLinkedQueue<>();
|
||||
|
||||
public ArrayList<Segment> segments = new ArrayList<>();
|
||||
public Vec3d start;
|
||||
public Vec3d end;
|
||||
|
||||
public double length;
|
||||
public int numSegments0;
|
||||
private int numSplits;
|
||||
private boolean finalized;
|
||||
private Random rand;
|
||||
public long seed;
|
||||
|
||||
public int particleAge;
|
||||
public int particleMaxAge;
|
||||
public boolean isDead;
|
||||
|
||||
private World world;
|
||||
private HashMap<Integer, Integer> splitParents = new HashMap<>();
|
||||
|
||||
public float speed = 1.5F;
|
||||
public static final int FADE_TIME = 4; // Short lifespan for projectile-attached lightning
|
||||
|
||||
public int colorOuter;
|
||||
public int colorInner;
|
||||
|
||||
public LightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, long seed, int colorOuter, int colorInner) {
|
||||
this.world = world;
|
||||
this.seed = seed;
|
||||
this.rand = new Random(seed);
|
||||
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
this.speed = ticksPerMeter;
|
||||
|
||||
this.colorOuter = colorOuter;
|
||||
this.colorInner = colorInner;
|
||||
|
||||
this.numSegments0 = 1;
|
||||
this.length = end.copy().subtract(start).mag();
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply default fractal splitting for natural-looking lightning.
|
||||
*/
|
||||
public void defaultFractal() {
|
||||
fractal(2, length / 1.5, 0.7F, 0.7F, 45);
|
||||
fractal(2, length / 4, 0.5F, 0.8F, 50);
|
||||
fractal(2, length / 15, 0.5F, 0.9F, 55);
|
||||
fractal(2, length / 30, 0.5F, 1.0F, 60);
|
||||
fractal(2, length / 60, 0, 0, 0);
|
||||
fractal(2, length / 100, 0, 0, 0);
|
||||
fractal(2, length / 400, 0, 0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simplified fractal for short-lived projectile lightning.
|
||||
* Less detail but faster and more appropriate for fast-moving objects.
|
||||
*/
|
||||
public void simpleFractal() {
|
||||
fractal(2, length / 2.0, 0.4F, 0.6F, 35);
|
||||
fractal(2, length / 6, 0.3F, 0.7F, 40);
|
||||
fractal(2, length / 20, 0, 0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply fractal splitting to create branching lightning.
|
||||
*
|
||||
* @param splits Number of splits per segment
|
||||
* @param amount Displacement amount
|
||||
* @param splitChance Probability of branching (0-1)
|
||||
* @param splitLength Length multiplier for branches
|
||||
* @param splitAngle Angle for branch splits in degrees
|
||||
*/
|
||||
public void fractal(int splits, double amount, double splitChance, double splitLength, double splitAngle) {
|
||||
if (finalized) return;
|
||||
|
||||
ArrayList<Segment> oldSegments = segments;
|
||||
segments = new ArrayList<>();
|
||||
|
||||
Segment prev = null;
|
||||
|
||||
for (Segment segment : oldSegments) {
|
||||
prev = segment.prev;
|
||||
|
||||
Vec3d subSegment = segment.diff.copy().multiply(1.0 / splits);
|
||||
|
||||
BoltPoint[] newPoints = new BoltPoint[splits + 1];
|
||||
|
||||
Vec3d startPoint = segment.startPoint.point;
|
||||
newPoints[0] = segment.startPoint;
|
||||
newPoints[splits] = segment.endPoint;
|
||||
|
||||
for (int i = 1; i < splits; i++) {
|
||||
Vec3d randOff = segment.diff.copy().perpendicular().normalize()
|
||||
.rotate(rand.nextFloat() * 360, segment.diff);
|
||||
randOff.multiply((rand.nextFloat() - 0.5F) * amount * 2);
|
||||
|
||||
Vec3d basePoint = startPoint.copy().add(subSegment.copy().multiply(i));
|
||||
|
||||
newPoints[i] = new BoltPoint(basePoint, randOff);
|
||||
}
|
||||
|
||||
for (int i = 0; i < splits; i++) {
|
||||
Segment next = new Segment(newPoints[i], newPoints[i + 1], segment.light,
|
||||
segment.segmentNo * splits + i, segment.splitNo);
|
||||
next.prev = prev;
|
||||
if (prev != null) {
|
||||
prev.next = next;
|
||||
}
|
||||
|
||||
if (i != 0 && rand.nextFloat() < splitChance) {
|
||||
Vec3d splitRot = next.diff.copy().xCrossProduct()
|
||||
.rotate(rand.nextFloat() * 360, next.diff);
|
||||
Vec3d diff = next.diff.copy()
|
||||
.rotate((rand.nextFloat() * 0.66F + 0.33F) * splitAngle, splitRot)
|
||||
.multiply(splitLength);
|
||||
|
||||
numSplits++;
|
||||
splitParents.put(numSplits, next.splitNo);
|
||||
|
||||
Segment split = new Segment(newPoints[i],
|
||||
new BoltPoint(newPoints[i + 1].basePoint, newPoints[i + 1].offsetVec.copy().add(diff)),
|
||||
segment.light / 2F, next.segmentNo, numSplits);
|
||||
split.prev = prev;
|
||||
|
||||
segments.add(split);
|
||||
}
|
||||
|
||||
prev = next;
|
||||
segments.add(next);
|
||||
}
|
||||
|
||||
if (segment.next != null) {
|
||||
segment.next.prev = prev;
|
||||
}
|
||||
}
|
||||
|
||||
numSegments0 *= splits;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalize the bolt after all fractal passes.
|
||||
*/
|
||||
public void finalizeBolt() {
|
||||
if (finalized) return;
|
||||
finalized = true;
|
||||
|
||||
calculateEndDiffs();
|
||||
Collections.sort(segments, new SegmentLightSorter());
|
||||
}
|
||||
|
||||
private void calculateEndDiffs() {
|
||||
Collections.sort(segments, new SegmentSorter());
|
||||
|
||||
for (Segment segment : segments) {
|
||||
segment.calcEndDiffs();
|
||||
}
|
||||
}
|
||||
|
||||
public void onUpdate() {
|
||||
particleAge++;
|
||||
if (particleAge >= particleMaxAge) {
|
||||
isDead = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update all active lightning bolts. Called from client tick handler.
|
||||
*/
|
||||
public static void updateAll() {
|
||||
for (Iterator<LightningBolt> iterator = boltList.iterator(); iterator.hasNext(); ) {
|
||||
LightningBolt bolt = iterator.next();
|
||||
bolt.onUpdate();
|
||||
if (bolt.isDead) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== INNER CLASSES ====================
|
||||
|
||||
public class BoltPoint {
|
||||
public Vec3d point;
|
||||
public Vec3d basePoint;
|
||||
public Vec3d offsetVec;
|
||||
|
||||
public BoltPoint(Vec3d basePoint, Vec3d offsetVec) {
|
||||
this.point = basePoint.copy().add(offsetVec);
|
||||
this.basePoint = basePoint;
|
||||
this.offsetVec = offsetVec;
|
||||
}
|
||||
}
|
||||
|
||||
public class Segment {
|
||||
public BoltPoint startPoint;
|
||||
public BoltPoint endPoint;
|
||||
|
||||
public Vec3d diff;
|
||||
public Segment prev;
|
||||
public Segment next;
|
||||
|
||||
public Vec3d nextDiff;
|
||||
public Vec3d prevDiff;
|
||||
|
||||
public float sinPrev;
|
||||
public float sinNext;
|
||||
public float light;
|
||||
|
||||
public int segmentNo;
|
||||
public int splitNo;
|
||||
|
||||
public Segment(BoltPoint start, BoltPoint end, float light, int segmentNo, int splitNo) {
|
||||
this.startPoint = start;
|
||||
this.endPoint = end;
|
||||
this.light = light;
|
||||
this.segmentNo = segmentNo;
|
||||
this.splitNo = splitNo;
|
||||
calcDiff();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
public void calcDiff() {
|
||||
diff = endPoint.point.copy().subtract(startPoint.point);
|
||||
}
|
||||
|
||||
public void calcEndDiffs() {
|
||||
if (prev != null) {
|
||||
Vec3d prevDiffNorm = prev.diff.copy().normalize();
|
||||
Vec3d thisDiffNorm = diff.copy().normalize();
|
||||
|
||||
prevDiff = thisDiffNorm.copy().add(prevDiffNorm).normalize();
|
||||
sinPrev = (float) Math.sin(thisDiffNorm.angle(prevDiffNorm.multiply(-1)) / 2);
|
||||
} else {
|
||||
prevDiff = diff.copy().normalize();
|
||||
sinPrev = 1;
|
||||
}
|
||||
|
||||
if (next != null) {
|
||||
Vec3d nextDiffNorm = next.diff.copy().normalize();
|
||||
Vec3d thisDiffNorm = diff.copy().normalize();
|
||||
|
||||
nextDiff = thisDiffNorm.add(nextDiffNorm).normalize();
|
||||
sinNext = (float) Math.sin(thisDiffNorm.angle(nextDiffNorm.multiply(-1)) / 2);
|
||||
} else {
|
||||
nextDiff = diff.copy().normalize();
|
||||
sinNext = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SegmentSorter implements Comparator<Segment> {
|
||||
@Override
|
||||
public int compare(Segment o1, Segment o2) {
|
||||
int comp = Integer.compare(o1.splitNo, o2.splitNo);
|
||||
if (comp == 0) {
|
||||
return Integer.compare(o1.segmentNo, o2.segmentNo);
|
||||
}
|
||||
return comp;
|
||||
}
|
||||
}
|
||||
|
||||
public class SegmentLightSorter implements Comparator<Segment> {
|
||||
@Override
|
||||
public int compare(Segment o1, Segment o2) {
|
||||
return Float.compare(o2.light, o1.light);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package kamkeel.npcs.client.renderer.lightning;
|
||||
|
||||
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
|
||||
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.Tessellator;
|
||||
import net.minecraft.client.renderer.texture.TextureManager;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraftforge.client.event.RenderWorldLastEvent;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
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)
|
||||
public class LightningHandler {
|
||||
|
||||
private static final ResourceLocation TEXTURE_OUTER = new ResourceLocation("customnpcs", "textures/effects/lightning_outer.png");
|
||||
private static final ResourceLocation TEXTURE_INNER = new ResourceLocation("customnpcs", "textures/effects/lightning_inner.png");
|
||||
|
||||
public static int lightningCount = 0;
|
||||
|
||||
private static Vec3d getRelativeViewVector(Vec3d pos) {
|
||||
Entity renderEntity = Minecraft.getMinecraft().renderViewEntity;
|
||||
return new Vec3d(
|
||||
(float) renderEntity.posX - pos.x,
|
||||
(float) renderEntity.posY + renderEntity.getEyeHeight() - pos.y,
|
||||
(float) renderEntity.posZ - pos.z
|
||||
);
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
public void onRenderWorldLast(RenderWorldLastEvent event) {
|
||||
float partialTicks = event.partialTicks;
|
||||
Entity entity = Minecraft.getMinecraft().thePlayer;
|
||||
TextureManager textureManager = Minecraft.getMinecraft().renderEngine;
|
||||
|
||||
double interpPosX = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * partialTicks;
|
||||
double interpPosY = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * partialTicks;
|
||||
double interpPosZ = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * partialTicks;
|
||||
|
||||
if (LightningBolt.boltList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
GL11.glPushMatrix();
|
||||
GL11.glTranslated(-interpPosX, -interpPosY, -interpPosZ);
|
||||
|
||||
Tessellator tessellator = Tessellator.instance;
|
||||
|
||||
GL11.glDepthMask(false);
|
||||
GL11.glEnable(GL11.GL_BLEND);
|
||||
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
|
||||
GL11.glDisable(GL11.GL_TEXTURE_2D);
|
||||
GL11.glDisable(GL11.GL_LIGHTING);
|
||||
GL11.glDisable(GL11.GL_CULL_FACE);
|
||||
|
||||
lightningCount = 0;
|
||||
|
||||
// Render outer layer (translucent glow)
|
||||
for (LightningBolt bolt : LightningBolt.boltList) {
|
||||
renderBolt(bolt, tessellator, partialTicks, false);
|
||||
}
|
||||
|
||||
// Render inner layer (bright core)
|
||||
for (LightningBolt bolt : LightningBolt.boltList) {
|
||||
renderBolt(bolt, tessellator, partialTicks, true);
|
||||
}
|
||||
|
||||
GL11.glEnable(GL11.GL_CULL_FACE);
|
||||
GL11.glEnable(GL11.GL_LIGHTING);
|
||||
GL11.glEnable(GL11.GL_TEXTURE_2D);
|
||||
GL11.glDisable(GL11.GL_BLEND);
|
||||
GL11.glDepthMask(true);
|
||||
|
||||
GL11.glPopMatrix();
|
||||
}
|
||||
|
||||
private void renderBolt(LightningBolt bolt, Tessellator tessellator, float partialTicks, boolean inner) {
|
||||
lightningCount++;
|
||||
|
||||
float boltAge = bolt.particleAge < 0 ? 0 : (float) bolt.particleAge / (float) bolt.particleMaxAge;
|
||||
float mainAlpha;
|
||||
if (!inner) {
|
||||
mainAlpha = (1 - boltAge) * 0.4F;
|
||||
} else {
|
||||
mainAlpha = 1 - boltAge * 0.5F;
|
||||
}
|
||||
|
||||
int expandTime = (int) (bolt.length * bolt.speed);
|
||||
|
||||
int renderStart = (int) ((expandTime / 2 - bolt.particleMaxAge + bolt.particleAge) / (float) (expandTime / 2) * bolt.numSegments0);
|
||||
int renderEnd = (int) ((bolt.particleAge + expandTime) / (float) expandTime * bolt.numSegments0);
|
||||
|
||||
for (Segment segment : bolt.segments) {
|
||||
if (segment.segmentNo < renderStart || segment.segmentNo > renderEnd) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Vec3d playerVec = getRelativeViewVector(segment.startPoint.point).multiply(-1);
|
||||
|
||||
double width = 0.008F * (playerVec.mag() / 8 + 1) * (1 + segment.light) * 0.4F;
|
||||
|
||||
Vec3d diff1 = playerVec.copy().crossProduct(segment.prevDiff).normalize().multiply(width / segment.sinPrev);
|
||||
Vec3d diff2 = playerVec.copy().crossProduct(segment.nextDiff).normalize().multiply(width / segment.sinNext);
|
||||
|
||||
Vec3d startVec = segment.startPoint.point;
|
||||
Vec3d endVec = segment.endPoint.point;
|
||||
|
||||
int color = inner ? bolt.colorInner : bolt.colorOuter;
|
||||
Color c = new Color(color);
|
||||
int alpha = (int) (mainAlpha * segment.light * c.getAlpha());
|
||||
|
||||
tessellator.startDrawingQuads();
|
||||
tessellator.setBrightness(0xF000F0);
|
||||
tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), alpha);
|
||||
|
||||
tessellator.addVertex(endVec.x - diff2.x, endVec.y - diff2.y, endVec.z - diff2.z);
|
||||
tessellator.addVertex(startVec.x - diff1.x, startVec.y - diff1.y, startVec.z - diff1.z);
|
||||
tessellator.addVertex(startVec.x + diff1.x, startVec.y + diff1.y, startVec.z + diff1.z);
|
||||
tessellator.addVertex(endVec.x + diff2.x, endVec.y + diff2.y, endVec.z + diff2.z);
|
||||
|
||||
tessellator.draw();
|
||||
|
||||
// Rounded end caps
|
||||
if (segment.next == null) {
|
||||
Vec3d roundEnd = segment.endPoint.point.copy().add(segment.diff.copy().normalize().multiply(width));
|
||||
|
||||
tessellator.startDrawingQuads();
|
||||
tessellator.setBrightness(0xF000F0);
|
||||
tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), alpha);
|
||||
|
||||
tessellator.addVertex(roundEnd.x - diff2.x, roundEnd.y - diff2.y, roundEnd.z - diff2.z);
|
||||
tessellator.addVertex(endVec.x - diff2.x, endVec.y - diff2.y, endVec.z - diff2.z);
|
||||
tessellator.addVertex(endVec.x + diff2.x, endVec.y + diff2.y, endVec.z + diff2.z);
|
||||
tessellator.addVertex(roundEnd.x + diff2.x, roundEnd.y + diff2.y, roundEnd.z + diff2.z);
|
||||
|
||||
tessellator.draw();
|
||||
}
|
||||
|
||||
if (segment.prev == null) {
|
||||
Vec3d roundEnd = segment.startPoint.point.copy().subtract(segment.diff.copy().normalize().multiply(width));
|
||||
|
||||
tessellator.startDrawingQuads();
|
||||
tessellator.setBrightness(0xF000F0);
|
||||
tessellator.setColorRGBA(c.getRed(), c.getGreen(), c.getBlue(), alpha);
|
||||
|
||||
tessellator.addVertex(startVec.x - diff1.x, startVec.y - diff1.y, startVec.z - diff1.z);
|
||||
tessellator.addVertex(roundEnd.x - diff1.x, roundEnd.y - diff1.y, roundEnd.z - diff1.z);
|
||||
tessellator.addVertex(roundEnd.x + diff1.x, roundEnd.y + diff1.y, roundEnd.z + diff1.z);
|
||||
tessellator.addVertex(startVec.x + diff1.x, startVec.y + diff1.y, startVec.z + diff1.z);
|
||||
|
||||
tessellator.draw();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a lightning bolt between two points.
|
||||
*
|
||||
* @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)
|
||||
*/
|
||||
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);
|
||||
bolt.defaultFractal();
|
||||
bolt.finalizeBolt();
|
||||
LightningBolt.boltList.add(bolt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a lightning bolt with automatic seed.
|
||||
*/
|
||||
public static void spawnLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, int colorOuter, int colorInner) {
|
||||
spawnLightningBolt(world, start, end, ticksPerMeter, System.nanoTime(), colorOuter, colorInner);
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a simple lightning bolt for projectiles - less detail, faster.
|
||||
*/
|
||||
public static void spawnSimpleLightningBolt(World world, Vec3d start, Vec3d end, float ticksPerMeter, int colorOuter, int colorInner) {
|
||||
LightningBolt bolt = new LightningBolt(world, start, end, ticksPerMeter, System.nanoTime(), colorOuter, colorInner);
|
||||
bolt.simpleFractal();
|
||||
bolt.finalizeBolt();
|
||||
LightningBolt.boltList.add(bolt);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package kamkeel.npcs.client.renderer.lightning;
|
||||
|
||||
/**
|
||||
* Quaternion class for axis-angle rotations in lightning calculations.
|
||||
* Adapted from Botania's Quat by ChickenBones.
|
||||
*/
|
||||
public class Quaternion {
|
||||
public double x;
|
||||
public double y;
|
||||
public double z;
|
||||
public double s;
|
||||
|
||||
public Quaternion() {
|
||||
s = 1.0;
|
||||
x = 0.0;
|
||||
y = 0.0;
|
||||
z = 0.0;
|
||||
}
|
||||
|
||||
public Quaternion(Quaternion quat) {
|
||||
x = quat.x;
|
||||
y = quat.y;
|
||||
z = quat.z;
|
||||
s = quat.s;
|
||||
}
|
||||
|
||||
public Quaternion(double s, double x, double y, double z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
this.s = s;
|
||||
}
|
||||
|
||||
public static Quaternion aroundAxis(double ax, double ay, double az, double angle) {
|
||||
angle *= 0.5;
|
||||
double sinAngle = Math.sin(angle);
|
||||
return new Quaternion(Math.cos(angle), ax * sinAngle, ay * sinAngle, az * sinAngle);
|
||||
}
|
||||
|
||||
public static Quaternion aroundAxis(Vec3d axis, double angle) {
|
||||
return aroundAxis(axis.x, axis.y, axis.z, angle);
|
||||
}
|
||||
|
||||
public void multiply(Quaternion quat) {
|
||||
double d = s * quat.s - x * quat.x - y * quat.y - z * quat.z;
|
||||
double d1 = s * quat.x + x * quat.s - y * quat.z + z * quat.y;
|
||||
double d2 = s * quat.y + x * quat.z + y * quat.s - z * quat.x;
|
||||
double d3 = s * quat.z - x * quat.y + y * quat.x + z * quat.s;
|
||||
s = d;
|
||||
x = d1;
|
||||
y = d2;
|
||||
z = d3;
|
||||
}
|
||||
|
||||
public double mag() {
|
||||
return Math.sqrt(x * x + y * y + z * z + s * s);
|
||||
}
|
||||
|
||||
public void normalize() {
|
||||
double d = mag();
|
||||
if (d == 0.0) {
|
||||
return;
|
||||
}
|
||||
d = 1.0 / d;
|
||||
x *= d;
|
||||
y *= d;
|
||||
z *= d;
|
||||
s *= d;
|
||||
}
|
||||
|
||||
public void rotate(Vec3d vec) {
|
||||
double d = -x * vec.x - y * vec.y - z * vec.z;
|
||||
double d1 = s * vec.x + y * vec.z - z * vec.y;
|
||||
double d2 = s * vec.y - x * vec.z + z * vec.x;
|
||||
double d3 = s * vec.z + x * vec.y - y * vec.x;
|
||||
vec.x = d1 * s - d * x - d2 * z + d3 * y;
|
||||
vec.y = d2 * s - d * y + d1 * z - d3 * x;
|
||||
vec.z = d3 * s - d * z - d1 * y + d2 * x;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Quaternion(" + s + ", " + x + ", " + y + ", " + z + ")";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package kamkeel.npcs.client.renderer.lightning;
|
||||
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.util.Vec3;
|
||||
import org.lwjgl.opengl.GL11;
|
||||
|
||||
/**
|
||||
* 3D Vector helper class for lightning calculations.
|
||||
* Adapted from Botania's Vector3 by ChickenBones.
|
||||
*/
|
||||
public class Vec3d {
|
||||
public double x;
|
||||
public double y;
|
||||
public double z;
|
||||
|
||||
public Vec3d() {
|
||||
}
|
||||
|
||||
public Vec3d(double x, double y, double z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
}
|
||||
|
||||
public Vec3d(Vec3d vec) {
|
||||
this.x = vec.x;
|
||||
this.y = vec.y;
|
||||
this.z = vec.z;
|
||||
}
|
||||
|
||||
public Vec3d(Vec3 vec) {
|
||||
this.x = vec.xCoord;
|
||||
this.y = vec.yCoord;
|
||||
this.z = vec.zCoord;
|
||||
}
|
||||
|
||||
public Vec3d copy() {
|
||||
return new Vec3d(this);
|
||||
}
|
||||
|
||||
public static Vec3d fromEntity(Entity e) {
|
||||
return new Vec3d(e.posX, e.posY, e.posZ);
|
||||
}
|
||||
|
||||
public static Vec3d fromEntityCenter(Entity e) {
|
||||
return new Vec3d(e.posX, e.posY - e.yOffset + e.height / 2, e.posZ);
|
||||
}
|
||||
|
||||
public Vec3d set(double x, double y, double z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vec3d set(Vec3d vec) {
|
||||
this.x = vec.x;
|
||||
this.y = vec.y;
|
||||
this.z = vec.z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public double dotProduct(Vec3d vec) {
|
||||
double d = vec.x * x + vec.y * y + vec.z * z;
|
||||
if (d > 1 && d < 1.00001) d = 1;
|
||||
else if (d < -1 && d > -1.00001) d = -1;
|
||||
return d;
|
||||
}
|
||||
|
||||
public Vec3d crossProduct(Vec3d vec) {
|
||||
double d = y * vec.z - z * vec.y;
|
||||
double d1 = z * vec.x - x * vec.z;
|
||||
double d2 = x * vec.y - y * vec.x;
|
||||
x = d;
|
||||
y = d1;
|
||||
z = d2;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vec3d add(double x, double y, double z) {
|
||||
this.x += x;
|
||||
this.y += y;
|
||||
this.z += z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vec3d add(Vec3d vec) {
|
||||
this.x += vec.x;
|
||||
this.y += vec.y;
|
||||
this.z += vec.z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vec3d subtract(Vec3d vec) {
|
||||
this.x -= vec.x;
|
||||
this.y -= vec.y;
|
||||
this.z -= vec.z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vec3d multiply(double d) {
|
||||
this.x *= d;
|
||||
this.y *= d;
|
||||
this.z *= d;
|
||||
return this;
|
||||
}
|
||||
|
||||
public double mag() {
|
||||
return Math.sqrt(x * x + y * y + z * z);
|
||||
}
|
||||
|
||||
public double magSquared() {
|
||||
return x * x + y * y + z * z;
|
||||
}
|
||||
|
||||
public Vec3d normalize() {
|
||||
double d = mag();
|
||||
if (d != 0) {
|
||||
multiply(1 / d);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vec3d perpendicular() {
|
||||
if (z == 0) {
|
||||
return zCrossProduct();
|
||||
}
|
||||
return xCrossProduct();
|
||||
}
|
||||
|
||||
public Vec3d xCrossProduct() {
|
||||
double d = z;
|
||||
double d1 = -y;
|
||||
x = 0;
|
||||
y = d;
|
||||
z = d1;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vec3d zCrossProduct() {
|
||||
double d = y;
|
||||
double d1 = -x;
|
||||
x = d;
|
||||
y = d1;
|
||||
z = 0;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vec3 toVec3() {
|
||||
return Vec3.createVectorHelper(x, y, z);
|
||||
}
|
||||
|
||||
public double angle(Vec3d vec) {
|
||||
return Math.acos(copy().normalize().dotProduct(vec.copy().normalize()));
|
||||
}
|
||||
|
||||
public Vec3d negate() {
|
||||
x = -x;
|
||||
y = -y;
|
||||
z = -z;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Vec3d rotate(double angle, Vec3d axis) {
|
||||
Quaternion.aroundAxis(axis.copy().normalize(), angle).rotate(this);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void glVertex() {
|
||||
GL11.glVertex3d(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Vec3d(" + x + ", " + y + ", " + z + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof Vec3d)) return false;
|
||||
Vec3d v = (Vec3d) o;
|
||||
return x == v.x && y == v.y && z == v.z;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
package kamkeel.npcs.command;
|
||||
|
||||
import kamkeel.npcs.controllers.AbilityController;
|
||||
import kamkeel.npcs.controllers.data.ability.Ability;
|
||||
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;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static kamkeel.npcs.util.ColorUtil.sendError;
|
||||
import static kamkeel.npcs.util.ColorUtil.sendResult;
|
||||
|
||||
public class AbilityCommand extends CommandKamkeelBase {
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return "ability";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Ability operations";
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "List all custom abilities"
|
||||
)
|
||||
public void list(ICommandSender sender, String[] args) {
|
||||
Set<String> names = AbilityController.Instance.getCustomAbilityNames();
|
||||
if (names.isEmpty()) {
|
||||
sendResult(sender, "No custom abilities found.");
|
||||
return;
|
||||
}
|
||||
|
||||
sendResult(sender, "Custom Abilities (" + names.size() + "):");
|
||||
for (String name : names) {
|
||||
Ability ability = AbilityController.Instance.getCustomAbility(name);
|
||||
if (ability != null) {
|
||||
sendResult(sender, " - \u00A7b" + name + "\u00A77 (" + ability.getTypeId() + ")");
|
||||
} else {
|
||||
sendResult(sender, " - \u00A7b" + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "List all registered ability types"
|
||||
)
|
||||
public void types(ICommandSender sender, String[] args) {
|
||||
String[] typeIds = AbilityController.Instance.getTypes();
|
||||
if (typeIds.length == 0) {
|
||||
sendResult(sender, "No ability types registered.");
|
||||
return;
|
||||
}
|
||||
|
||||
List<String> sortedTypes = new ArrayList<>();
|
||||
for (String typeId : typeIds) {
|
||||
sortedTypes.add(typeId);
|
||||
}
|
||||
Collections.sort(sortedTypes);
|
||||
|
||||
sendResult(sender, "Registered Ability Types (" + sortedTypes.size() + "):");
|
||||
for (String typeId : sortedTypes) {
|
||||
sendResult(sender, " - \u00A7d" + typeId);
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Reload abilities from disk"
|
||||
)
|
||||
public void reload(ICommandSender sender, String[] args) {
|
||||
AbilityController.Instance.load();
|
||||
sendResult(sender, "Abilities and chained abilities reloaded from disk.");
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
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 <name>");
|
||||
return;
|
||||
}
|
||||
|
||||
String name = joinArgs(args, 0);
|
||||
if (!AbilityController.Instance.hasCustomAbilityName(name)) {
|
||||
sendError(sender, "No custom ability with name: " + name);
|
||||
return;
|
||||
}
|
||||
|
||||
AbilityController.Instance.deleteCustomAbility(name);
|
||||
sendResult(sender, "Deleted ability: \u00A7b" + name);
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Get info about an ability",
|
||||
usage = "<name or uuid>"
|
||||
)
|
||||
public void info(ICommandSender sender, String[] args) {
|
||||
if (args.length < 1) {
|
||||
sendError(sender, "Usage: /kam ability info <name or uuid>");
|
||||
return;
|
||||
}
|
||||
|
||||
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.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");
|
||||
if (ability.isInterruptible()) {
|
||||
sendResult(sender, " Dazed: \u00A7e" + ability.getDazedTicks() + " ticks");
|
||||
}
|
||||
sendResult(sender, " Range: \u00A7e" + ability.getMinRange() + " - " + ability.getMaxRange());
|
||||
sendResult(sender, " Telegraph: \u00A7e" + (ability.isShowTelegraph() ? "Yes" : "No"));
|
||||
sendResult(sender, " Allowed By: \u00A7e" + ability.getAllowedBy().name());
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "List all built-in abilities available for players"
|
||||
)
|
||||
public void prebuilts(ICommandSender sender, String[] args) {
|
||||
Set<String> names = AbilityController.Instance.getAbilityNames();
|
||||
if (names.isEmpty()) {
|
||||
sendResult(sender, "No built-in abilities found.");
|
||||
return;
|
||||
}
|
||||
|
||||
List<String> playerAbilities = new ArrayList<>();
|
||||
for (String name : names) {
|
||||
Ability ability = AbilityController.Instance.getAbility(name);
|
||||
if (ability != null && ability.getAllowedBy().allowsPlayer()) {
|
||||
playerAbilities.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
if (playerAbilities.isEmpty()) {
|
||||
sendResult(sender, "No player-usable built-in abilities found.");
|
||||
return;
|
||||
}
|
||||
|
||||
Collections.sort(playerAbilities);
|
||||
sendResult(sender, "Built-in Player Abilities (" + playerAbilities.size() + "):");
|
||||
for (String name : playerAbilities) {
|
||||
Ability ability = AbilityController.Instance.getAbility(name);
|
||||
String userType = ability.getAllowedBy() == UserType.PLAYER_ONLY ? "\u00A7d[PLAYER]" : "\u00A7a[BOTH]";
|
||||
sendResult(sender, " - \u00A7b" + name + " " + userType);
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Give an ability to a player",
|
||||
usage = "<player> <ability>"
|
||||
)
|
||||
public void give(ICommandSender sender, String[] args) {
|
||||
if (args.length < 2) {
|
||||
sendError(sender, "Usage: /kam ability give <player> <ability>");
|
||||
return;
|
||||
}
|
||||
|
||||
String playerName = args[0];
|
||||
String abilityKey = joinArgs(args, 1);
|
||||
|
||||
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
|
||||
if (player == null) {
|
||||
sendError(sender, "Player not found: " + playerName);
|
||||
return;
|
||||
}
|
||||
|
||||
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
|
||||
if (ability == null) {
|
||||
sendError(sender, "Ability not found: " + abilityKey);
|
||||
return;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
String displayName = ability.getDisplayName();
|
||||
|
||||
if (!ability.getAllowedBy().allowsPlayer()) {
|
||||
sendError(sender, "Ability '\u00A7b" + displayName + "\u00A7c' is NPC-only and cannot be given to players.");
|
||||
return;
|
||||
}
|
||||
|
||||
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
|
||||
if (data.abilityData.hasUnlockedAbility(canonicalKey)) {
|
||||
sendError(sender, "Player already has ability: " + displayName);
|
||||
return;
|
||||
}
|
||||
|
||||
data.abilityData.unlockAbility(canonicalKey);
|
||||
sendResult(sender, "Gave ability '\u00A7b" + displayName + "\u00A77' to player \u00A7a" + playerName);
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Remove an ability from a player",
|
||||
usage = "<player> <ability>"
|
||||
)
|
||||
public void remove(ICommandSender sender, String[] args) {
|
||||
if (args.length < 2) {
|
||||
sendError(sender, "Usage: /kam ability remove <player> <ability>");
|
||||
return;
|
||||
}
|
||||
|
||||
String playerName = args[0];
|
||||
String abilityKey = joinArgs(args, 1);
|
||||
|
||||
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
|
||||
if (player == null) {
|
||||
sendError(sender, "Player not found: " + playerName);
|
||||
return;
|
||||
}
|
||||
|
||||
Ability ability = AbilityController.Instance.resolveAbility(abilityKey);
|
||||
if (ability == null) {
|
||||
sendError(sender, "Ability not found: " + abilityKey);
|
||||
return;
|
||||
}
|
||||
String canonicalKey = ability.getId() != null ? ability.getId() : abilityKey;
|
||||
String displayName = ability.getDisplayName();
|
||||
|
||||
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
|
||||
if (!data.abilityData.hasUnlockedAbility(canonicalKey)) {
|
||||
sendError(sender, "Player doesn't have ability: " + displayName);
|
||||
return;
|
||||
}
|
||||
|
||||
data.abilityData.lockAbility(canonicalKey);
|
||||
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(
|
||||
desc = "List abilities unlocked for a player",
|
||||
usage = "<player>"
|
||||
)
|
||||
public void player(ICommandSender sender, String[] args) {
|
||||
if (args.length < 1) {
|
||||
sendError(sender, "Usage: /kam ability player <player>");
|
||||
return;
|
||||
}
|
||||
|
||||
String playerName = args[0];
|
||||
|
||||
// Find player
|
||||
EntityPlayerMP player = (EntityPlayerMP) NoppesUtilServer.getPlayerByName(playerName);
|
||||
if (player == null) {
|
||||
sendError(sender, "Player not found: " + playerName);
|
||||
return;
|
||||
}
|
||||
|
||||
PlayerData data = PlayerDataController.Instance.getPlayerData(player);
|
||||
String[] abilityKeys = data.abilityData.getUnlockedAbilities();
|
||||
|
||||
if (abilityKeys.length == 0) {
|
||||
sendResult(sender, "Player \u00A7a" + playerName + "\u00A77 has no unlocked abilities.");
|
||||
return;
|
||||
}
|
||||
|
||||
sendResult(sender, "Abilities for \u00A7a" + playerName + "\u00A77 (" + abilityKeys.length + "):");
|
||||
int selected = data.abilityData.getSelectedIndex();
|
||||
for (int i = 0; i < abilityKeys.length; i++) {
|
||||
String key = abilityKeys[i];
|
||||
String prefix = (i == selected) ? "\u00A7e> " : " ";
|
||||
|
||||
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 {
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String joinArgs(String[] args, int startIndex) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = startIndex; i < args.length; i++) {
|
||||
if (i > startIndex) sb.append(" ");
|
||||
sb.append(args[i]);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package kamkeel.npcs.command;
|
||||
|
||||
import kamkeel.npcs.command.auction.BlacklistSubCommand;
|
||||
import net.minecraft.command.CommandException;
|
||||
import net.minecraft.command.ICommandSender;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import noppes.npcs.NoppesUtilServer;
|
||||
import noppes.npcs.config.ConfigMarket;
|
||||
import noppes.npcs.constants.EnumGuiType;
|
||||
import noppes.npcs.controllers.AuctionController;
|
||||
import noppes.npcs.controllers.PlayerDataController;
|
||||
import noppes.npcs.controllers.data.AuctionListing;
|
||||
import noppes.npcs.controllers.data.PlayerData;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static kamkeel.npcs.util.ColorUtil.sendError;
|
||||
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();
|
||||
registerNestedCommand(new BlacklistSubCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return "auction";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Auction operations";
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "List active auctions",
|
||||
usage = "[page]"
|
||||
)
|
||||
public void list(ICommandSender sender, String[] args) throws CommandException {
|
||||
if (!ConfigMarket.AuctionEnabled) {
|
||||
sendError(sender, "Auction system is disabled");
|
||||
return;
|
||||
}
|
||||
|
||||
AuctionController controller = AuctionController.getInstance();
|
||||
if (controller == null) {
|
||||
sendError(sender, "Auction system is not available");
|
||||
return;
|
||||
}
|
||||
|
||||
int page = 1;
|
||||
if (args.length > 0) {
|
||||
try {
|
||||
page = Integer.parseInt(args[0]);
|
||||
} catch (NumberFormatException ex) {
|
||||
sendError(sender, "Invalid page number: " + args[0]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
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 / COMMAND_PAGE_SIZE));
|
||||
|
||||
if (listings.isEmpty()) {
|
||||
sendMessage(sender, "\u00A77No active auctions found");
|
||||
return;
|
||||
}
|
||||
|
||||
sendMessage(sender, String.format("\u00A76=== Active Auctions (Page %d/%d) ===", page, totalPages));
|
||||
for (AuctionListing listing : listings) {
|
||||
String itemName = listing.item != null ? listing.item.getDisplayName() : "Unknown";
|
||||
String price = listing.hasBids() ?
|
||||
String.format("%,d (bid)", listing.currentBid) :
|
||||
String.format("%,d (start)", listing.startingPrice);
|
||||
sendMessage(sender, String.format("\u00A7e%s \u00A77by \u00A7b%s\u00A77 - \u00A76%s %s",
|
||||
itemName, listing.sellerName, price, ConfigMarket.CurrencyName));
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "View player's auction activity",
|
||||
usage = "<player>"
|
||||
)
|
||||
public void view(ICommandSender sender, String[] args) throws CommandException {
|
||||
if (!ConfigMarket.AuctionEnabled) {
|
||||
sendError(sender, "Auction system is disabled");
|
||||
return;
|
||||
}
|
||||
|
||||
AuctionController controller = AuctionController.getInstance();
|
||||
if (controller == null) {
|
||||
sendError(sender, "Auction system is not available");
|
||||
return;
|
||||
}
|
||||
|
||||
if (args.length < 1) {
|
||||
throw new CommandException("Usage: /auction view <player>");
|
||||
}
|
||||
|
||||
String playername = args[0];
|
||||
List<PlayerData> dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
|
||||
|
||||
if (dataList.isEmpty()) {
|
||||
sendError(sender, "Unknown player: " + playername);
|
||||
return;
|
||||
}
|
||||
|
||||
for (PlayerData playerdata : dataList) {
|
||||
UUID playerUUID = UUID.fromString(playerdata.uuid);
|
||||
List<AuctionListing> activeListings = controller.getPlayerActiveListings(playerUUID);
|
||||
List<AuctionListing> activeBids = controller.getPlayerActiveBids(playerUUID);
|
||||
int claimCount = controller.getPlayerClaims(playerUUID).size();
|
||||
|
||||
sendMessage(sender, String.format("\u00A76=== Auction Activity for %s ===", playerdata.playername));
|
||||
sendMessage(sender, String.format("\u00A77Active Listings: \u00A7e%d", activeListings.size()));
|
||||
sendMessage(sender, String.format("\u00A77Active Bids: \u00A7e%d", activeBids.size()));
|
||||
sendMessage(sender, String.format("\u00A77Pending Claims: \u00A7e%d", claimCount));
|
||||
|
||||
if (!activeListings.isEmpty()) {
|
||||
sendMessage(sender, "\u00A7a--- Selling ---");
|
||||
for (AuctionListing listing : activeListings) {
|
||||
String itemName = listing.item != null ? listing.item.getDisplayName() : "Unknown";
|
||||
String price = listing.hasBids() ?
|
||||
String.format("%,d (bid)", listing.currentBid) :
|
||||
String.format("%,d (start)", listing.startingPrice);
|
||||
sendMessage(sender, String.format(" \u00A7e%s \u00A77- \u00A76%s", itemName, price));
|
||||
}
|
||||
}
|
||||
|
||||
if (!activeBids.isEmpty()) {
|
||||
sendMessage(sender, "\u00A7e--- Bidding ---");
|
||||
for (AuctionListing bid : activeBids) {
|
||||
String itemName = bid.item != null ? bid.item.getDisplayName() : "Unknown";
|
||||
sendMessage(sender, String.format(" \u00A7e%s \u00A77- \u00A76%,d %s",
|
||||
itemName, bid.currentBid, ConfigMarket.CurrencyName));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Open the Auction GUI",
|
||||
usage = "",
|
||||
permission = 0
|
||||
)
|
||||
public void open(ICommandSender sender, String[] args) throws CommandException {
|
||||
if (!ConfigMarket.AuctionEnabled) {
|
||||
sendError(sender, "Auction system is disabled");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(sender instanceof EntityPlayer)) {
|
||||
sendError(sender, "This command can only be used by players");
|
||||
return;
|
||||
}
|
||||
|
||||
EntityPlayer player = (EntityPlayer) sender;
|
||||
|
||||
// Open the auction GUI without requiring an NPC
|
||||
NoppesUtilServer.sendOpenGui(player, EnumGuiType.PlayerAuction, null);
|
||||
sendResult(sender, "Opening Auction...");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List addTabCompletionOptions(ICommandSender sender, String[] args) {
|
||||
if (args.length == 1) {
|
||||
return getListOfStringsMatchingLastWord(args, getAllSubCommandNames());
|
||||
}
|
||||
|
||||
// Delegate to nested commands for deeper tab completion
|
||||
List nestedCompletions = getNestedTabCompletions(sender, args);
|
||||
if (nestedCompletions != null) {
|
||||
return nestedCompletions;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import net.minecraft.util.MathHelper;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.WorldServer;
|
||||
import noppes.npcs.controllers.ServerCloneController;
|
||||
import noppes.npcs.controllers.data.CloneFolder;
|
||||
import noppes.npcs.entity.EntityNPCInterface;
|
||||
|
||||
import java.util.List;
|
||||
@@ -35,20 +36,24 @@ public class CloneCommand extends CommandKamkeelBase {
|
||||
|
||||
@SubCommand(
|
||||
desc = "Add NPC(s) to clone storage",
|
||||
usage = "<npc> <tab> [clonedname]",
|
||||
usage = "<npc> <tab|folder> [clonedname]",
|
||||
permission = 4
|
||||
)
|
||||
public void add(ICommandSender sender, String[] args) {
|
||||
int tab = 0;
|
||||
int tab = -1;
|
||||
String folder = null;
|
||||
try {
|
||||
tab = Integer.parseInt(args[1]);
|
||||
if (tab < 0 || tab > 15) {
|
||||
if (tab < 1 || tab > 15) {
|
||||
sendError(sender, "Tab must be within 1-15");
|
||||
return;
|
||||
}
|
||||
} catch (NumberFormatException ex) {
|
||||
sendError(sender, String.format("Tab is not a number: %s", args[1]));
|
||||
return;
|
||||
folder = args[1];
|
||||
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
|
||||
sendError(sender, String.format("Unknown folder: %s", folder));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
int x = sender.getPlayerCoordinates().posX;
|
||||
@@ -64,32 +69,47 @@ public class CloneCommand extends CommandKamkeelBase {
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
if (!npc.writeToNBTOptional(compound))
|
||||
return;
|
||||
ServerCloneController.Instance.addClone(compound, name, tab);
|
||||
sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab));
|
||||
if (folder != null) {
|
||||
ServerCloneController.Instance.addClone(compound, name, folder);
|
||||
sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Folder \u00A7b%s\u00A77", name, folder));
|
||||
} else {
|
||||
ServerCloneController.Instance.addClone(compound, name, tab);
|
||||
sendResult(sender, String.format("Added NPC \u00A7e%s\u00A77 to Tab \u00A7b%d\u00A77", name, tab));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "List NPC from clone storage",
|
||||
usage = "<tab>",
|
||||
usage = "<tab|folder>",
|
||||
permission = 2
|
||||
)
|
||||
public void list(ICommandSender sender, String[] args) {
|
||||
sendMessage(sender, "--- Stored NPCs --- (server side)");
|
||||
int tab = 0;
|
||||
int tab = -1;
|
||||
String folder = null;
|
||||
try {
|
||||
tab = Integer.parseInt(args[1]);
|
||||
if (tab < 0 || tab > 15) {
|
||||
if (tab < 1 || tab > 15) {
|
||||
sendError(sender, "Tab must be within 1-15");
|
||||
return;
|
||||
}
|
||||
} catch (NumberFormatException ex) {
|
||||
sendError(sender, String.format("Tab is not a number: %s", args[1]));
|
||||
return;
|
||||
folder = args[1];
|
||||
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
|
||||
sendError(sender, String.format("Unknown folder: %s", folder));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for (String name : ServerCloneController.Instance.getClones(tab)) {
|
||||
List<String> clones;
|
||||
if (folder != null) {
|
||||
clones = ServerCloneController.Instance.getClones(folder);
|
||||
} else {
|
||||
clones = ServerCloneController.Instance.getClones(tab);
|
||||
}
|
||||
for (String name : clones) {
|
||||
sendMessage(sender, name);
|
||||
}
|
||||
sendMessage(sender, "------------------------------------");
|
||||
@@ -97,59 +117,75 @@ public class CloneCommand extends CommandKamkeelBase {
|
||||
|
||||
@SubCommand(
|
||||
desc = "Remove NPC from clone storage",
|
||||
usage = "<name> <tab>",
|
||||
usage = "<name> <tab|folder>",
|
||||
permission = 4
|
||||
)
|
||||
public void del(ICommandSender sender, String[] args) throws CommandException {
|
||||
String nametodel = args[0];
|
||||
int tab = 0;
|
||||
int tab = -1;
|
||||
String folder = null;
|
||||
try {
|
||||
tab = Integer.parseInt(args[1]);
|
||||
if (tab < 0 || tab > 15) {
|
||||
sendError(sender, String.format("Tab must be within 1-15"));
|
||||
if (tab < 1 || tab > 15) {
|
||||
sendError(sender, "Tab must be within 1-15");
|
||||
return;
|
||||
}
|
||||
} catch (NumberFormatException ex) {
|
||||
sendError(sender, String.format("Tab is not a number: %s", args[1]));
|
||||
return;
|
||||
}
|
||||
|
||||
boolean deleted = false;
|
||||
for (String name : ServerCloneController.Instance.getClones(tab)) {
|
||||
if (nametodel.equalsIgnoreCase(name)) {
|
||||
ServerCloneController.Instance.removeClone(name, tab);
|
||||
deleted = true;
|
||||
break;
|
||||
folder = args[1];
|
||||
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
|
||||
sendError(sender, String.format("Unknown folder: %s", folder));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!ServerCloneController.Instance.removeClone(nametodel, tab)) {
|
||||
|
||||
boolean success;
|
||||
if (folder != null) {
|
||||
success = ServerCloneController.Instance.removeClone(nametodel, folder);
|
||||
} else {
|
||||
success = ServerCloneController.Instance.removeClone(nametodel, tab);
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
sendError(sender, String.format("NPC '%s' was not found", nametodel));
|
||||
} else {
|
||||
sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab));
|
||||
if (folder != null) {
|
||||
sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Folder \u00A7b%s\u00A77", nametodel, folder));
|
||||
} else {
|
||||
sendResult(sender, String.format("Removed NPC \u00A7e%s\u00A77 from Tab \u00A7b%d\u00A77", nametodel, tab));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Spawn cloned NPC",
|
||||
usage = "<name> <tab> [[world:]x,y,z]] [newname]",
|
||||
usage = "<name> <tab|folder> [[world:]x,y,z]] [newname]",
|
||||
permission = 2
|
||||
)
|
||||
public void spawn(ICommandSender sender, String[] args) throws CommandException {
|
||||
String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space
|
||||
int tab = 0;
|
||||
int tab = -1;
|
||||
String folder = null;
|
||||
try {
|
||||
tab = Integer.parseInt(args[1]);
|
||||
if (tab < 0 || tab > 15) {
|
||||
sendError(sender, String.format("Tab must be within 1-15"));
|
||||
if (tab < 1 || tab > 15) {
|
||||
sendError(sender, "Tab must be within 1-15");
|
||||
return;
|
||||
}
|
||||
} catch (NumberFormatException ex) {
|
||||
sendError(sender, String.format("Tab is not a number: %s", args[1]));
|
||||
return;
|
||||
folder = args[1];
|
||||
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
|
||||
sendError(sender, String.format("Unknown folder: %s", folder));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
String newname = null;
|
||||
NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
|
||||
NBTTagCompound compound;
|
||||
if (folder != null) {
|
||||
compound = ServerCloneController.Instance.getCloneData(sender, name, folder);
|
||||
} else {
|
||||
compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
|
||||
}
|
||||
if (compound == null) {
|
||||
sendError(sender, "Unknown npc");
|
||||
return;
|
||||
@@ -211,22 +247,26 @@ public class CloneCommand extends CommandKamkeelBase {
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Spawn cloned NPC",
|
||||
usage = "<name> <tab> [[world:]x,y,z]] [newname]",
|
||||
desc = "Spawn cloned NPC in a grid",
|
||||
usage = "<name> <tab|folder> <width> <height> [[world:]x,y,z]] [newname]",
|
||||
permission = 2
|
||||
)
|
||||
public void grid(ICommandSender sender, String[] args) throws CommandException {
|
||||
String name = args[0].replaceAll("%", " "); // if name of npc separed by space, user must use % in place of space
|
||||
int tab = 0;
|
||||
int tab = -1;
|
||||
String folder = null;
|
||||
try {
|
||||
tab = Integer.parseInt(args[1]);
|
||||
if (tab < 0 || tab > 15) {
|
||||
sendError(sender, String.format("Tab must be within 1-15"));
|
||||
if (tab < 1 || tab > 15) {
|
||||
sendError(sender, "Tab must be within 1-15");
|
||||
return;
|
||||
}
|
||||
} catch (NumberFormatException ex) {
|
||||
sendError(sender, String.format("Tab is not a number: %s", args[1]));
|
||||
return;
|
||||
folder = args[1];
|
||||
if (ServerCloneController.Instance == null || !ServerCloneController.Instance.hasFolder(folder)) {
|
||||
sendError(sender, String.format("Unknown folder: %s", folder));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
int width, height;
|
||||
@@ -238,9 +278,13 @@ public class CloneCommand extends CommandKamkeelBase {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
String newname = null;
|
||||
NBTTagCompound compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
|
||||
NBTTagCompound compound;
|
||||
if (folder != null) {
|
||||
compound = ServerCloneController.Instance.getCloneData(sender, name, folder);
|
||||
} else {
|
||||
compound = ServerCloneController.Instance.getCloneData(sender, name, tab);
|
||||
}
|
||||
if (compound == null) {
|
||||
sendError(sender, "Unknown npc");
|
||||
return;
|
||||
@@ -317,6 +361,163 @@ public class CloneCommand extends CommandKamkeelBase {
|
||||
return;
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "List all custom clone folders",
|
||||
usage = "",
|
||||
permission = 2
|
||||
)
|
||||
public void listfolders(ICommandSender sender, String[] args) {
|
||||
if (ServerCloneController.Instance == null) {
|
||||
sendError(sender, "Folder system not initialized");
|
||||
return;
|
||||
}
|
||||
sendMessage(sender, "--- Clone Folders ---");
|
||||
for (CloneFolder f : ServerCloneController.Instance.getFolderList()) {
|
||||
sendMessage(sender, f.name);
|
||||
}
|
||||
sendMessage(sender, "------------------------------------");
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Create a custom clone folder",
|
||||
usage = "<name>",
|
||||
permission = 4
|
||||
)
|
||||
public void createfolder(ICommandSender sender, String[] args) {
|
||||
if (ServerCloneController.Instance == null) {
|
||||
sendError(sender, "Folder system not initialized");
|
||||
return;
|
||||
}
|
||||
String name = args[0];
|
||||
if (!CloneFolder.isValidName(name)) {
|
||||
sendError(sender, String.format("Invalid folder name: %s", name));
|
||||
return;
|
||||
}
|
||||
if (ServerCloneController.Instance.hasFolder(name)) {
|
||||
sendError(sender, String.format("Folder '%s' already exists", name));
|
||||
return;
|
||||
}
|
||||
CloneFolder created = ServerCloneController.Instance.createFolder(name);
|
||||
if (created != null) {
|
||||
sendResult(sender, String.format("Created folder \u00A7b%s", name));
|
||||
} else {
|
||||
sendError(sender, String.format("Failed to create folder '%s'", name));
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Rename a custom clone folder",
|
||||
usage = "<oldname> <newname>",
|
||||
permission = 4
|
||||
)
|
||||
public void renamefolder(ICommandSender sender, String[] args) {
|
||||
if (ServerCloneController.Instance == null) {
|
||||
sendError(sender, "Folder system not initialized");
|
||||
return;
|
||||
}
|
||||
String oldName = args[0];
|
||||
String newName = args[1];
|
||||
if (!ServerCloneController.Instance.hasFolder(oldName)) {
|
||||
sendError(sender, String.format("Unknown folder: %s", oldName));
|
||||
return;
|
||||
}
|
||||
if (!CloneFolder.isValidName(newName)) {
|
||||
sendError(sender, String.format("Invalid folder name: %s", newName));
|
||||
return;
|
||||
}
|
||||
if (ServerCloneController.Instance.renameFolder(oldName, newName)) {
|
||||
sendResult(sender, String.format("Renamed folder \u00A7b%s\u00A77 to \u00A7b%s", oldName, newName));
|
||||
} else {
|
||||
sendError(sender, String.format("Failed to rename folder '%s'", oldName));
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Delete an empty custom clone folder",
|
||||
usage = "<name>",
|
||||
permission = 4
|
||||
)
|
||||
public void deletefolder(ICommandSender sender, String[] args) {
|
||||
if (ServerCloneController.Instance == null) {
|
||||
sendError(sender, "Folder system not initialized");
|
||||
return;
|
||||
}
|
||||
String name = args[0];
|
||||
if (!ServerCloneController.Instance.hasFolder(name)) {
|
||||
sendError(sender, String.format("Unknown folder: %s", name));
|
||||
return;
|
||||
}
|
||||
if (ServerCloneController.Instance.deleteFolder(name)) {
|
||||
sendResult(sender, String.format("Deleted folder \u00A7b%s", name));
|
||||
} else {
|
||||
sendError(sender, String.format("Failed to delete folder '%s' (folder must be empty)", name));
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Move a clone between tabs/folders",
|
||||
usage = "<clonename> <from_tab|folder> <to_tab|folder>",
|
||||
permission = 4
|
||||
)
|
||||
public void move(ICommandSender sender, String[] args) {
|
||||
if (ServerCloneController.Instance == null) {
|
||||
sendError(sender, "Folder system not initialized");
|
||||
return;
|
||||
}
|
||||
String cloneName = args[0];
|
||||
|
||||
int fromTab = -1;
|
||||
String fromFolder = null;
|
||||
try {
|
||||
fromTab = Integer.parseInt(args[1]);
|
||||
if (fromTab < 1 || fromTab > 15) {
|
||||
sendError(sender, "Source tab must be within 1-15");
|
||||
return;
|
||||
}
|
||||
} catch (NumberFormatException ex) {
|
||||
fromFolder = args[1];
|
||||
if (!ServerCloneController.Instance.hasFolder(fromFolder)) {
|
||||
sendError(sender, String.format("Unknown source folder: %s", fromFolder));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
int toTab = -1;
|
||||
String toFolder = null;
|
||||
try {
|
||||
toTab = Integer.parseInt(args[2]);
|
||||
if (toTab < 1 || toTab > 15) {
|
||||
sendError(sender, "Destination tab must be within 1-15");
|
||||
return;
|
||||
}
|
||||
} catch (NumberFormatException ex) {
|
||||
toFolder = args[2];
|
||||
if (!ServerCloneController.Instance.hasFolder(toFolder)) {
|
||||
sendError(sender, String.format("Unknown destination folder: %s", toFolder));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
boolean success;
|
||||
if (fromFolder != null && toFolder != null) {
|
||||
success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toFolder);
|
||||
} else if (fromFolder != null) {
|
||||
success = ServerCloneController.Instance.moveClone(cloneName, fromFolder, toTab);
|
||||
} else if (toFolder != null) {
|
||||
success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toFolder);
|
||||
} else {
|
||||
success = ServerCloneController.Instance.moveClone(cloneName, fromTab, toTab);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
String from = fromFolder != null ? fromFolder : String.valueOf(fromTab);
|
||||
String to = toFolder != null ? toFolder : String.valueOf(toTab);
|
||||
sendResult(sender, String.format("Moved \u00A7e%s\u00A77 from \u00A7b%s\u00A77 to \u00A7b%s", cloneName, from, to));
|
||||
} else {
|
||||
sendError(sender, String.format("Failed to move '%s'", cloneName));
|
||||
}
|
||||
}
|
||||
|
||||
public World getWorld(String t) {
|
||||
WorldServer[] ws = MinecraftServer.getServer().worldServers;
|
||||
for (WorldServer w : ws) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import noppes.npcs.CustomNpcsPermissions;
|
||||
import noppes.npcs.config.ConfigMain;
|
||||
import noppes.npcs.config.ConfigMarket;
|
||||
import noppes.npcs.scripted.CustomNPCsException;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
@@ -19,6 +20,8 @@ import java.util.HashMap;
|
||||
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 {
|
||||
@@ -43,8 +46,13 @@ public class CommandKamkeel extends CommandBase {
|
||||
registerCommand(new OverlayCommand());
|
||||
registerCommand(new CommandCommand());
|
||||
registerCommand(new EffectCommand());
|
||||
registerCommand(new AbilityCommand());
|
||||
registerCommand(new MoneyCommand());
|
||||
if (ConfigMarket.AuctionEnabled)
|
||||
registerCommand(new AuctionCommand());
|
||||
if (ConfigMain.AttributesEnabled)
|
||||
registerCommand(new AttributeCommand());
|
||||
registerCommand(new DebugCommand());
|
||||
}
|
||||
|
||||
public void registerCommand(CommandKamkeelBase command) {
|
||||
@@ -128,7 +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 = 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()]));
|
||||
}
|
||||
}
|
||||
@@ -136,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;
|
||||
|
||||
@@ -12,12 +12,16 @@ import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public abstract class CommandKamkeelBase extends CommandBase {
|
||||
public Map<String, Method> subcommands = new HashMap<String, Method>();
|
||||
public Map<String, CommandKamkeelBase> nestedCommands = new HashMap<String, CommandKamkeelBase>();
|
||||
|
||||
public CommandKamkeelBase() {
|
||||
for (Method m : this.getClass().getDeclaredMethods()) {
|
||||
@@ -31,6 +35,14 @@ public abstract class CommandKamkeelBase extends CommandBase {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a nested command class as a subcommand.
|
||||
* The nested command's getCommandName() becomes the subcommand name.
|
||||
*/
|
||||
public void registerNestedCommand(CommandKamkeelBase command) {
|
||||
nestedCommands.put(command.getCommandName().toLowerCase(), command);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
|
||||
|
||||
@@ -51,7 +63,7 @@ public abstract class CommandKamkeelBase extends CommandBase {
|
||||
}
|
||||
|
||||
public boolean runSubCommands() {
|
||||
return !subcommands.isEmpty();
|
||||
return !subcommands.isEmpty() || !nestedCommands.isEmpty();
|
||||
}
|
||||
|
||||
@Retention(value = RetentionPolicy.RUNTIME)
|
||||
@@ -71,6 +83,22 @@ public abstract class CommandKamkeelBase extends CommandBase {
|
||||
}
|
||||
|
||||
public void processSubCommand(ICommandSender sender, String command, String[] args) throws CommandException {
|
||||
// Check nested commands first
|
||||
CommandKamkeelBase nested = nestedCommands.get(command.toLowerCase());
|
||||
if (nested != null) {
|
||||
if (!canSendNestedCommand(sender, nested)) {
|
||||
throw new CommandException("You are not allowed to use this command: " + command);
|
||||
}
|
||||
|
||||
if (args.length == 0 || !nested.runSubCommands()) {
|
||||
nested.processCommand(sender, args);
|
||||
} else {
|
||||
nested.processSubCommand(sender, args[0], Arrays.copyOfRange(args, 1, args.length));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Fall back to method subcommands
|
||||
Method m = subcommands.get(command.toLowerCase());
|
||||
if (m == null)
|
||||
throw new CommandException("Unknown subcommand " + command);
|
||||
@@ -132,4 +160,55 @@ public abstract class CommandKamkeelBase extends CommandBase {
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean canSendNestedCommand(ICommandSender sender, CommandKamkeelBase nested) {
|
||||
int permission = nested.getRequiredPermissionLevel();
|
||||
String subCommand = nested.getCommandName();
|
||||
|
||||
if (sender.canCommandSenderUseCommand(permission, getSubUniversalPermission())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sender.canCommandSenderUseCommand(permission, getSubCommandPermission(subCommand))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (sender instanceof EntityPlayer) {
|
||||
return CustomNpcsPermissions.hasCustomPermission((EntityPlayer) sender, getSubCommandPermission(subCommand));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// =========================================
|
||||
// Tab Completion Helpers
|
||||
// =========================================
|
||||
|
||||
/**
|
||||
* Get all subcommand names (both method-based and nested)
|
||||
*/
|
||||
public String[] getAllSubCommandNames() {
|
||||
Set<String> names = new HashSet<>();
|
||||
names.addAll(subcommands.keySet());
|
||||
names.addAll(nestedCommands.keySet());
|
||||
return names.toArray(new String[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tab completions for nested command at given depth
|
||||
*/
|
||||
public List getNestedTabCompletions(ICommandSender sender, String[] args) {
|
||||
if (args.length == 0) return null;
|
||||
|
||||
String subCmd = args[0].toLowerCase();
|
||||
CommandKamkeelBase nested = nestedCommands.get(subCmd);
|
||||
|
||||
if (nested != null && args.length > 1) {
|
||||
// Delegate to nested command
|
||||
String[] nestedArgs = Arrays.copyOfRange(args, 1, args.length);
|
||||
return nested.addTabCompletionOptions(sender, nestedArgs);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package kamkeel.npcs.command;
|
||||
|
||||
import kamkeel.npcs.util.CNPCDebug;
|
||||
import net.minecraft.command.CommandException;
|
||||
import net.minecraft.command.ICommandSender;
|
||||
|
||||
import static kamkeel.npcs.util.ColorUtil.sendResult;
|
||||
|
||||
public class DebugCommand extends CommandKamkeelBase {
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return "debug";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Toggle debug logging types";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsage() {
|
||||
return "<type>";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean runSubCommands() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
|
||||
if (args.length == 0) {
|
||||
throw new CommandException("Usage: /kam debug <type> (e.g. energy)");
|
||||
}
|
||||
|
||||
String type = args[0].toLowerCase();
|
||||
boolean newState = CNPCDebug.toggleServer(type);
|
||||
sendResult(sender, "Server debug '" + type + "' " + (newState ? "\u00A7aENABLED" : "\u00A7cDISABLED"));
|
||||
}
|
||||
}
|
||||
@@ -308,6 +308,7 @@ public class EffectCommand extends CommandKamkeelBase {
|
||||
|
||||
// Helper method to find effects by name.
|
||||
private List<EffectEntry> findEffectsByName(String name) {
|
||||
String strippedName = stripColorCodes(name);
|
||||
List<EffectEntry> matches = new ArrayList<>();
|
||||
CustomEffectController controller = CustomEffectController.getInstance();
|
||||
for (Map.Entry<Integer, HashMap<Integer, CustomEffect>> entry : controller.indexMapper.entrySet()) {
|
||||
@@ -317,11 +318,12 @@ public class EffectCommand extends CommandKamkeelBase {
|
||||
for (Map.Entry<Integer, CustomEffect> effectEntry : effects.entrySet()) {
|
||||
int id = effectEntry.getKey();
|
||||
CustomEffect effect = effectEntry.getValue();
|
||||
if (effect.getName().equalsIgnoreCase(name)) {
|
||||
String effectName = stripColorCodes(effect.getName());
|
||||
if (effectName.equalsIgnoreCase(strippedName)) {
|
||||
List<EffectEntry> exact = new ArrayList<>();
|
||||
exact.add(new EffectEntry(idx, id, effect));
|
||||
return exact;
|
||||
} else if (effect.getName().toLowerCase().contains(name.toLowerCase())) {
|
||||
} else if (effectName.toLowerCase().contains(strippedName.toLowerCase())) {
|
||||
matches.add(new EffectEntry(idx, id, effect));
|
||||
}
|
||||
}
|
||||
@@ -329,6 +331,10 @@ public class EffectCommand extends CommandKamkeelBase {
|
||||
return matches;
|
||||
}
|
||||
|
||||
private static String stripColorCodes(String s) {
|
||||
return s.replaceAll("\u00A7[0-9a-fk-or]", "");
|
||||
}
|
||||
|
||||
public static List<String> getSortedEffectNames() {
|
||||
List<EffectEntry> entries = new ArrayList<>();
|
||||
CustomEffectController controller = CustomEffectController.getInstance();
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package kamkeel.npcs.command;
|
||||
|
||||
import net.minecraft.command.CommandException;
|
||||
import net.minecraft.command.ICommandSender;
|
||||
import noppes.npcs.config.ConfigMarket;
|
||||
import noppes.npcs.controllers.PlayerDataController;
|
||||
import noppes.npcs.controllers.data.PlayerData;
|
||||
import noppes.npcs.controllers.data.PlayerTradeData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static kamkeel.npcs.util.ColorUtil.sendError;
|
||||
import static kamkeel.npcs.util.ColorUtil.sendResult;
|
||||
|
||||
public class MoneyCommand extends CommandKamkeelBase {
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return "money";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Currency operations";
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Show player's balance",
|
||||
usage = "<player>"
|
||||
)
|
||||
public void balance(ICommandSender sender, String[] args) throws CommandException {
|
||||
String playername = args[0];
|
||||
List<PlayerData> dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
|
||||
|
||||
if (dataList.isEmpty()) {
|
||||
sendError(sender, "Unknown player: " + playername);
|
||||
return;
|
||||
}
|
||||
|
||||
for (PlayerData playerdata : dataList) {
|
||||
PlayerTradeData currency = playerdata.tradeData;
|
||||
long balance = currency.getBalance();
|
||||
sendResult(sender, String.format("Player \u00A7b%s\u00A77 has \u00A76%,d %s",
|
||||
playerdata.playername, balance, ConfigMarket.CurrencyName));
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Give currency to player",
|
||||
usage = "<player> <amount>"
|
||||
)
|
||||
public void give(ICommandSender sender, String[] args) throws CommandException {
|
||||
String playername = args[0];
|
||||
long amount;
|
||||
try {
|
||||
amount = Long.parseLong(args[1]);
|
||||
} catch (NumberFormatException ex) {
|
||||
sendError(sender, "Invalid amount: " + args[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (amount <= 0) {
|
||||
sendError(sender, "Amount must be positive");
|
||||
return;
|
||||
}
|
||||
|
||||
List<PlayerData> dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
|
||||
|
||||
if (dataList.isEmpty()) {
|
||||
sendError(sender, "Unknown player: " + playername);
|
||||
return;
|
||||
}
|
||||
|
||||
for (PlayerData playerdata : dataList) {
|
||||
PlayerTradeData currency = playerdata.tradeData;
|
||||
if (currency.deposit(amount)) {
|
||||
playerdata.save();
|
||||
sendResult(sender, String.format("Gave \u00A76%,d %s\u00A77 to player \u00A7b%s\u00A77. New balance: \u00A76%,d",
|
||||
amount, ConfigMarket.CurrencyName, playerdata.playername, currency.getBalance()));
|
||||
} else {
|
||||
sendError(sender, String.format("Failed to give currency to %s (would exceed max balance)",
|
||||
playerdata.playername));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Withdraw currency from player",
|
||||
usage = "<player> <amount>"
|
||||
)
|
||||
public void withdraw(ICommandSender sender, String[] args) throws CommandException {
|
||||
String playername = args[0];
|
||||
long amount;
|
||||
try {
|
||||
amount = Long.parseLong(args[1]);
|
||||
} catch (NumberFormatException ex) {
|
||||
sendError(sender, "Invalid amount: " + args[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (amount <= 0) {
|
||||
sendError(sender, "Amount must be positive");
|
||||
return;
|
||||
}
|
||||
|
||||
List<PlayerData> dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
|
||||
|
||||
if (dataList.isEmpty()) {
|
||||
sendError(sender, "Unknown player: " + playername);
|
||||
return;
|
||||
}
|
||||
|
||||
for (PlayerData playerdata : dataList) {
|
||||
PlayerTradeData currency = playerdata.tradeData;
|
||||
if (currency.withdraw(amount)) {
|
||||
playerdata.save();
|
||||
sendResult(sender, String.format("Withdrew \u00A76%,d %s\u00A77 from player \u00A7b%s\u00A77. New balance: \u00A76%,d",
|
||||
amount, ConfigMarket.CurrencyName, playerdata.playername, currency.getBalance()));
|
||||
} else {
|
||||
sendError(sender, String.format("Failed to withdraw from %s (insufficient funds)",
|
||||
playerdata.playername));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Set player's balance",
|
||||
usage = "<player> <amount>"
|
||||
)
|
||||
public void set(ICommandSender sender, String[] args) throws CommandException {
|
||||
String playername = args[0];
|
||||
long amount;
|
||||
try {
|
||||
amount = Long.parseLong(args[1]);
|
||||
} catch (NumberFormatException ex) {
|
||||
sendError(sender, "Invalid amount: " + args[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (amount < 0) {
|
||||
sendError(sender, "Amount cannot be negative");
|
||||
return;
|
||||
}
|
||||
|
||||
List<PlayerData> dataList = PlayerDataController.Instance.getPlayersData(sender, playername);
|
||||
|
||||
if (dataList.isEmpty()) {
|
||||
sendError(sender, "Unknown player: " + playername);
|
||||
return;
|
||||
}
|
||||
|
||||
for (PlayerData playerdata : dataList) {
|
||||
PlayerTradeData currency = playerdata.tradeData;
|
||||
currency.setBalance(amount);
|
||||
playerdata.save();
|
||||
sendResult(sender, String.format("Set balance of player \u00A7b%s\u00A77 to \u00A76%,d %s",
|
||||
playerdata.playername, currency.getBalance(), ConfigMarket.CurrencyName));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List addTabCompletionOptions(ICommandSender par1, String[] args) {
|
||||
if (args.length == 1) {
|
||||
return getListOfStringsMatchingLastWord(args, new String[]{"balance", "give", "withdraw", "set"});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -200,7 +200,7 @@ public class NpcCommand extends CommandKamkeelBase {
|
||||
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());
|
||||
|
||||
@@ -99,7 +99,9 @@ public class QuestCategoryCommand extends CommandKamkeelBase {
|
||||
playerdata.questData.finishedQuests.put(quest.id, completeTime);
|
||||
}
|
||||
|
||||
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
|
||||
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions
|
||||
&& (quest.profileOptions.completeControl == EnumProfileSync.Shared
|
||||
|| quest.profileOptions.cooldownControl == EnumProfileSync.Shared))
|
||||
ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
|
||||
;
|
||||
|
||||
|
||||
@@ -115,7 +115,9 @@ public class QuestCommand extends CommandKamkeelBase {
|
||||
playerdata.questData.finishedQuests.put(quest.id, completeTime);
|
||||
}
|
||||
|
||||
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions && quest.profileOptions.completeControl == EnumProfileSync.Shared)
|
||||
if (ConfigMain.ProfilesEnabled && playerdata.player != null && quest.profileOptions.enableOptions
|
||||
&& (quest.profileOptions.completeControl == EnumProfileSync.Shared
|
||||
|| quest.profileOptions.cooldownControl == EnumProfileSync.Shared))
|
||||
ProfileController.Instance.shareQuestCompletion(playerdata.player, quest.id, completeTime);
|
||||
|
||||
playerdata.save();
|
||||
|
||||
@@ -12,6 +12,7 @@ public class ScriptCommand extends CommandKamkeelBase {
|
||||
@SubCommand(desc = "Reload scripts data and folders.")
|
||||
public Boolean reload(ICommandSender sender, String args[]) {
|
||||
ScriptController.Instance.loadCategories();
|
||||
ScriptController.Instance.syncClientScripts(null);
|
||||
|
||||
if (ScriptController.Instance.loadPlayerScripts())
|
||||
sendResult(sender, "Reload player scripts successfully");
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
package kamkeel.npcs.command.auction;
|
||||
|
||||
import kamkeel.npcs.command.CommandKamkeelBase;
|
||||
import net.minecraft.command.CommandException;
|
||||
import net.minecraft.command.ICommandSender;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import noppes.npcs.controllers.data.AuctionBlacklist;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static kamkeel.npcs.util.ColorUtil.sendError;
|
||||
import static kamkeel.npcs.util.ColorUtil.sendMessage;
|
||||
import static kamkeel.npcs.util.ColorUtil.sendResult;
|
||||
|
||||
public class BlacklistSubCommand extends CommandKamkeelBase {
|
||||
|
||||
@Override
|
||||
public String getCommandName() {
|
||||
return "blacklist";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Manage auction item blacklist";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processCommand(ICommandSender sender, String[] args) throws CommandException {
|
||||
// Show help when called with no subcommand
|
||||
sendHelp(sender);
|
||||
}
|
||||
|
||||
private void sendHelp(ICommandSender sender) {
|
||||
sendMessage(sender, "\u00A76=== Auction Blacklist Commands ===");
|
||||
sendMessage(sender, "\u00A7e/cnpc auction blacklist add <item|mod|nbt> <value>");
|
||||
sendMessage(sender, "\u00A7e/cnpc auction blacklist remove <item|mod|nbt> <value>");
|
||||
sendMessage(sender, "\u00A7e/cnpc auction blacklist list [item|mod|nbt]");
|
||||
sendMessage(sender, "\u00A7e/cnpc auction blacklist reload");
|
||||
sendMessage(sender, "\u00A7e/cnpc auction blacklist check \u00A77(checks held item)");
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Add item, mod, or NBT tag to blacklist",
|
||||
usage = "<item|mod|nbt> <value>"
|
||||
)
|
||||
public void add(ICommandSender sender, String[] args) throws CommandException {
|
||||
if (args.length < 2) {
|
||||
sendError(sender, "Usage: /cnpc auction blacklist add <item|mod|nbt> <value>");
|
||||
return;
|
||||
}
|
||||
|
||||
String type = args[0].toLowerCase();
|
||||
String value = args[1];
|
||||
|
||||
switch (type) {
|
||||
case "item":
|
||||
if (AuctionBlacklist.addItem(value)) {
|
||||
sendResult(sender, "Added item to blacklist: " + value);
|
||||
} else {
|
||||
sendError(sender, "Failed to add item to blacklist");
|
||||
}
|
||||
break;
|
||||
case "mod":
|
||||
if (AuctionBlacklist.addMod(value)) {
|
||||
sendResult(sender, "Added mod to blacklist: " + value);
|
||||
} else {
|
||||
sendError(sender, "Failed to add mod to blacklist");
|
||||
}
|
||||
break;
|
||||
case "nbt":
|
||||
if (AuctionBlacklist.addNBTTag(value)) {
|
||||
sendResult(sender, "Added NBT tag to blacklist: " + value);
|
||||
} else {
|
||||
sendError(sender, "Failed to add NBT tag to blacklist");
|
||||
}
|
||||
break;
|
||||
default:
|
||||
sendError(sender, "Unknown type: " + type + ". Use: item, mod, or nbt");
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Remove item, mod, or NBT tag from blacklist",
|
||||
usage = "<item|mod|nbt> <value>"
|
||||
)
|
||||
public void remove(ICommandSender sender, String[] args) throws CommandException {
|
||||
if (args.length < 2) {
|
||||
sendError(sender, "Usage: /cnpc auction blacklist remove <item|mod|nbt> <value>");
|
||||
return;
|
||||
}
|
||||
|
||||
String type = args[0].toLowerCase();
|
||||
String value = args[1];
|
||||
|
||||
switch (type) {
|
||||
case "item":
|
||||
if (AuctionBlacklist.removeItem(value)) {
|
||||
sendResult(sender, "Removed item from blacklist: " + value);
|
||||
} else {
|
||||
sendError(sender, "Item not found in blacklist: " + value);
|
||||
}
|
||||
break;
|
||||
case "mod":
|
||||
if (AuctionBlacklist.removeMod(value)) {
|
||||
sendResult(sender, "Removed mod from blacklist: " + value);
|
||||
} else {
|
||||
sendError(sender, "Mod not found in blacklist: " + value);
|
||||
}
|
||||
break;
|
||||
case "nbt":
|
||||
if (AuctionBlacklist.removeNBTTag(value)) {
|
||||
sendResult(sender, "Removed NBT tag from blacklist: " + value);
|
||||
} else {
|
||||
sendError(sender, "NBT tag not found in blacklist: " + value);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
sendError(sender, "Unknown type: " + type + ". Use: item, mod, or nbt");
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "List blacklisted items, mods, or NBT tags",
|
||||
usage = "[item|mod|nbt]"
|
||||
)
|
||||
public void list(ICommandSender sender, String[] args) throws CommandException {
|
||||
String filter = args.length > 0 ? args[0].toLowerCase() : "all";
|
||||
|
||||
if (filter.equals("all") || filter.equals("item")) {
|
||||
List<String> items = AuctionBlacklist.getBlacklistedItems();
|
||||
sendMessage(sender, "\u00A76=== Blacklisted Items (" + items.size() + ") ===");
|
||||
if (items.isEmpty()) {
|
||||
sendMessage(sender, "\u00A77 (none)");
|
||||
} else {
|
||||
for (String item : items) {
|
||||
sendMessage(sender, "\u00A7e " + item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (filter.equals("all") || filter.equals("mod")) {
|
||||
List<String> mods = AuctionBlacklist.getBlacklistedMods();
|
||||
sendMessage(sender, "\u00A76=== Blacklisted Mods (" + mods.size() + ") ===");
|
||||
if (mods.isEmpty()) {
|
||||
sendMessage(sender, "\u00A77 (none)");
|
||||
} else {
|
||||
for (String mod : mods) {
|
||||
sendMessage(sender, "\u00A7e " + mod);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (filter.equals("all") || filter.equals("nbt")) {
|
||||
List<String> tags = AuctionBlacklist.getBlacklistedNBTTags();
|
||||
sendMessage(sender, "\u00A76=== Blacklisted NBT Tags (" + tags.size() + ") ===");
|
||||
if (tags.isEmpty()) {
|
||||
sendMessage(sender, "\u00A77 (none)");
|
||||
} else {
|
||||
for (String tag : tags) {
|
||||
sendMessage(sender, "\u00A7e " + tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sendMessage(sender, "\u00A77Note: Soulbound and Profile-Slotbound items are always blocked.");
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Reload blacklist from config"
|
||||
)
|
||||
public void reload(ICommandSender sender, String[] args) throws CommandException {
|
||||
AuctionBlacklist.reload();
|
||||
sendResult(sender, "Blacklist reloaded from config");
|
||||
}
|
||||
|
||||
@SubCommand(
|
||||
desc = "Check if held item is blacklisted",
|
||||
permission = 0
|
||||
)
|
||||
public void check(ICommandSender sender, String[] args) throws CommandException {
|
||||
if (!(sender instanceof EntityPlayer)) {
|
||||
sendError(sender, "This command can only be used by players");
|
||||
return;
|
||||
}
|
||||
|
||||
EntityPlayer player = (EntityPlayer) sender;
|
||||
ItemStack heldItem = player.getHeldItem();
|
||||
|
||||
if (heldItem == null) {
|
||||
sendError(sender, "You are not holding an item");
|
||||
return;
|
||||
}
|
||||
|
||||
String registryName = AuctionBlacklist.getRegistryName(heldItem);
|
||||
sendMessage(sender, "\u00A76=== Blacklist Check ===");
|
||||
sendMessage(sender, "\u00A77Item: \u00A7e" + heldItem.getDisplayName());
|
||||
sendMessage(sender, "\u00A77Registry: \u00A7e" + (registryName != null ? registryName : "unknown"));
|
||||
|
||||
boolean isBlacklisted = AuctionBlacklist.isBlacklisted(heldItem);
|
||||
boolean canBypass = AuctionBlacklist.canBypass(player);
|
||||
|
||||
if (isBlacklisted) {
|
||||
sendMessage(sender, "\u00A7cStatus: BLACKLISTED");
|
||||
if (canBypass) {
|
||||
sendMessage(sender, "\u00A7aYou have bypass permission");
|
||||
}
|
||||
} else {
|
||||
sendMessage(sender, "\u00A7aStatus: ALLOWED");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List addTabCompletionOptions(ICommandSender sender, String[] args) {
|
||||
if (args.length == 1) {
|
||||
return getListOfStringsMatchingLastWord(args, getAllSubCommandNames());
|
||||
}
|
||||
if (args.length == 2) {
|
||||
String subCmd = args[0].toLowerCase();
|
||||
if (subCmd.equals("add") || subCmd.equals("remove") || subCmd.equals("list")) {
|
||||
return getListOfStringsMatchingLastWord(args, new String[]{"item", "mod", "nbt"});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,209 @@
|
||||
package kamkeel.npcs.controllers;
|
||||
|
||||
import kamkeel.npcs.controllers.data.energy.IEnergyExtender;
|
||||
import kamkeel.npcs.entity.*;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.world.World;
|
||||
import noppes.npcs.api.IEnergyHandler;
|
||||
import noppes.npcs.api.IWorld;
|
||||
import noppes.npcs.api.entity.*;
|
||||
import noppes.npcs.api.entity.IEnergyExplosion;
|
||||
import noppes.npcs.scripted.NpcAPI;
|
||||
import noppes.npcs.scripted.entity.ScriptEnergyExplosion;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Central controller for script-created energy entities and handler registration.
|
||||
* Provides factory methods for creating all energy entity types and routes
|
||||
* damage through registered handlers when entities have customDamageData
|
||||
* but no sourceAbility.
|
||||
*/
|
||||
public class EnergyController implements IEnergyHandler {
|
||||
|
||||
public static EnergyController Instance = new EnergyController();
|
||||
|
||||
private final List<IEnergyExtender> extenders = new ArrayList<>();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// HANDLER REGISTRATION
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
public void registerExtender(IEnergyExtender handler) {
|
||||
extenders.add(handler);
|
||||
}
|
||||
|
||||
public List<IEnergyExtender> getExtenders() {
|
||||
return extenders;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// DAMAGE ROUTING
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Fire onEnergyDamage on all handlers. Chain of responsibility — first true wins.
|
||||
*/
|
||||
public boolean fireOnEnergyDamage(Entity energyEntity, EntityLivingBase owner,
|
||||
EntityLivingBase target, float damage,
|
||||
float knockback, float knockbackUp,
|
||||
double kbDirX, double kbDirZ,
|
||||
float damageMultiplier,
|
||||
NBTTagCompound damageData) {
|
||||
for (IEnergyExtender handler : extenders) {
|
||||
if (handler.onEnergyDamage(energyEntity, owner, target, damage,
|
||||
knockback, knockbackUp, kbDirX, kbDirZ, damageMultiplier, damageData)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fire modifyEnergyDamage on all handlers. Cumulative — each handler's output feeds the next.
|
||||
*/
|
||||
public float fireModifyEnergyDamage(Entity energyEntity, EntityLivingBase owner,
|
||||
float baseDamage, NBTTagCompound damageData) {
|
||||
float damage = baseDamage;
|
||||
for (IEnergyExtender handler : extenders) {
|
||||
damage = handler.modifyEnergyDamage(energyEntity, owner, damage, damageData);
|
||||
}
|
||||
return damage;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// INTERNAL FACTORY METHODS (MC types)
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
public EntityAbilityOrb createOrbInternal(World world, Entity owner, double x, double y, double z, float size) {
|
||||
EntityAbilityOrb entity = new EntityAbilityOrb(world);
|
||||
entity.setPosition(x, y, z);
|
||||
entity.setStartPosition(x, y, z);
|
||||
entity.setOwnerEntityId(owner.getEntityId());
|
||||
entity.setProjectileSize(size);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public EntityAbilityBeam createBeamInternal(World world, Entity owner, double x, double y, double z,
|
||||
float beamWidth, float headSize) {
|
||||
EntityAbilityBeam entity = new EntityAbilityBeam(world);
|
||||
entity.setPosition(x, y, z);
|
||||
entity.setStartPosition(x, y, z);
|
||||
entity.setOwnerEntityId(owner.getEntityId());
|
||||
entity.setBeamWidth(beamWidth);
|
||||
entity.setHeadSize(headSize);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public EntityAbilityDisc createDiscInternal(World world, Entity owner, double x, double y, double z,
|
||||
float radius, float thickness) {
|
||||
EntityAbilityDisc entity = new EntityAbilityDisc(world);
|
||||
entity.setPosition(x, y, z);
|
||||
entity.setStartPosition(x, y, z);
|
||||
entity.setOwnerEntityId(owner.getEntityId());
|
||||
entity.setDiscRadius(radius);
|
||||
entity.setDiscThickness(thickness);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public EntityAbilityLaser createLaserInternal(World world, Entity owner, double x, double y, double z,
|
||||
float laserWidth) {
|
||||
EntityAbilityLaser entity = new EntityAbilityLaser(world);
|
||||
entity.setPosition(x, y, z);
|
||||
entity.setStartPosition(x, y, z);
|
||||
entity.setOwnerEntityId(owner.getEntityId());
|
||||
entity.setLaserWidth(laserWidth);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public EntityAbilityZone createHazardInternal(World world, Entity owner, double x, double y, double z) {
|
||||
EntityAbilityZone entity = new EntityAbilityZone(world);
|
||||
entity.initAsHazard(owner, x, y, z);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public EntityAbilityZone createTrapInternal(World world, Entity owner, double x, double y, double z) {
|
||||
EntityAbilityZone entity = new EntityAbilityZone(world);
|
||||
entity.initAsTrap(owner, x, y, z);
|
||||
return entity;
|
||||
}
|
||||
|
||||
public EntityEnergySweeper createSweeperInternal(World world, Entity owner, double x, double y, double z) {
|
||||
EntityEnergySweeper entity = new EntityEnergySweeper(world);
|
||||
entity.setPosition(x, y, z);
|
||||
entity.setOwnerEntityId(owner.getEntityId());
|
||||
return entity;
|
||||
}
|
||||
|
||||
public EntityEnergyPanel createPanelInternal(World world, Entity owner, double x, double y, double z) {
|
||||
EntityEnergyPanel entity = new EntityEnergyPanel(world);
|
||||
entity.setPosition(x, y, z);
|
||||
entity.setOwnerEntityId(owner.getEntityId());
|
||||
return entity;
|
||||
}
|
||||
|
||||
public EntityEnergyExplosion createExplosionInternal(World world, Entity owner, double x, double y, double z, float radius) {
|
||||
return new EntityEnergyExplosion(world, owner, x, y, z, radius);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// IEnergyHandler (Script API methods)
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
@Override
|
||||
public IEnergyOrb createOrb(IWorld world, IEntity owner, double x, double y, double z, float size) {
|
||||
EntityAbilityOrb entity = createOrbInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, size);
|
||||
return (IEnergyOrb) NpcAPI.Instance().getIEntity(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEnergyBeam createBeam(IWorld world, IEntity owner, double x, double y, double z, float beamWidth, float headSize) {
|
||||
EntityAbilityBeam entity = createBeamInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, beamWidth, headSize);
|
||||
return (IEnergyBeam) NpcAPI.Instance().getIEntity(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEnergyDisc createDisc(IWorld world, IEntity owner, double x, double y, double z, float radius, float thickness) {
|
||||
EntityAbilityDisc entity = createDiscInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, radius, thickness);
|
||||
return (IEnergyDisc) NpcAPI.Instance().getIEntity(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEnergyLaser createLaser(IWorld world, IEntity owner, double x, double y, double z, float laserWidth) {
|
||||
EntityAbilityLaser entity = createLaserInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, laserWidth);
|
||||
return (IEnergyLaser) NpcAPI.Instance().getIEntity(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEnergyZone createHazard(IWorld world, IEntity owner, double x, double y, double z) {
|
||||
EntityAbilityZone entity = createHazardInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
|
||||
return (IEnergyZone) NpcAPI.Instance().getIEntity(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEnergyZone createTrap(IWorld world, IEntity owner, double x, double y, double z) {
|
||||
EntityAbilityZone entity = createTrapInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
|
||||
return (IEnergyZone) NpcAPI.Instance().getIEntity(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEnergySweeper createSweeper(IWorld world, IEntity owner, double x, double y, double z) {
|
||||
EntityEnergySweeper entity = createSweeperInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
|
||||
return (IEnergySweeper) NpcAPI.Instance().getIEntity(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEnergyPanel createPanel(IWorld world, IEntity owner, double x, double y, double z) {
|
||||
EntityEnergyPanel entity = createPanelInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z);
|
||||
return (IEnergyPanel) NpcAPI.Instance().getIEntity(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IEnergyExplosion createExplosion(IWorld world, IEntity owner, double x, double y, double z, float radius) {
|
||||
EntityEnergyExplosion entity = createExplosionInternal((World) world.getMCWorld(), owner.getMCEntity(), x, y, z, radius);
|
||||
return new ScriptEnergyExplosion<>(entity);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package kamkeel.npcs.controllers;
|
||||
|
||||
import kamkeel.npcs.controllers.AttributeController;
|
||||
import kamkeel.npcs.controllers.data.profile.CNPCData;
|
||||
import kamkeel.npcs.controllers.data.profile.EnumProfileOperation;
|
||||
import kamkeel.npcs.controllers.data.profile.IProfileData;
|
||||
@@ -524,6 +523,7 @@ public class ProfileController implements IProfileHandler {
|
||||
// overwrite the destination slot with stale data.
|
||||
saveSlotData(profile.player, profile, prevSlot);
|
||||
loadSlotData(profile.player, profile, newSlotId);
|
||||
syncSharedQuestsToPlayer(profile.player);
|
||||
|
||||
EventHooks.onProfileChange(handler, scriptPlayer, profile, newSlotId, prevSlot, true);
|
||||
} else {
|
||||
@@ -861,6 +861,9 @@ public class ProfileController implements IProfileHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// Update the profile cache
|
||||
profile.sharedQuestTimestamps = universalFinished;
|
||||
|
||||
// Push the universal shared completion times into every slot.
|
||||
for (ISlot slot : profile.getSlots().values()) {
|
||||
IPlayerData data = getSlotPlayerData(player, slot.getId());
|
||||
@@ -873,21 +876,29 @@ public class ProfileController implements IProfileHandler {
|
||||
}
|
||||
}
|
||||
|
||||
public void syncSharedQuestsToPlayer(EntityPlayer player) {
|
||||
Profile profile = getProfile(player);
|
||||
if (profile == null || profile.sharedQuestTimestamps.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
PlayerQuestData questData = PlayerData.get(player).questData;
|
||||
for (Map.Entry<Integer, Long> entry : profile.sharedQuestTimestamps.entrySet()) {
|
||||
Long existing = questData.finishedQuests.get(entry.getKey());
|
||||
if (existing == null || entry.getValue() > existing) {
|
||||
questData.finishedQuests.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void shareQuestCompletion(EntityPlayer player, int questId, long completeTime) {
|
||||
Profile profile = getProfile(player);
|
||||
if (profile == null) {
|
||||
return;
|
||||
}
|
||||
for (ISlot slot : profile.getSlots().values()) {
|
||||
IPlayerData playerData = getSlotPlayerData(player, slot.getId());
|
||||
if (playerData != null) {
|
||||
PlayerQuestData questData = (PlayerQuestData) playerData.getQuestData();
|
||||
Long existing = questData.finishedQuests.get(questId);
|
||||
if (existing == null || completeTime > existing) {
|
||||
questData.finishedQuests.put(questId, completeTime);
|
||||
}
|
||||
playerData.save();
|
||||
}
|
||||
|
||||
Long existing = profile.sharedQuestTimestamps.get(questId);
|
||||
if (existing == null || completeTime > existing) {
|
||||
profile.sharedQuestTimestamps.put(questId, completeTime);
|
||||
}
|
||||
save(player, profile);
|
||||
}
|
||||
|
||||
@@ -2,14 +2,19 @@ package kamkeel.npcs.controllers;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.addon.DBCAddon;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import kamkeel.npcs.addon.DBCAddon;
|
||||
import kamkeel.npcs.controllers.data.ability.Ability;
|
||||
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
|
||||
import kamkeel.npcs.network.LargeAbstractPacket;
|
||||
import kamkeel.npcs.network.PacketHandler;
|
||||
import kamkeel.npcs.network.enums.EnumSyncAction;
|
||||
import kamkeel.npcs.network.enums.EnumSyncType;
|
||||
import kamkeel.npcs.network.packets.data.LoginPacket;
|
||||
import kamkeel.npcs.network.packets.data.ability.AbilityCooldownSyncPacket;
|
||||
import kamkeel.npcs.network.packets.data.ability.AbilityHotbarSyncPacket;
|
||||
import kamkeel.npcs.network.packets.data.ability.PlayerAbilitySyncPacket;
|
||||
import kamkeel.npcs.network.packets.data.large.SyncEffectPacket;
|
||||
import kamkeel.npcs.network.packets.data.large.SyncPacket;
|
||||
import kamkeel.npcs.network.packets.request.party.PartyInfoPacket;
|
||||
@@ -44,6 +49,7 @@ import java.io.IOException;
|
||||
import java.util.EnumMap;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -72,7 +78,9 @@ public class SyncController {
|
||||
EnumSyncType.ANVIL_RECIPES,
|
||||
EnumSyncType.CUSTOM_EFFECTS,
|
||||
EnumSyncType.MAGIC,
|
||||
EnumSyncType.MAGIC_CYCLE
|
||||
EnumSyncType.MAGIC_CYCLE,
|
||||
EnumSyncType.CUSTOM_ABILITY,
|
||||
EnumSyncType.CHAINED_ABILITY
|
||||
};
|
||||
|
||||
public static void load() {
|
||||
@@ -88,6 +96,8 @@ public class SyncController {
|
||||
registerCache(EnumSyncType.CUSTOM_EFFECTS, SyncController::customEffectsNBT);
|
||||
registerCache(EnumSyncType.MAGIC, SyncController::magicsNBT);
|
||||
registerCache(EnumSyncType.MAGIC_CYCLE, SyncController::magicCyclesNBT);
|
||||
registerCache(EnumSyncType.CUSTOM_ABILITY, SyncController::customAbilitiesNBT);
|
||||
registerCache(EnumSyncType.CHAINED_ABILITY, SyncController::chainedAbilitiesNBT);
|
||||
}
|
||||
|
||||
public static void syncPlayer(EntityPlayerMP player) {
|
||||
@@ -174,6 +184,14 @@ public class SyncController {
|
||||
DBCAddon.instance.syncPlayer(player);
|
||||
syncPlayerData(player, false);
|
||||
PartyInfoPacket.sendPartyData(player);
|
||||
|
||||
// Sync skin overlays after full handshake to ensure the client is ready.
|
||||
// Overlays are not part of getSyncNBTFull(), and packets sent during
|
||||
// PlayerLoggedInEvent can arrive before the client entity exists.
|
||||
PlayerData data = PlayerData.get(player);
|
||||
if (data != null) {
|
||||
data.skinOverlays.updateClient();
|
||||
}
|
||||
}
|
||||
|
||||
private static EnumMap<EnumSyncType, Integer> getServerRevisionSnapshot() {
|
||||
@@ -323,6 +341,48 @@ public class SyncController {
|
||||
return compound;
|
||||
}
|
||||
|
||||
public static NBTTagCompound customAbilitiesNBT() {
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (Map.Entry<String, Ability> entry : AbilityController.Instance.getCustomAbilities().entrySet()) {
|
||||
NBTTagCompound abilityNBT = entry.getValue().writeNBT(false);
|
||||
abilityNBT.setString("CustomAbilityId", entry.getKey());
|
||||
list.appendTag(abilityNBT);
|
||||
}
|
||||
compound.setTag("Data", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
public static void syncAllCustomAbilities() {
|
||||
CachedSyncPayload payload = rebuildNow(EnumSyncType.CUSTOM_ABILITY);
|
||||
if (payload == null) {
|
||||
return;
|
||||
}
|
||||
PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CUSTOM_ABILITY, payload));
|
||||
updateAllPlayerRevisions(EnumSyncType.CUSTOM_ABILITY, payload.getRevision());
|
||||
}
|
||||
|
||||
public static NBTTagCompound chainedAbilitiesNBT() {
|
||||
NBTTagList list = new NBTTagList();
|
||||
NBTTagCompound compound = new NBTTagCompound();
|
||||
for (Map.Entry<String, ChainedAbility> entry : AbilityController.Instance.getChainedAbilities().entrySet()) {
|
||||
NBTTagCompound chainNBT = entry.getValue().writeNBT(false);
|
||||
chainNBT.setString("ChainedAbilityId", entry.getKey());
|
||||
list.appendTag(chainNBT);
|
||||
}
|
||||
compound.setTag("Data", list);
|
||||
return compound;
|
||||
}
|
||||
|
||||
public static void syncAllChainedAbilities() {
|
||||
CachedSyncPayload payload = rebuildNow(EnumSyncType.CHAINED_ABILITY);
|
||||
if (payload == null) {
|
||||
return;
|
||||
}
|
||||
PacketHandler.Instance.sendToAll(new SyncPacket(EnumSyncType.CHAINED_ABILITY, payload));
|
||||
updateAllPlayerRevisions(EnumSyncType.CHAINED_ABILITY, payload.getRevision());
|
||||
}
|
||||
|
||||
public static void syncPlayerData(EntityPlayerMP player, boolean update) {
|
||||
PlayerData data = PlayerData.get(player);
|
||||
if (data != null) {
|
||||
@@ -595,6 +655,35 @@ public class SyncController {
|
||||
ce.customEffectsSync.clear();
|
||||
break;
|
||||
}
|
||||
case CUSTOM_ABILITY: {
|
||||
NBTTagList list = fullCompound.getTagList("Data", 10);
|
||||
LinkedHashMap<String, Ability> sync = new LinkedHashMap<>();
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
NBTTagCompound nbt = list.getCompoundTagAt(i);
|
||||
String name = nbt.getString("CustomAbilityId");
|
||||
Ability ability = AbilityController.Instance.fromNBT(nbt);
|
||||
if (ability != null) {
|
||||
ability.setName(name);
|
||||
sync.put(name, ability);
|
||||
}
|
||||
}
|
||||
AbilityController.Instance.setCustomAbilities(sync);
|
||||
break;
|
||||
}
|
||||
case CHAINED_ABILITY: {
|
||||
NBTTagList list = fullCompound.getTagList("Data", 10);
|
||||
LinkedHashMap<String, ChainedAbility> sync = new LinkedHashMap<>();
|
||||
for (int i = 0; i < list.tagCount(); i++) {
|
||||
NBTTagCompound nbt = list.getCompoundTagAt(i);
|
||||
String id = nbt.getString("ChainedAbilityId");
|
||||
ChainedAbility chain = new ChainedAbility();
|
||||
chain.readNBT(nbt);
|
||||
chain.setName(id);
|
||||
sync.put(id, chain);
|
||||
}
|
||||
AbilityController.Instance.setChainedAbilities(sync);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
ClientCacheHandler.updateClientRevision(enumSyncType, revision);
|
||||
@@ -787,6 +876,32 @@ public class SyncController {
|
||||
PacketHandler.Instance.sendToPlayer(new SyncEffectPacket(compound), playerMP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Full sync of all player ability state to the client: unlocked abilities,
|
||||
* selection, toggles, hotbar layout, and cooldowns.
|
||||
* Used for entity reconstruction and other full-refresh scenarios.
|
||||
*/
|
||||
public static void syncAbilities(EntityPlayerMP playerMP) {
|
||||
PlayerData playerData = PlayerData.get(playerMP);
|
||||
if (playerData == null) return;
|
||||
|
||||
PlayerAbilitySyncPacket.sendToPlayer(playerMP);
|
||||
AbilityHotbarSyncPacket.sendToPlayer(playerMP);
|
||||
AbilityCooldownSyncPacket.sendToPlayer(playerMP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight sync of cooldown state only (global + per-ability).
|
||||
* Called periodically (every 10 ticks) to keep the client's cooldown
|
||||
* display accurate. Cooldowns are transient and not part of NBT sync.
|
||||
*/
|
||||
public static void syncAbilityCooldowns(EntityPlayerMP playerMP) {
|
||||
PlayerData playerData = PlayerData.get(playerMP);
|
||||
if (playerData == null) return;
|
||||
|
||||
AbilityCooldownSyncPacket.sendToPlayer(playerMP);
|
||||
}
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
public static void clientSyncEffects(NBTTagCompound compound) {
|
||||
PlayerData playerData = PlayerData.get(Minecraft.getMinecraft().thePlayer);
|
||||
@@ -843,6 +958,10 @@ public class SyncController {
|
||||
return EnumSet.of(EnumSyncType.ANVIL_RECIPES);
|
||||
case CUSTOM_EFFECTS:
|
||||
return EnumSet.of(EnumSyncType.CUSTOM_EFFECTS);
|
||||
case CUSTOM_ABILITY:
|
||||
return EnumSet.of(EnumSyncType.CUSTOM_ABILITY);
|
||||
case CHAINED_ABILITY:
|
||||
return EnumSet.of(EnumSyncType.CHAINED_ABILITY);
|
||||
default:
|
||||
return EnumSet.noneOf(EnumSyncType.class);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
package kamkeel.npcs.controllers;
|
||||
|
||||
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
|
||||
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
|
||||
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
|
||||
import kamkeel.npcs.network.packets.data.telegraph.TelegraphRemovePacket;
|
||||
import kamkeel.npcs.network.packets.data.telegraph.TelegraphSpawnPacket;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.world.World;
|
||||
import noppes.npcs.CustomNpcs;
|
||||
import noppes.npcs.LogWriter;
|
||||
import noppes.npcs.api.ITelegraph;
|
||||
import noppes.npcs.api.ITelegraphInstance;
|
||||
import noppes.npcs.api.IWorld;
|
||||
import noppes.npcs.api.entity.IEntity;
|
||||
import noppes.npcs.api.handler.ITelegraphHandler;
|
||||
import noppes.npcs.scripted.ScriptTelegraph;
|
||||
import noppes.npcs.scripted.ScriptTelegraphInstance;
|
||||
import noppes.npcs.util.NBTJsonUtil;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Server-side controller for managing telegraphs.
|
||||
* Provides factory methods for creating telegraphs and spawn methods for sending to clients.
|
||||
* Also manages saved telegraph presets.
|
||||
*/
|
||||
public class TelegraphController implements ITelegraphHandler {
|
||||
|
||||
public static TelegraphController Instance;
|
||||
|
||||
// Saved telegraph presets (name -> Telegraph)
|
||||
private HashMap<String, Telegraph> savedTelegraphs = new HashMap<>();
|
||||
|
||||
// Active server-side telegraph instances (for removal tracking)
|
||||
private ConcurrentHashMap<String, TelegraphInstance> activeInstances = new ConcurrentHashMap<>();
|
||||
|
||||
public TelegraphController() {
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
Instance = new TelegraphController();
|
||||
Instance.load();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// INTERNAL SPAWN METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Spawn a telegraph at a fixed position.
|
||||
*
|
||||
* @param telegraph The telegraph configuration
|
||||
* @param world The world
|
||||
* @param x X position
|
||||
* @param y Y position
|
||||
* @param z Z position
|
||||
* @param yaw Rotation yaw (for directional telegraphs like LINE/CONE)
|
||||
* @return The spawned telegraph instance
|
||||
*/
|
||||
public TelegraphInstance spawn(Telegraph telegraph, World world, double x, double y, double z, float yaw) {
|
||||
TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw);
|
||||
instance.setWorld(world);
|
||||
activeInstances.put(instance.getInstanceId(), instance);
|
||||
TelegraphSpawnPacket.sendToDimension(instance, world.provider.dimensionId);
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a telegraph at a position with default yaw.
|
||||
*/
|
||||
public TelegraphInstance spawn(Telegraph telegraph, World world, double x, double y, double z) {
|
||||
return spawn(telegraph, world, x, y, z, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a telegraph that follows an entity.
|
||||
*
|
||||
* @param telegraph The telegraph configuration
|
||||
* @param entity The entity to follow
|
||||
* @return The spawned telegraph instance
|
||||
*/
|
||||
public TelegraphInstance spawn(Telegraph telegraph, Entity entity) {
|
||||
return spawn(telegraph, entity, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a telegraph that follows an entity with yaw.
|
||||
*/
|
||||
public TelegraphInstance spawn(Telegraph telegraph, Entity entity, float yaw) {
|
||||
TelegraphInstance instance = new TelegraphInstance(telegraph, entity.posX, entity.posY, entity.posZ, yaw);
|
||||
instance.setWorld(entity.worldObj);
|
||||
instance.setEntityIdToFollow(entity.getEntityId());
|
||||
activeInstances.put(instance.getInstanceId(), instance);
|
||||
TelegraphSpawnPacket.sendToTracking(instance, entity);
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a telegraph to a specific player only.
|
||||
*/
|
||||
public TelegraphInstance spawnToPlayer(Telegraph telegraph, EntityPlayerMP player, double x, double y, double z, float yaw) {
|
||||
TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw);
|
||||
instance.setWorld(player.worldObj);
|
||||
activeInstances.put(instance.getInstanceId(), instance);
|
||||
TelegraphSpawnPacket.send(instance, player);
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a telegraph to all players on the server.
|
||||
*/
|
||||
public TelegraphInstance spawnToAll(Telegraph telegraph, World world, double x, double y, double z, float yaw) {
|
||||
TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw);
|
||||
instance.setWorld(world);
|
||||
activeInstances.put(instance.getInstanceId(), instance);
|
||||
TelegraphSpawnPacket.sendToAll(instance);
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a telegraph to all players tracking an entity.
|
||||
*/
|
||||
public TelegraphInstance spawnToTracking(Telegraph telegraph, Entity entity, double x, double y, double z, float yaw) {
|
||||
TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw);
|
||||
instance.setWorld(entity.worldObj);
|
||||
activeInstances.put(instance.getInstanceId(), instance);
|
||||
TelegraphSpawnPacket.sendToTracking(instance, entity);
|
||||
return instance;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// REMOVAL METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Remove a telegraph by instance ID.
|
||||
*/
|
||||
public void remove(String instanceId) {
|
||||
TelegraphInstance instance = activeInstances.remove(instanceId);
|
||||
if (instance != null && instance.getWorld() != null) {
|
||||
TelegraphRemovePacket.sendToDimension(instanceId, instance.getDimensionId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a telegraph instance.
|
||||
*/
|
||||
public void remove(TelegraphInstance instance) {
|
||||
if (instance != null) {
|
||||
remove(instance.getInstanceId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a telegraph for a specific player only.
|
||||
*/
|
||||
public void removeFromPlayer(String instanceId, EntityPlayerMP player) {
|
||||
activeInstances.remove(instanceId);
|
||||
TelegraphRemovePacket.send(instanceId, player);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an active telegraph instance by ID.
|
||||
*/
|
||||
public TelegraphInstance getActiveInstance(String instanceId) {
|
||||
return activeInstances.get(instanceId);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// PRESET MANAGEMENT
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Save a telegraph preset (internal use).
|
||||
*
|
||||
* @param name The name for the preset
|
||||
* @param telegraph The telegraph configuration to save
|
||||
*/
|
||||
public void saveInternal(String name, Telegraph telegraph) {
|
||||
if (name == null || name.isEmpty() || telegraph == null) return;
|
||||
|
||||
telegraph.setId(name);
|
||||
savedTelegraphs.put(name, telegraph);
|
||||
saveTelegraphFile(name, telegraph);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a saved telegraph preset by name (internal use).
|
||||
*
|
||||
* @param name The preset name
|
||||
* @return The telegraph configuration, or null if not found
|
||||
*/
|
||||
public Telegraph getInternal(String name) {
|
||||
return savedTelegraphs.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a saved telegraph preset.
|
||||
*
|
||||
* @param name The preset name
|
||||
*/
|
||||
public void delete(String name) {
|
||||
Telegraph removed = savedTelegraphs.remove(name);
|
||||
if (removed != null) {
|
||||
File file = new File(getDir(), name + ".json");
|
||||
if (file.exists()) {
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a preset exists.
|
||||
*/
|
||||
public boolean has(String name) {
|
||||
return savedTelegraphs.containsKey(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all saved preset names.
|
||||
*/
|
||||
public String[] getSavedNames() {
|
||||
return savedTelegraphs.keySet().toArray(new String[0]);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// PERSISTENCE
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
private File getDir() {
|
||||
return new File(CustomNpcs.getWorldSaveDirectory(), "telegraphs");
|
||||
}
|
||||
|
||||
public void load() {
|
||||
savedTelegraphs.clear();
|
||||
LogWriter.info("Loading telegraph presets...");
|
||||
|
||||
File dir = getDir();
|
||||
if (!dir.exists()) {
|
||||
dir.mkdirs();
|
||||
return;
|
||||
}
|
||||
|
||||
File[] files = dir.listFiles();
|
||||
if (files == null) return;
|
||||
|
||||
for (File file : files) {
|
||||
if (!file.isFile() || !file.getName().endsWith(".json")) continue;
|
||||
try {
|
||||
Telegraph telegraph = new Telegraph();
|
||||
telegraph.readNBT(NBTJsonUtil.LoadFile(file));
|
||||
String name = file.getName().substring(0, file.getName().length() - 5);
|
||||
telegraph.setId(name);
|
||||
savedTelegraphs.put(name, telegraph);
|
||||
} catch (Exception e) {
|
||||
LogWriter.error("Error loading telegraph preset: " + file.getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
LogWriter.info("Loaded " + savedTelegraphs.size() + " telegraph presets.");
|
||||
}
|
||||
|
||||
private void saveTelegraphFile(String name, Telegraph telegraph) {
|
||||
try {
|
||||
File dir = getDir();
|
||||
if (!dir.exists()) {
|
||||
dir.mkdirs();
|
||||
}
|
||||
|
||||
File file = new File(dir, name + ".json_new");
|
||||
File file2 = new File(dir, name + ".json");
|
||||
|
||||
NBTJsonUtil.SaveFile(file, telegraph.writeNBT());
|
||||
if (file2.exists()) {
|
||||
file2.delete();
|
||||
}
|
||||
file.renameTo(file2);
|
||||
} catch (Exception e) {
|
||||
LogWriter.error("Error saving telegraph preset: " + name, e);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// ITelegraphHandler INTERFACE IMPLEMENTATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@Override
|
||||
public ITelegraph createCircle(float radius) {
|
||||
return new ScriptTelegraph(Telegraph.circle(radius));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraph createRing(float outerRadius, float innerRadius) {
|
||||
return new ScriptTelegraph(Telegraph.ring(outerRadius, innerRadius));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraph createLine(float length, float width) {
|
||||
return new ScriptTelegraph(Telegraph.line(length, width));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraph createCone(float length, float angle) {
|
||||
return new ScriptTelegraph(Telegraph.cone(length, angle));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraph createSquare(float radius) {
|
||||
return new ScriptTelegraph(Telegraph.square(radius));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraph createPoint() {
|
||||
return new ScriptTelegraph(Telegraph.point());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraph create(String type) {
|
||||
if (type == null) return null;
|
||||
try {
|
||||
TelegraphType telegraphType = TelegraphType.valueOf(type.toUpperCase());
|
||||
Telegraph telegraph;
|
||||
switch (telegraphType) {
|
||||
case CIRCLE:
|
||||
telegraph = Telegraph.circle(3.0f);
|
||||
break;
|
||||
case RING:
|
||||
telegraph = Telegraph.ring(5.0f, 2.0f);
|
||||
break;
|
||||
case LINE:
|
||||
telegraph = Telegraph.line(5.0f, 2.0f);
|
||||
break;
|
||||
case CONE:
|
||||
telegraph = Telegraph.cone(5.0f, 45.0f);
|
||||
break;
|
||||
case SQUARE:
|
||||
telegraph = Telegraph.square(3.0f);
|
||||
break;
|
||||
case POINT:
|
||||
telegraph = Telegraph.point();
|
||||
break;
|
||||
default:
|
||||
telegraph = Telegraph.circle(3.0f);
|
||||
}
|
||||
return new ScriptTelegraph(telegraph);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraphInstance spawn(ITelegraph telegraph, IWorld world, double x, double y, double z) {
|
||||
return spawn(telegraph, world, x, y, z, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraphInstance spawn(ITelegraph telegraph, IWorld world, double x, double y, double z, float yaw) {
|
||||
if (telegraph == null || world == null) return null;
|
||||
Telegraph internal = ((ScriptTelegraph) telegraph).getMCTelegraph();
|
||||
TelegraphInstance instance = spawn(internal, (World) world.getMCWorld(), x, y, z, yaw);
|
||||
return new ScriptTelegraphInstance(instance);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraphInstance spawn(ITelegraph telegraph, IEntity entity) {
|
||||
return spawn(telegraph, entity, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraphInstance spawn(ITelegraph telegraph, IEntity entity, float yaw) {
|
||||
if (telegraph == null || entity == null) return null;
|
||||
Telegraph internal = ((ScriptTelegraph) telegraph).getMCTelegraph();
|
||||
TelegraphInstance instance = spawn(internal, (Entity) entity.getMCEntity(), yaw);
|
||||
return new ScriptTelegraphInstance(instance);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ITelegraph get(String name) {
|
||||
Telegraph telegraph = savedTelegraphs.get(name);
|
||||
return telegraph != null ? new ScriptTelegraph(new Telegraph(telegraph)) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(String name, ITelegraph telegraph) {
|
||||
if (name == null || name.isEmpty() || telegraph == null) return;
|
||||
Telegraph internal = ((ScriptTelegraph) telegraph).getMCTelegraph();
|
||||
saveInternal(name, internal);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(ITelegraphInstance instance) {
|
||||
if (instance != null) {
|
||||
remove(instance.getInstanceId());
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,323 @@
|
||||
package kamkeel.npcs.controllers.data.ability;
|
||||
|
||||
import kamkeel.npcs.controllers.AbilityController;
|
||||
import kamkeel.npcs.controllers.data.ability.data.ChainedAbility;
|
||||
import kamkeel.npcs.controllers.data.ability.data.IAbilityAction;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Unified slot for storing any combat action: inline ability, ability reference, or chain reference.
|
||||
* Support for all {@link IAbilityAction} types.
|
||||
* <p>
|
||||
* References are lazy-resolved via their respective controllers and cached until
|
||||
* the controller revision changes.
|
||||
*/
|
||||
public class AbilityAction {
|
||||
|
||||
public enum SlotType {
|
||||
INLINE_ABILITY,
|
||||
ABILITY_REFERENCE,
|
||||
CHAIN_REFERENCE,
|
||||
INLINE_CHAIN
|
||||
}
|
||||
|
||||
private SlotType slotType;
|
||||
private Ability inlineAbility;
|
||||
private ChainedAbility inlineChain;
|
||||
private String referenceId;
|
||||
|
||||
/**
|
||||
* Per-slot enabled override for reference slots (null = use master's default).
|
||||
*/
|
||||
private Boolean enabledOverride;
|
||||
|
||||
// Cache
|
||||
private transient IAbilityAction cachedAction;
|
||||
private transient int cachedRevision = -1;
|
||||
|
||||
private AbilityAction() {
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// FACTORY METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
public static AbilityAction inline(Ability ability) {
|
||||
AbilityAction slot = new AbilityAction();
|
||||
slot.slotType = SlotType.INLINE_ABILITY;
|
||||
slot.inlineAbility = ability;
|
||||
return slot;
|
||||
}
|
||||
|
||||
public static AbilityAction abilityReference(String referenceId) {
|
||||
AbilityAction slot = new AbilityAction();
|
||||
slot.slotType = SlotType.ABILITY_REFERENCE;
|
||||
slot.referenceId = referenceId;
|
||||
return slot;
|
||||
}
|
||||
|
||||
public static AbilityAction chainReference(String referenceId) {
|
||||
AbilityAction slot = new AbilityAction();
|
||||
slot.slotType = SlotType.CHAIN_REFERENCE;
|
||||
slot.referenceId = referenceId;
|
||||
return slot;
|
||||
}
|
||||
|
||||
public static AbilityAction inlineChain(ChainedAbility chain) {
|
||||
AbilityAction slot = new AbilityAction();
|
||||
slot.slotType = SlotType.INLINE_CHAIN;
|
||||
slot.inlineChain = chain;
|
||||
return slot;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// QUERIES
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
public SlotType getSlotType() {
|
||||
return slotType;
|
||||
}
|
||||
|
||||
public boolean isReference() {
|
||||
return slotType == SlotType.ABILITY_REFERENCE || slotType == SlotType.CHAIN_REFERENCE;
|
||||
}
|
||||
|
||||
public boolean isChainReference() {
|
||||
return slotType == SlotType.CHAIN_REFERENCE;
|
||||
}
|
||||
|
||||
public boolean isInlineChain() {
|
||||
return slotType == SlotType.INLINE_CHAIN;
|
||||
}
|
||||
|
||||
public boolean isChain() {
|
||||
return slotType == SlotType.CHAIN_REFERENCE || slotType == SlotType.INLINE_CHAIN;
|
||||
}
|
||||
|
||||
public boolean isAbilityReference() {
|
||||
return slotType == SlotType.ABILITY_REFERENCE;
|
||||
}
|
||||
|
||||
public String getReferenceId() {
|
||||
return referenceId;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// RESOLUTION
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Resolve the action. Inline returns directly; references resolve
|
||||
* from the appropriate controller with version-based caching.
|
||||
*/
|
||||
public IAbilityAction getAction() {
|
||||
switch (slotType) {
|
||||
case INLINE_ABILITY:
|
||||
return inlineAbility;
|
||||
|
||||
case INLINE_CHAIN:
|
||||
return inlineChain;
|
||||
|
||||
case ABILITY_REFERENCE: {
|
||||
AbilityController ctrl = AbilityController.Instance;
|
||||
if (ctrl == null) return null;
|
||||
int rev = ctrl.getCustomAbilityRevision();
|
||||
if (cachedAction != null && cachedRevision == rev) {
|
||||
return cachedAction;
|
||||
}
|
||||
Ability resolved = ctrl.resolveAbility(referenceId);
|
||||
cachedAction = resolved;
|
||||
cachedRevision = rev;
|
||||
return cachedAction;
|
||||
}
|
||||
|
||||
case CHAIN_REFERENCE: {
|
||||
AbilityController ctrl = AbilityController.Instance;
|
||||
if (ctrl == null) return null;
|
||||
int rev = ctrl.getChainedAbilityRevision();
|
||||
if (cachedAction != null && cachedRevision == rev) {
|
||||
return cachedAction;
|
||||
}
|
||||
ChainedAbility resolved = ctrl.resolveChainedAbility(referenceId);
|
||||
cachedAction = resolved;
|
||||
cachedRevision = rev;
|
||||
return cachedAction;
|
||||
}
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get as Ability (returns null if this is a chain slot or resolution fails).
|
||||
*/
|
||||
public Ability getAbility() {
|
||||
IAbilityAction action = getAction();
|
||||
return (action instanceof Ability) ? (Ability) action : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get as ChainedAbility (returns null if this is an ability slot or resolution fails).
|
||||
*/
|
||||
public ChainedAbility getChainedAbility() {
|
||||
IAbilityAction action = getAction();
|
||||
return (action instanceof ChainedAbility) ? (ChainedAbility) action : null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// ENABLED OVERRIDE
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
if (slotType == SlotType.INLINE_ABILITY) {
|
||||
if (inlineAbility != null) {
|
||||
inlineAbility.setEnabled(enabled);
|
||||
}
|
||||
} else if (slotType == SlotType.INLINE_CHAIN) {
|
||||
if (inlineChain != null) {
|
||||
inlineChain.setEnabled(enabled);
|
||||
}
|
||||
} else {
|
||||
this.enabledOverride = enabled;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this slot is enabled. For inline slots, delegates to the action directly.
|
||||
* For reference slots, uses enabledOverride if set, otherwise the resolved action's own state.
|
||||
* This avoids mutating the shared controller instance.
|
||||
*/
|
||||
public boolean isSlotEnabled() {
|
||||
if (enabledOverride != null) {
|
||||
return enabledOverride;
|
||||
}
|
||||
IAbilityAction action = getAction();
|
||||
return action != null && action.isEnabled();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// INLINE CONVERSION (ability references only)
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
public Ability getInlineAbility() {
|
||||
return inlineAbility;
|
||||
}
|
||||
|
||||
public ChainedAbility getInlineChain() {
|
||||
return inlineChain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert this reference slot to an inline slot by copying the resolved data.
|
||||
* Works for ability references (→ INLINE_ABILITY) and chain references (→ INLINE_CHAIN).
|
||||
* Chain entries are kept as-is (not auto-converted to inline).
|
||||
*/
|
||||
public boolean convertToInline() {
|
||||
if (slotType == SlotType.ABILITY_REFERENCE) {
|
||||
Ability resolved = getAbility();
|
||||
if (resolved == null) return false;
|
||||
|
||||
NBTTagCompound nbt = resolved.writeNBT(true);
|
||||
nbt.setString("id", UUID.randomUUID().toString());
|
||||
inlineAbility = AbilityController.Instance.fromNBT(nbt);
|
||||
slotType = SlotType.INLINE_ABILITY;
|
||||
referenceId = null;
|
||||
cachedAction = null;
|
||||
cachedRevision = -1;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (slotType == SlotType.CHAIN_REFERENCE) {
|
||||
ChainedAbility resolved = getChainedAbility();
|
||||
if (resolved == null) return false;
|
||||
|
||||
inlineChain = new ChainedAbility();
|
||||
NBTTagCompound chainNbt = resolved.writeNBT(true);
|
||||
chainNbt.setString("Id", UUID.randomUUID().toString());
|
||||
inlineChain.readNBT(chainNbt);
|
||||
slotType = SlotType.INLINE_CHAIN;
|
||||
referenceId = null;
|
||||
cachedAction = null;
|
||||
cachedRevision = -1;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// NBT
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
|
||||
public NBTTagCompound writeNBT(boolean saveScripts) {
|
||||
switch (slotType) {
|
||||
case INLINE_CHAIN: {
|
||||
NBTTagCompound nbt = new NBTTagCompound();
|
||||
if (inlineChain != null) {
|
||||
nbt.setTag("InlineChain", inlineChain.writeNBT(saveScripts));
|
||||
}
|
||||
return nbt;
|
||||
}
|
||||
|
||||
case CHAIN_REFERENCE: {
|
||||
NBTTagCompound nbt = new NBTTagCompound();
|
||||
nbt.setString("ChainReference", referenceId);
|
||||
if (enabledOverride != null) {
|
||||
nbt.setBoolean("RefEnabled", enabledOverride);
|
||||
}
|
||||
return nbt;
|
||||
}
|
||||
|
||||
case ABILITY_REFERENCE: {
|
||||
NBTTagCompound nbt = new NBTTagCompound();
|
||||
nbt.setString("Reference", referenceId);
|
||||
if (enabledOverride != null) {
|
||||
nbt.setBoolean("RefEnabled", enabledOverride);
|
||||
}
|
||||
return nbt;
|
||||
}
|
||||
|
||||
case INLINE_ABILITY:
|
||||
default:
|
||||
return inlineAbility != null ? inlineAbility.writeNBT(saveScripts) : new NBTTagCompound();
|
||||
}
|
||||
}
|
||||
|
||||
public static AbilityAction fromNBT(NBTTagCompound nbt) {
|
||||
if (nbt == null) return null;
|
||||
|
||||
// Inline chain (new format)
|
||||
if (nbt.hasKey("InlineChain")) {
|
||||
ChainedAbility chain = new ChainedAbility();
|
||||
chain.readNBT(nbt.getCompoundTag("InlineChain"));
|
||||
return inlineChain(chain);
|
||||
}
|
||||
|
||||
// Chain reference
|
||||
if (nbt.hasKey("ChainReference")) {
|
||||
AbilityAction slot = chainReference(nbt.getString("ChainReference"));
|
||||
if (nbt.hasKey("RefEnabled")) {
|
||||
slot.enabledOverride = nbt.getBoolean("RefEnabled");
|
||||
}
|
||||
return slot;
|
||||
}
|
||||
|
||||
// Ability reference
|
||||
if (nbt.hasKey("Reference")) {
|
||||
AbilityAction slot = abilityReference(nbt.getString("Reference"));
|
||||
if (nbt.hasKey("RefEnabled")) {
|
||||
slot.enabledOverride = nbt.getBoolean("RefEnabled");
|
||||
}
|
||||
return slot;
|
||||
}
|
||||
|
||||
// Inline ability
|
||||
if (AbilityController.Instance == null) return null;
|
||||
Ability ability = AbilityController.Instance.fromNBT(nbt);
|
||||
if (ability == null) return null;
|
||||
return inline(ability);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package kamkeel.npcs.controllers.data.ability;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Represents a variant/template for an ability type.
|
||||
* When a user creates an ability that has registered variants,
|
||||
* they are presented with a selection dialog before the ability is created.
|
||||
* <p>
|
||||
* Each variant has a display name (lang key) and a configurator that
|
||||
* applies preset values to the newly created ability.
|
||||
*/
|
||||
public class AbilityVariant {
|
||||
|
||||
private final String displayKey;
|
||||
private final String group;
|
||||
private final Consumer<Ability> configurator;
|
||||
|
||||
/**
|
||||
* @param displayKey Lang key for the variant display name (e.g., "ability.variant.dual")
|
||||
* @param configurator Lambda that configures the ability with preset values
|
||||
*/
|
||||
public AbilityVariant(String displayKey, Consumer<Ability> configurator) {
|
||||
this(displayKey, null, configurator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param displayKey Lang key for the variant display name
|
||||
* @param group Optional group header shown in the variant selection GUI (e.g., "DBC Addon")
|
||||
* @param configurator Lambda that configures the ability with preset values
|
||||
*/
|
||||
public AbilityVariant(String displayKey, String group, Consumer<Ability> configurator) {
|
||||
this.displayKey = displayKey;
|
||||
this.group = group;
|
||||
this.configurator = configurator;
|
||||
}
|
||||
|
||||
public String getDisplayKey() {
|
||||
return displayKey;
|
||||
}
|
||||
|
||||
public String getGroup() {
|
||||
return group;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply this variant's preset configuration to the given ability.
|
||||
*/
|
||||
public void apply(Ability ability) {
|
||||
if (configurator != null) {
|
||||
configurator.accept(ability);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package kamkeel.npcs.controllers.data.ability;
|
||||
|
||||
import kamkeel.npcs.controllers.data.ability.enums.AbilityPhase;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
|
||||
/**
|
||||
* Wraps a concurrent ability execution with its own independent lifecycle.
|
||||
* Concurrent abilities skip animations, sounds, and movement/rotation locks.
|
||||
* They run their execute/tick logic in parallel with the primary ability.
|
||||
* <p>
|
||||
* Used by the chain system when an entry is concurrent-capable and concurrent-enabled.
|
||||
*/
|
||||
public class ConcurrentSlot {
|
||||
|
||||
private final Ability ability;
|
||||
private boolean started = false;
|
||||
private boolean completed = false;
|
||||
|
||||
public ConcurrentSlot(Ability ability) {
|
||||
this.ability = ability;
|
||||
}
|
||||
|
||||
public Ability getAbility() {
|
||||
return ability;
|
||||
}
|
||||
|
||||
public boolean isCompleted() {
|
||||
return completed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the concurrent ability. Skips windup — goes straight to ACTIVE.
|
||||
* Called once when the slot is activated.
|
||||
*/
|
||||
public void start(EntityLivingBase caster, EntityLivingBase target) {
|
||||
// Skip windup for concurrent execution — fire immediately
|
||||
ability.setWindUpTicks(0);
|
||||
ability.start(target);
|
||||
started = true;
|
||||
|
||||
// Ability should now be in ACTIVE phase (0 windup → immediate)
|
||||
if (ability.getPhase() == AbilityPhase.ACTIVE) {
|
||||
ability.onExecute(caster, target);
|
||||
}
|
||||
|
||||
// Check if ability completed during onExecute (instant abilities like signalCompletion)
|
||||
if (ability.getPhase() == AbilityPhase.IDLE) {
|
||||
completed = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tick the concurrent ability. Called every game tick from AbstractDataAbilities.
|
||||
* Handles phase transitions including burst delay → re-execute cycles.
|
||||
*/
|
||||
public void tick(EntityLivingBase caster, EntityLivingBase target) {
|
||||
if (completed || !started) return;
|
||||
|
||||
AbilityPhase oldPhase = ability.getPhase();
|
||||
boolean phaseChanged = ability.tick();
|
||||
AbilityPhase newPhase = ability.getPhase();
|
||||
|
||||
switch (newPhase) {
|
||||
case ACTIVE:
|
||||
if (phaseChanged && oldPhase == AbilityPhase.BURST_DELAY) {
|
||||
// Re-entering ACTIVE after burst delay → re-execute (burst re-fire)
|
||||
ability.onExecute(caster, target);
|
||||
if (ability.getPhase() == AbilityPhase.IDLE) {
|
||||
completed = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Normal active tick
|
||||
ability.onActiveTick(caster, target, ability.getCurrentTick());
|
||||
if (ability.getPhase() == AbilityPhase.IDLE) {
|
||||
completed = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case BURST_DELAY:
|
||||
// Waiting between bursts — nothing to do, tick() handles countdown
|
||||
break;
|
||||
|
||||
case WINDUP:
|
||||
// Burst replay with windup — for concurrent, skip it by advancing
|
||||
// (windUpTicks was set to 0 at start, but burst replay may re-enter WINDUP)
|
||||
// The next tick() call will transition to ACTIVE
|
||||
break;
|
||||
|
||||
case IDLE:
|
||||
completed = true;
|
||||
break;
|
||||
|
||||
case DAZED:
|
||||
// Concurrent abilities don't get dazed — treat as completed
|
||||
completed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Force cleanup on interrupt. Called when the NPC is interrupted or combat ends.
|
||||
*/
|
||||
public void interrupt() {
|
||||
if (!completed) {
|
||||
ability.interrupt();
|
||||
completed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
package kamkeel.npcs.controllers.data.ability;
|
||||
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
import kamkeel.npcs.controllers.data.ability.enums.LockMode;
|
||||
import kamkeel.npcs.controllers.data.ability.enums.TargetingMode;
|
||||
import kamkeel.npcs.controllers.data.ability.enums.UserType;
|
||||
import kamkeel.npcs.controllers.data.telegraph.Telegraph;
|
||||
import kamkeel.npcs.controllers.data.telegraph.TelegraphInstance;
|
||||
import kamkeel.npcs.controllers.data.telegraph.TelegraphType;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import noppes.npcs.api.ability.ICustomAbility;
|
||||
import noppes.npcs.client.gui.builder.FieldDef;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A blank-slate ability that does nothing by itself.
|
||||
* All behavior is driven by script event hooks (abilityStart, abilityTick, abilityComplete,
|
||||
* abilityToggle, abilityToggleTick).
|
||||
* <p>
|
||||
* Supports two modes based on toggle configuration:
|
||||
* <ul>
|
||||
* <li><b>Instant mode</b> (toggleStates = 0): Uses standard execution lifecycle with
|
||||
* configurable duration. Script hooks: abilityStart, abilityTick, abilityComplete.</li>
|
||||
* <li><b>Toggle mode</b> (toggleStates >= 1): Uses toggle lifecycle.
|
||||
* Script hooks: abilityToggle, abilityToggleTick.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class CustomAbility extends Ability implements ICustomAbility {
|
||||
|
||||
private int durationTicks = 20;
|
||||
|
||||
// Telegraph dimension fields
|
||||
private float tRadius = 5.0f;
|
||||
private float tInnerRadius = 0.0f;
|
||||
private float tLength = 5.0f;
|
||||
private float tWidth = 2.0f;
|
||||
private float tAngle = 45.0f;
|
||||
|
||||
// Telegraph timing
|
||||
private int telegraphActiveTicks = 0;
|
||||
private boolean syncTelegraphWithDuration = true;
|
||||
|
||||
public CustomAbility() {
|
||||
this.typeId = "ability.cnpc.custom";
|
||||
this.name = "Custom";
|
||||
this.targetingMode = TargetingMode.SELF;
|
||||
this.lockMovement = LockMode.NO;
|
||||
this.cooldownTicks = 0;
|
||||
this.windUpTicks = 0;
|
||||
this.telegraphType = TelegraphType.NONE;
|
||||
this.showTelegraph = false;
|
||||
}
|
||||
|
||||
// ==================== EXECUTION ====================
|
||||
|
||||
@Override
|
||||
public void onExecute(EntityLivingBase caster, EntityLivingBase target) {
|
||||
if (durationTicks <= 0) {
|
||||
signalCompletion();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActiveTick(EntityLivingBase caster, EntityLivingBase target, int tick) {
|
||||
if (durationTicks > 0 && tick >= durationTicks) {
|
||||
signalCompletion();
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== PROPERTIES ====================
|
||||
|
||||
@Override
|
||||
public boolean hasDamage() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConcurrentCapable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTargetingModeLocked() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean allowFreeOnCast() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasOwnTelegraphControls() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// ==================== TELEGRAPH OVERRIDES ====================
|
||||
|
||||
@Override
|
||||
public boolean keepTelegraphDuringActive() {
|
||||
return getResolvedTelegraphActiveTicks() > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the effective telegraph active ticks: synced from duration or manual value.
|
||||
*/
|
||||
public int getResolvedTelegraphActiveTicks() {
|
||||
if (syncTelegraphWithDuration) {
|
||||
return durationTicks;
|
||||
}
|
||||
return telegraphActiveTicks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TelegraphInstance createTelegraph(EntityLivingBase caster, EntityLivingBase target) {
|
||||
if (!isShowTelegraph() || getTelegraphType() == TelegraphType.NONE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Telegraph telegraph;
|
||||
double x, y, z;
|
||||
float yaw = caster.rotationYaw;
|
||||
TelegraphType tType = getTelegraphType();
|
||||
|
||||
boolean positionAtCaster = targetingMode == TargetingMode.AOE_SELF ||
|
||||
targetingMode == TargetingMode.SELF ||
|
||||
tType == TelegraphType.LINE ||
|
||||
tType == TelegraphType.CONE;
|
||||
|
||||
if (positionAtCaster) {
|
||||
x = caster.posX;
|
||||
y = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ);
|
||||
z = caster.posZ;
|
||||
} else if (target != null) {
|
||||
x = target.posX;
|
||||
y = findGroundLevel(caster.worldObj, target.posX, target.posY, target.posZ);
|
||||
z = target.posZ;
|
||||
} else {
|
||||
x = caster.posX;
|
||||
y = findGroundLevel(caster.worldObj, caster.posX, caster.posY, caster.posZ);
|
||||
z = caster.posZ;
|
||||
}
|
||||
|
||||
switch (tType) {
|
||||
case CIRCLE:
|
||||
telegraph = Telegraph.circle(tRadius);
|
||||
break;
|
||||
case RING:
|
||||
telegraph = Telegraph.ring(tRadius, tInnerRadius);
|
||||
break;
|
||||
case LINE:
|
||||
telegraph = Telegraph.line(tLength, tWidth);
|
||||
break;
|
||||
case CONE:
|
||||
telegraph = Telegraph.cone(tLength, tAngle, tInnerRadius);
|
||||
break;
|
||||
case POINT:
|
||||
telegraph = new Telegraph("", TelegraphType.POINT);
|
||||
break;
|
||||
case SQUARE:
|
||||
telegraph = Telegraph.square(tRadius);
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
int activeTicks = getResolvedTelegraphActiveTicks();
|
||||
int totalDuration = windUpTicks + activeTicks;
|
||||
telegraph.setDurationTicks(Math.max(1, totalDuration));
|
||||
telegraph.setColor(windUpColor);
|
||||
telegraph.setWarningColor(activeColor);
|
||||
if (windUpTicks > 0) {
|
||||
telegraph.setWarningStartTick(windUpTicks);
|
||||
} else {
|
||||
telegraph.setWarningStartTick(0);
|
||||
}
|
||||
telegraph.setHeightOffset(telegraphHeightOffset);
|
||||
|
||||
TelegraphInstance instance = new TelegraphInstance(telegraph, x, y, z, yaw);
|
||||
instance.setCasterEntityId(caster.getEntityId());
|
||||
|
||||
if (positionAtCaster) {
|
||||
instance.setEntityIdToFollow(caster.getEntityId());
|
||||
if (tType == TelegraphType.LINE || tType == TelegraphType.CONE) {
|
||||
if (!isRotationLockedDuringWindup()) {
|
||||
if (target != null) {
|
||||
instance.setTargetEntityId(target.getEntityId());
|
||||
} else {
|
||||
instance.setTrackFollowedEntityYaw(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (target != null) {
|
||||
instance.setEntityIdToFollow(target.getEntityId());
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTelegraphRadius() {
|
||||
return tRadius;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTelegraphInnerRadius() {
|
||||
return tInnerRadius;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTelegraphLength() {
|
||||
return tLength;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTelegraphWidth() {
|
||||
return tWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public float getTelegraphAngle() {
|
||||
return tAngle;
|
||||
}
|
||||
|
||||
// ==================== FIELDS ====================
|
||||
|
||||
@Override
|
||||
public int getDurationTicks() {
|
||||
return durationTicks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDurationTicks(int ticks) {
|
||||
this.durationTicks = Math.max(0, ticks);
|
||||
}
|
||||
|
||||
public float getTRadius() {
|
||||
return tRadius;
|
||||
}
|
||||
|
||||
public void setTRadius(float radius) {
|
||||
this.tRadius = Math.max(0, radius);
|
||||
}
|
||||
|
||||
public float getTInnerRadius() {
|
||||
return tInnerRadius;
|
||||
}
|
||||
|
||||
public void setTInnerRadius(float innerRadius) {
|
||||
this.tInnerRadius = Math.max(0, innerRadius);
|
||||
}
|
||||
|
||||
public float getTLength() {
|
||||
return tLength;
|
||||
}
|
||||
|
||||
public void setTLength(float length) {
|
||||
this.tLength = Math.max(0, length);
|
||||
}
|
||||
|
||||
public float getTWidth() {
|
||||
return tWidth;
|
||||
}
|
||||
|
||||
public void setTWidth(float width) {
|
||||
this.tWidth = Math.max(0, width);
|
||||
}
|
||||
|
||||
public float getTAngle() {
|
||||
return tAngle;
|
||||
}
|
||||
|
||||
public void setTAngle(float angle) {
|
||||
this.tAngle = Math.max(0, angle);
|
||||
}
|
||||
|
||||
public int getTelegraphActiveTicks() {
|
||||
return telegraphActiveTicks;
|
||||
}
|
||||
|
||||
public void setTelegraphActiveTicks(int ticks) {
|
||||
this.telegraphActiveTicks = Math.max(0, ticks);
|
||||
}
|
||||
|
||||
public boolean isSyncTelegraphWithDuration() {
|
||||
return syncTelegraphWithDuration;
|
||||
}
|
||||
|
||||
public void setSyncTelegraphWithDuration(boolean sync) {
|
||||
this.syncTelegraphWithDuration = sync;
|
||||
}
|
||||
|
||||
// ==================== ICustomAbility ====================
|
||||
|
||||
@Override
|
||||
public int getTelegraphShapeType() {
|
||||
return getTelegraphType().ordinal();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTelegraphShapeType(int type) {
|
||||
TelegraphType[] values = TelegraphType.values();
|
||||
if (type >= 0 && type < values.length) {
|
||||
setTelegraphType(values[type]);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTelegraphRadius(float radius) {
|
||||
this.tRadius = Math.max(0, radius);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTelegraphInnerRadius(float innerRadius) {
|
||||
this.tInnerRadius = Math.max(0, innerRadius);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTelegraphLength(float length) {
|
||||
this.tLength = Math.max(0, length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTelegraphWidth(float width) {
|
||||
this.tWidth = Math.max(0, width);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTelegraphAngle(float angle) {
|
||||
this.tAngle = Math.max(0, angle);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTargetingModeType() {
|
||||
return getTargetingMode().ordinal();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTargetingModeType(int type) {
|
||||
TargetingMode[] values = TargetingMode.values();
|
||||
if (type >= 0 && type < values.length) {
|
||||
setTargetingMode(values[type]);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== NBT ====================
|
||||
|
||||
@Override
|
||||
public void writeTypeNBT(NBTTagCompound nbt) {
|
||||
nbt.setInteger("durationTicks", durationTicks);
|
||||
nbt.setFloat("tRadius", tRadius);
|
||||
nbt.setFloat("tInnerRadius", tInnerRadius);
|
||||
nbt.setFloat("tLength", tLength);
|
||||
nbt.setFloat("tWidth", tWidth);
|
||||
nbt.setFloat("tAngle", tAngle);
|
||||
nbt.setInteger("telegraphActiveTicks", telegraphActiveTicks);
|
||||
nbt.setBoolean("syncTelegraphWithDuration", syncTelegraphWithDuration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readTypeNBT(NBTTagCompound nbt) {
|
||||
this.durationTicks = Math.max(0, nbt.getInteger("durationTicks"));
|
||||
this.tRadius = nbt.hasKey("tRadius") ? nbt.getFloat("tRadius") : 5.0f;
|
||||
this.tInnerRadius = nbt.hasKey("tInnerRadius") ? nbt.getFloat("tInnerRadius") : 0.0f;
|
||||
this.tLength = nbt.hasKey("tLength") ? nbt.getFloat("tLength") : 5.0f;
|
||||
this.tWidth = nbt.hasKey("tWidth") ? nbt.getFloat("tWidth") : 2.0f;
|
||||
this.tAngle = nbt.hasKey("tAngle") ? nbt.getFloat("tAngle") : 45.0f;
|
||||
this.telegraphActiveTicks = nbt.hasKey("telegraphActiveTicks") ? nbt.getInteger("telegraphActiveTicks") : 0;
|
||||
this.syncTelegraphWithDuration = nbt.hasKey("syncTelegraphWithDuration") ? nbt.getBoolean("syncTelegraphWithDuration") : true;
|
||||
}
|
||||
|
||||
// ==================== GUI ====================
|
||||
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void getAbilityDefinitions(List<FieldDef> defs) {
|
||||
// User Type (NPC / Player / Both)
|
||||
defs.add(FieldDef.enumField("ability.allowedBy", UserType.class,
|
||||
this::getAllowedBy, this::setAllowedBy));
|
||||
|
||||
// Targeting Mode
|
||||
defs.add(FieldDef.enumField("ability.targetingMode", TargetingMode.class,
|
||||
this::getTargetingMode, this::setTargetingMode));
|
||||
|
||||
// Toggle section
|
||||
defs.add(FieldDef.section("ability.section.toggle"));
|
||||
defs.add(FieldDef.boolField("ability.toggleEnabled",
|
||||
this::isToggleable, enabled -> setToggleStates(enabled ? Math.max(1, getToggleStates()) : 0)));
|
||||
defs.add(FieldDef.intField("ability.toggleStates", this::getToggleStates, this::setToggleStates)
|
||||
.range(1, 10)
|
||||
.visibleWhen(this::isToggleable));
|
||||
defs.add(FieldDef.boolField("ability.hasActiveToggle", this::hasActiveToggle, this::setHasActiveToggle)
|
||||
.visibleWhen(this::isToggleable));
|
||||
|
||||
// Duration (instant mode only)
|
||||
defs.add(FieldDef.section("ability.section.execution")
|
||||
.visibleWhen(() -> !this.isToggleable()));
|
||||
defs.add(FieldDef.intField("ability.duration", this::getDurationTicks, this::setDurationTicks)
|
||||
.range(0, 6000)
|
||||
.visibleWhen(() -> !this.isToggleable()));
|
||||
|
||||
// ── Telegraph Controls (Effects tab) ─────────────────────────
|
||||
defs.add(FieldDef.section("ability.section.telegraph").tab("Effects"));
|
||||
defs.add(FieldDef.enumField("ability.telegraphShape", TelegraphType.class,
|
||||
this::getTelegraphType, this::setTelegraphType).tab("Effects")
|
||||
.hover("ability.hover.telegraphShape"));
|
||||
defs.add(FieldDef.boolField("ability.showTelegraph", this::isShowTelegraph, this::setShowTelegraph)
|
||||
.tab("Effects").visibleWhen(this::hasTelegraphShape)
|
||||
.hover("ability.hover.showTelegraph"));
|
||||
defs.add(FieldDef.colorSubGui("ability.windUpColor", this::getWindUpColor, this::setWindUpColor)
|
||||
.tab("Effects").visibleWhen(this::isTelegraphVisible)
|
||||
.hover("ability.hover.windUpColor"));
|
||||
defs.add(FieldDef.colorSubGui("ability.activeColor", this::getActiveColor, this::setActiveColor)
|
||||
.tab("Effects").visibleWhen(this::isTelegraphVisible)
|
||||
.hover("ability.hover.activeColor"));
|
||||
defs.add(FieldDef.floatField("ability.telegraphHeight", this::getTelegraphHeightOffset, this::setTelegraphHeightOffset)
|
||||
.tab("Effects").visibleWhen(this::isTelegraphVisible)
|
||||
.hover("ability.hover.telegraphHeight"));
|
||||
|
||||
// Telegraph active duration with sync toggle (mirrors windup sync pattern)
|
||||
defs.add(FieldDef.row(
|
||||
FieldDef.intField("ability.telegraphActiveTicks", this::getTelegraphActiveTicks, this::setTelegraphActiveTicks).range(0, 6000)
|
||||
.hover("ability.hover.telegraphActiveTicks"),
|
||||
FieldDef.boolField("ability.syncTelegraph", this::isSyncTelegraphWithDuration, this::setSyncTelegraphWithDuration)
|
||||
.hover("ability.hover.syncTelegraph")
|
||||
).tab("Effects").visibleWhen(() -> isTelegraphVisible() && !isSyncTelegraphWithDuration()));
|
||||
defs.add(FieldDef.row(
|
||||
FieldDef.labelField("ability.telegraphActiveTicks", () -> getResolvedTelegraphActiveTicks() + "t"),
|
||||
FieldDef.boolField("ability.syncTelegraph", this::isSyncTelegraphWithDuration, this::setSyncTelegraphWithDuration)
|
||||
.hover("ability.hover.syncTelegraph")
|
||||
).tab("Effects").visibleWhen(() -> isTelegraphVisible() && isSyncTelegraphWithDuration()));
|
||||
|
||||
// Shape-specific dimension fields
|
||||
defs.add(FieldDef.floatField("ability.telegraphRadius", this::getTRadius, this::setTRadius)
|
||||
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsRadius())
|
||||
.hover("ability.hover.telegraphRadius"));
|
||||
defs.add(FieldDef.floatField("ability.telegraphInnerRadius", this::getTInnerRadius, this::setTInnerRadius)
|
||||
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsInnerRadius())
|
||||
.hover("ability.hover.telegraphInnerRadius"));
|
||||
defs.add(FieldDef.floatField("ability.telegraphLength", this::getTLength, this::setTLength)
|
||||
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsLength())
|
||||
.hover("ability.hover.telegraphLength"));
|
||||
defs.add(FieldDef.floatField("ability.telegraphWidth", this::getTWidth, this::setTWidth)
|
||||
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsWidth())
|
||||
.hover("ability.hover.telegraphWidth"));
|
||||
defs.add(FieldDef.floatField("ability.telegraphAngle", this::getTAngle, this::setTAngle)
|
||||
.tab("Effects").visibleWhen(() -> isTelegraphVisible() && needsAngle())
|
||||
.hover("ability.hover.telegraphAngle"));
|
||||
}
|
||||
|
||||
// ==================== TELEGRAPH VISIBILITY HELPERS ====================
|
||||
|
||||
private boolean hasTelegraphShape() {
|
||||
return getTelegraphType() != TelegraphType.NONE;
|
||||
}
|
||||
|
||||
private boolean isTelegraphVisible() {
|
||||
return hasTelegraphShape() && isShowTelegraph();
|
||||
}
|
||||
|
||||
private boolean needsRadius() {
|
||||
TelegraphType t = getTelegraphType();
|
||||
return t == TelegraphType.CIRCLE || t == TelegraphType.RING || t == TelegraphType.SQUARE;
|
||||
}
|
||||
|
||||
private boolean needsInnerRadius() {
|
||||
TelegraphType t = getTelegraphType();
|
||||
return t == TelegraphType.RING || t == TelegraphType.CONE;
|
||||
}
|
||||
|
||||
private boolean needsLength() {
|
||||
TelegraphType t = getTelegraphType();
|
||||
return t == TelegraphType.LINE || t == TelegraphType.CONE;
|
||||
}
|
||||
|
||||
private boolean needsWidth() {
|
||||
return getTelegraphType() == TelegraphType.LINE;
|
||||
}
|
||||
|
||||
private boolean needsAngle() {
|
||||
return getTelegraphType() == TelegraphType.CONE;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 851 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user