载入中...
搜索中...
未找到
ShapeGrammar.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cctype>
4#include <cmath>
5#include <cstdlib>
6#include <functional>
7#include <simplesquirrel/simplesquirrel.hpp>
8#include <sstream>
10
11// ShapeGrammar.cpp
12namespace eve::procgen {
13namespace {
14
15uint32_t mixGrammar(uint32_t value) {
16 value += 0x9e3779b9u;
17 value = (value ^ (value >> 16u)) * 0x21f0aaadu;
18 value = (value ^ (value >> 15u)) * 0x735a2d97u;
19 return value ^ (value >> 15u);
20}
21float grammarUnit(uint32_t seed) { return float(mixGrammar(seed) >> 8u) * (1.f / 16777216.f); }
22
23float polylineLength(const PointSet& points) {
24 float result = 0.f;
25 for (size_t i = 1; i < points.points().size(); ++i) {
26 const auto& a = points.points()[i - 1];
27 const auto& b = points.points()[i];
28 const float dx = b.x - a.x;
29 const float dy = b.y - a.y;
30 const float dz = b.z - a.z;
31 result += std::sqrt(dx * dx + dy * dy + dz * dz);
32 }
33 return result;
34}
35
36bool samplePolyline(const PointSet& points, float distance, ProcgenPoint& output) {
37 float cursor = 0.f;
38 for (size_t i = 1; i < points.points().size(); ++i) {
39 const auto& a = points.points()[i - 1];
40 const auto& b = points.points()[i];
41 const float dx = b.x - a.x;
42 const float dy = b.y - a.y;
43 const float dz = b.z - a.z;
44 const float length = std::sqrt(dx * dx + dy * dy + dz * dz);
45 if (length <= 0.f) continue;
46 if (distance <= cursor + length || i + 1 == points.points().size()) {
47 const float t = std::clamp((distance - cursor) / length, 0.f, 1.f);
48 output.x = a.x + dx * t;
49 output.y = a.y + dy * t;
50 output.z = a.z + dz * t;
51 output.yaw = std::atan2(dz, dx) * 57.29577951308232f;
52 return true;
53 }
54 cursor += length;
55 }
56 return false;
57}
58
59} // namespace
60
62 modules_.clear();
63 moduleOrder_.clear();
64 error_.clear();
65 lastSymbolCount_ = 0;
66 lastUsedLength_ = 0.f;
67 lastSplineLength_ = 0.f;
68}
69
70bool ShapeGrammar::addModule(const std::string& symbol, const std::string& asset, float length, float weight) {
71 if (symbol.empty() || asset.empty() || length <= 0.f || weight <= 0.f) return false;
72 const auto existing = modules_.find(symbol);
73 if (existing != modules_.end() && !existing->second.empty() &&
74 std::abs(existing->second.front().length - length) > 0.0001f)
75 return false;
76 if (modules_.find(symbol) == modules_.end()) moduleOrder_.push_back(symbol);
77 modules_[symbol].push_back({asset, length, weight});
78 return true;
79}
80
81bool ShapeGrammar::removeModule(const std::string& symbol) {
82 if (modules_.erase(symbol) == 0) return false;
83 moduleOrder_.erase(std::remove(moduleOrder_.begin(), moduleOrder_.end(), symbol), moduleOrder_.end());
84 return true;
85}
86bool ShapeGrammar::hasModule(const std::string& symbol) const { return modules_.find(symbol) != modules_.end(); }
87int ShapeGrammar::getModuleCount() const { return int(moduleOrder_.size()); }
88std::string ShapeGrammar::getModuleSymbol(int index) const {
89 return index >= 0 && index < int(moduleOrder_.size()) ? moduleOrder_[size_t(index)] : std::string();
90}
91int ShapeGrammar::getVariantCount(const std::string& symbol) const {
92 const auto found = modules_.find(symbol);
93 return found == modules_.end() ? 0 : int(found->second.size());
94}
95std::string ShapeGrammar::getVariantAsset(const std::string& symbol, int index) const {
96 const auto found = modules_.find(symbol);
97 return found != modules_.end() && index >= 0 && index < int(found->second.size())
98 ? found->second[size_t(index)].asset
99 : std::string();
100}
101float ShapeGrammar::getVariantLength(const std::string& symbol, int index) const {
102 const auto found = modules_.find(symbol);
103 return found != modules_.end() && index >= 0 && index < int(found->second.size())
104 ? found->second[size_t(index)].length
105 : 0.f;
106}
107
108bool ShapeGrammar::validate(const std::string& grammar) {
109 error_.clear();
110 Parser parser{grammar};
111 const auto parsed = parser.sequence();
112 if (!parser.error.empty()) {
113 error_ = parser.error;
114 return false;
115 }
116 if (parsed.empty()) {
117 error_ = "grammar is empty";
118 return false;
119 }
120 std::vector<const Element*> stack;
121 stack.reserve(parsed.size());
122 for (const auto& element : parsed) stack.push_back(&element);
123 while (!stack.empty()) {
124 const Element* element = stack.back();
125 stack.pop_back();
126 if (!element->symbol.empty() && !hasModule(element->symbol)) {
127 error_ = "unknown module: " + element->symbol;
128 return false;
129 }
130 for (const auto& child : element->children) stack.push_back(&child);
131 }
132 return true;
133}
134
135PointSet* ShapeGrammar::generate(const std::string& grammar, PointSet* controlPoints, uint32_t seed,
136 bool acceptIncomplete) {
137 error_.clear();
138 lastSymbolCount_ = 0;
139 lastUsedLength_ = 0.f;
140 lastSplineLength_ = 0.f;
141 if (!controlPoints || controlPoints->getCount() < 2) {
142 error_ = "generate: requires at least two control points";
143 return nullptr;
144 }
145 if (!validate(grammar)) return nullptr;
146 Parser parser{grammar};
147 const auto parsed = parser.sequence();
148 lastSplineLength_ = polylineLength(*controlPoints);
149 if (!acceptIncomplete && sequenceMinLength(parsed) > lastSplineLength_ + 0.0001f) {
150 error_ = "mandatory grammar does not fit spline";
151 return nullptr;
152 }
153 std::vector<std::string> symbols;
154 float used = 0.f;
155 if (!expandSequence(parsed, lastSplineLength_, symbols, used)) {
156 error_ = "grammar expansion failed";
157 return nullptr;
158 }
159
161 float cursor = 0.f;
162 for (size_t i = 0; i < symbols.size(); ++i) {
163 const auto* variant = chooseVariant(symbols[i], mixGrammar(seed ^ uint32_t(i)));
164 if (!variant || cursor + variant->length > lastSplineLength_ + 0.0001f) {
165 if (!acceptIncomplete) {
166 error_ = "expanded module does not fit spline: " + symbols[i];
167 return nullptr;
168 }
169 break;
170 }
172 if (!samplePolyline(*controlPoints, cursor + variant->length * 0.5f, point)) break;
173 point.seed = mixGrammar(seed ^ uint32_t(i));
174 const int pointIndex = output.appendPoint(std::move(point));
175 output.trySetStringAttribute(pointIndex, "module", symbols[i]).expect("shape grammar module metadata schema");
176 output.trySetStringAttribute(pointIndex, "asset", variant->asset).expect("shape grammar asset metadata schema");
177 output.trySetFloatAttribute(pointIndex, "length", variant->length)
178 .expect("shape grammar length metadata schema");
179 cursor += variant->length;
180 }
181 lastSymbolCount_ = output.getCount();
182 lastUsedLength_ = cursor;
183 return new PointSet(std::move(output));
184}
185
186std::string ShapeGrammar::getError() const { return error_; }
187std::string ShapeGrammar::debugReport() const {
188 std::ostringstream out;
189 out << "modules=" << modules_.size() << " symbols=" << lastSymbolCount_ << " used=" << lastUsedLength_
190 << " spline=" << lastSplineLength_;
191 if (!error_.empty()) out << " error=" << error_;
192 return out.str();
193}
194
195void ShapeGrammar::Parser::skipWhitespace() {
196 while (position < text.size() && std::isspace(static_cast<unsigned char>(text[position]))) ++position;
197}
198
199std::vector<ShapeGrammar::Element> ShapeGrammar::Parser::sequence(char terminator) {
200 std::vector<Element> result;
201 while (position < text.size()) {
202 skipWhitespace();
203 if (position >= text.size()) break;
204 if (terminator != '\0' && text[position] == terminator) {
205 ++position;
206 return result;
207 }
208 Element element;
209 if (text[position] == '[') {
210 ++position;
211 element.children = sequence(']');
212 if (!error.empty()) return {};
213 if (element.children.empty()) {
214 error = "empty grammar group";
215 return {};
216 }
217 } else {
218 const size_t start = position;
219 while (position < text.size()) {
220 const unsigned char ch = static_cast<unsigned char>(text[position]);
221 // Decimal digits are reserved for the exact-repeat suffix: A3 means
222 // three A modules. Keeping module tokens digit-free removes the
223 // otherwise unresolvable ambiguity between a symbol and its repeat.
224 if (!std::isalpha(ch) && ch != '_' && ch != '-' && ch != '.') break;
225 ++position;
226 }
227 if (start == position) {
228 error = "expected module at character " + std::to_string(position);
229 return {};
230 }
231 element.symbol = text.substr(start, position - start);
232 }
233 skipWhitespace();
234 if (position < text.size() && text[position] == '*') {
235 element.repeatMin = 0;
236 element.repeatMax = -1;
237 ++position;
238 } else if (position < text.size() && text[position] == '+') {
239 element.repeatMin = 1;
240 element.repeatMax = -1;
241 ++position;
242 } else if (position < text.size() && std::isdigit(static_cast<unsigned char>(text[position]))) {
243 const size_t start = position;
244 while (position < text.size() && std::isdigit(static_cast<unsigned char>(text[position]))) ++position;
245 element.repeatMin = element.repeatMax =
246 std::max(0, std::atoi(text.substr(start, position - start).c_str()));
247 }
248 result.push_back(std::move(element));
249 skipWhitespace();
250 if (position < text.size() && text[position] == ',') {
251 ++position;
252 continue;
253 }
254 if (terminator != '\0' && position < text.size() && text[position] == terminator) continue;
255 if (position < text.size()) {
256 error = "expected comma at character " + std::to_string(position);
257 return {};
258 }
259 }
260 if (terminator != '\0') error = "unterminated grammar group";
261 return result;
262}
263
264float ShapeGrammar::elementMinLength(const Element& element) const {
265 float unit = 0.f;
266 if (!element.symbol.empty()) {
267 const auto found = modules_.find(element.symbol);
268 if (found != modules_.end() && !found->second.empty()) {
269 unit = found->second.front().length;
270 for (const auto& variant : found->second) unit = std::min(unit, variant.length);
271 }
272 } else {
273 unit = sequenceMinLength(element.children);
274 }
275 return unit * float(element.repeatMin);
276}
277
278float ShapeGrammar::sequenceMinLength(const std::vector<Element>& sequence, size_t from) const {
279 float result = 0.f;
280 for (size_t i = from; i < sequence.size(); ++i) result += elementMinLength(sequence[i]);
281 return result;
282}
283
284bool ShapeGrammar::expandSequence(const std::vector<Element>& sequence, float available,
285 std::vector<std::string>& symbols, float& used) const {
286 for (size_t i = 0; i < sequence.size(); ++i) {
287 const auto& element = sequence[i];
288 float unitLength = !element.symbol.empty() ? elementMinLength(Element{element.symbol, {}, 1, 1})
289 : sequenceMinLength(element.children);
290 if (unitLength <= 0.f) return false;
291 const float reservedAfter = sequenceMinLength(sequence, i + 1);
292 int repeats = element.repeatMin;
293 if (element.repeatMax < 0) {
294 const float room = std::max(0.f, available - used - reservedAfter);
295 repeats = std::max(element.repeatMin, int(std::floor(room / unitLength)));
296 } else {
297 repeats = element.repeatMax;
298 }
299 for (int repeat = 0; repeat < repeats; ++repeat) {
300 if (used + unitLength + reservedAfter > available + 0.0001f) return true;
301 if (!element.symbol.empty()) {
302 symbols.push_back(element.symbol);
303 used += unitLength;
304 } else {
305 float groupUsed = 0.f;
306 if (!expandSequence(element.children, available - used - reservedAfter, symbols, groupUsed))
307 return false;
308 used += groupUsed;
309 }
310 }
311 }
312 return true;
313}
314
315const ShapeModuleVariant* ShapeGrammar::chooseVariant(const std::string& symbol, uint32_t seed) const {
316 const auto found = modules_.find(symbol);
317 if (found == modules_.end() || found->second.empty()) return nullptr;
318 float total = 0.f;
319 for (const auto& variant : found->second) total += variant.weight;
320 float choice = grammarUnit(seed) * total;
321 for (const auto& variant : found->second) {
322 choice -= variant.weight;
323 if (choice <= 0.f) return &variant;
324 }
325 return &found->second.back();
326}
327
328} // namespace eve::procgen
329
330// ShapeGrammarScript.cpp
331namespace eve::procgen {
332
333void exposeShapeGrammar(ssq::Table& table) {
334 auto grammar = table.addClass<ShapeGrammar>(
335 "ProcgenShapeGrammar", std::function<ShapeGrammar*()>([]() -> ShapeGrammar* { return nullptr; }), true);
336 grammar.addFunc("clear", &ShapeGrammar::clear);
337 grammar.addFunc("addModule", &ShapeGrammar::addModule);
338 grammar.addFunc("removeModule", &ShapeGrammar::removeModule);
339 grammar.addFunc("hasModule", &ShapeGrammar::hasModule);
340 grammar.addFunc("getModuleCount", &ShapeGrammar::getModuleCount);
341 grammar.addFunc("getModuleSymbol", &ShapeGrammar::getModuleSymbol);
342 grammar.addFunc("getVariantCount", &ShapeGrammar::getVariantCount);
343 grammar.addFunc("getVariantAsset", &ShapeGrammar::getVariantAsset);
344 grammar.addFunc("getVariantLength", &ShapeGrammar::getVariantLength);
345 grammar.addFunc("validate", &ShapeGrammar::validate);
346 grammar.addFunc("generate", &ShapeGrammar::generate);
347 grammar.addFunc("getError", &ShapeGrammar::getError);
348 grammar.addFunc("debugReport", &ShapeGrammar::debugReport);
349}
350
351} // namespace eve::procgen
Duration start
std::string output
std::size_t cursor
std::string variant
std::int32_t second
float length
std::array< float, 3 > position
std::string from
Poco::JSON::Object::Ptr result
uint64_t used
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
glm::dvec3 dx
glm::dvec3 dz
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
std::string error
Definition Package.cpp:174
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
float t
bool found
std::string text
ScriptStructure out
float dy
Definition Shadow.cpp:151
std::string element
TacticalUnit * unit
uint32_t seed
Definition TreeMesh.cpp:276
int children
Definition TreeMesh.cpp:432
float size
Definition TreeMesh.cpp:158
double weight
uint32_t index
glm::vec3 point
Script-friendly collection of attributed 3D samples.
Definition PointSet.h:59
int getCount() const
Returns the count.
Definition PointSet.cpp:49
Module-based shape grammar expanded continuously along a 3D polyline.
std::string getModuleSymbol(int index) const
Returns the module symbol.
bool removeModule(const std::string &symbol)
Removes module.
void clear()
Remove every registered symbol and diagnostic.
int getModuleCount() const
Returns the module count.
float getVariantLength(const std::string &symbol, int index) const
Returns the variant length.
std::string getError() const
Returns the error.
bool validate(const std::string &grammar)
Parse and validate grammar without generating output.
bool hasModule(const std::string &symbol) const
True when module.
int getVariantCount(const std::string &symbol) const
Returns the variant count.
bool addModule(const std::string &symbol, const std::string &asset, float length, float weight=1.f)
Register a weighted asset variant for a symbol.
std::string getVariantAsset(const std::string &symbol, int index) const
Returns the variant asset.
PointSet * generate(const std::string &grammar, PointSet *controlPoints, uint32_t seed, bool acceptIncomplete)
Expand grammar along control points.
std::string debugReport() const
Debug report.
double polylineLength(const Polyline &pl)
Total length of an open polyline.
void exposeShapeGrammar(ssq::Table &table)
Register shape-grammar script types on the Procgen module table.
One deterministic sample used by script-first procedural pipelines.
Definition PointSet.h:17