BillboardSet.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/Batch.h"
  26. #include "../Graphics/BillboardSet.h"
  27. #include "../Graphics/Camera.h"
  28. #include "../Graphics/Geometry.h"
  29. #include "../Graphics/Graphics.h"
  30. #include "../Graphics/IndexBuffer.h"
  31. #include "../Graphics/OctreeQuery.h"
  32. #include "../Graphics/VertexBuffer.h"
  33. #include "../IO/MemoryBuffer.h"
  34. #include "../Resource/ResourceCache.h"
  35. #include "../Scene/Node.h"
  36. #include "../DebugNew.h"
  37. namespace Urho3D
  38. {
  39. extern const char* GEOMETRY_CATEGORY;
  40. static const float INV_SQRT_TWO = 1.0f / sqrtf(2.0f);
  41. const char* faceCameraModeNames[] =
  42. {
  43. "None",
  44. "Rotate XYZ",
  45. "Rotate Y",
  46. "LookAt XYZ",
  47. "LookAt Y",
  48. "LookAt Mixed",
  49. "Direction",
  50. nullptr
  51. };
  52. static const StringVector billboardsStructureElementNames =
  53. {
  54. "Billboard Count",
  55. " Position",
  56. " Size",
  57. " UV Coordinates",
  58. " Color",
  59. " Rotation",
  60. " Direction",
  61. " Is Enabled"
  62. };
  63. inline bool CompareBillboards(Billboard* lhs, Billboard* rhs)
  64. {
  65. return lhs->sortDistance_ > rhs->sortDistance_;
  66. }
  67. BillboardSet::BillboardSet(Context* context) :
  68. Drawable(context, DRAWABLE_GEOMETRY),
  69. animationLodBias_(1.0f),
  70. animationLodTimer_(0.0f),
  71. relative_(true),
  72. scaled_(true),
  73. sorted_(false),
  74. fixedScreenSize_(false),
  75. faceCameraMode_(FC_ROTATE_XYZ),
  76. minAngle_(0.0f),
  77. geometry_(new Geometry(context)),
  78. vertexBuffer_(new VertexBuffer(context_)),
  79. indexBuffer_(new IndexBuffer(context_)),
  80. bufferSizeDirty_(true),
  81. bufferDirty_(true),
  82. forceUpdate_(false),
  83. geometryTypeUpdate_(false),
  84. sortThisFrame_(false),
  85. hasOrthoCamera_(false),
  86. sortFrameNumber_(0),
  87. previousOffset_(Vector3::ZERO)
  88. {
  89. geometry_->SetVertexBuffer(0, vertexBuffer_);
  90. geometry_->SetIndexBuffer(indexBuffer_);
  91. batches_.Resize(1);
  92. batches_[0].geometry_ = geometry_;
  93. batches_[0].geometryType_ = GEOM_BILLBOARD;
  94. batches_[0].worldTransform_ = &transforms_[0];
  95. }
  96. BillboardSet::~BillboardSet() = default;
  97. void BillboardSet::RegisterObject(Context* context)
  98. {
  99. context->RegisterFactory<BillboardSet>(GEOMETRY_CATEGORY);
  100. URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT);
  101. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()),
  102. AM_DEFAULT);
  103. URHO3D_ACCESSOR_ATTRIBUTE("Relative Position", IsRelative, SetRelative, bool, true, AM_DEFAULT);
  104. URHO3D_ACCESSOR_ATTRIBUTE("Relative Scale", IsScaled, SetScaled, bool, true, AM_DEFAULT);
  105. URHO3D_ACCESSOR_ATTRIBUTE("Sort By Distance", IsSorted, SetSorted, bool, false, AM_DEFAULT);
  106. URHO3D_ACCESSOR_ATTRIBUTE("Fixed Screen Size", IsFixedScreenSize, SetFixedScreenSize, bool, false, AM_DEFAULT);
  107. URHO3D_ACCESSOR_ATTRIBUTE("Can Be Occluded", IsOccludee, SetOccludee, bool, true, AM_DEFAULT);
  108. URHO3D_ATTRIBUTE("Cast Shadows", bool, castShadows_, false, AM_DEFAULT);
  109. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Face Camera Mode", GetFaceCameraMode, SetFaceCameraMode, FaceCameraMode, faceCameraModeNames, FC_ROTATE_XYZ, AM_DEFAULT);
  110. URHO3D_ACCESSOR_ATTRIBUTE("Min Angle", GetMinAngle, SetMinAngle, float, 0.0f, AM_DEFAULT);
  111. URHO3D_ACCESSOR_ATTRIBUTE("Draw Distance", GetDrawDistance, SetDrawDistance, float, 0.0f, AM_DEFAULT);
  112. URHO3D_ACCESSOR_ATTRIBUTE("Shadow Distance", GetShadowDistance, SetShadowDistance, float, 0.0f, AM_DEFAULT);
  113. URHO3D_ACCESSOR_ATTRIBUTE("Animation LOD Bias", GetAnimationLodBias, SetAnimationLodBias, float, 1.0f, AM_DEFAULT);
  114. URHO3D_COPY_BASE_ATTRIBUTES(Drawable);
  115. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Billboards", GetBillboardsAttr, SetBillboardsAttr, VariantVector, Variant::emptyVariantVector, AM_FILE)
  116. .SetMetadata(AttributeMetadata::P_VECTOR_STRUCT_ELEMENTS, billboardsStructureElementNames);
  117. URHO3D_ACCESSOR_ATTRIBUTE("Network Billboards", GetNetBillboardsAttr, SetNetBillboardsAttr, PODVector<unsigned char>,
  118. Variant::emptyBuffer, AM_NET | AM_NOEDIT);
  119. }
  120. void BillboardSet::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  121. {
  122. // If no billboard-level testing, use the Drawable test
  123. if (query.level_ < RAY_TRIANGLE)
  124. {
  125. Drawable::ProcessRayQuery(query, results);
  126. return;
  127. }
  128. // Check ray hit distance to AABB before proceeding with billboard-level tests
  129. if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
  130. return;
  131. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  132. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  133. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  134. for (unsigned i = 0; i < billboards_.Size(); ++i)
  135. {
  136. if (!billboards_[i].enabled_)
  137. continue;
  138. // Approximate the billboards as spheres for raycasting
  139. float size = INV_SQRT_TWO * (billboards_[i].size_.x_ * billboardScale.x_ + billboards_[i].size_.y_ * billboardScale.y_);
  140. if (fixedScreenSize_)
  141. size *= billboards_[i].screenScaleFactor_;
  142. Vector3 center = billboardTransform * billboards_[i].position_;
  143. Sphere billboardSphere(center, size);
  144. float distance = query.ray_.HitDistance(billboardSphere);
  145. if (distance < query.maxDistance_)
  146. {
  147. // If the code reaches here then we have a hit
  148. RayQueryResult result;
  149. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  150. result.normal_ = -query.ray_.direction_;
  151. result.distance_ = distance;
  152. result.drawable_ = this;
  153. result.node_ = node_;
  154. result.subObject_ = i;
  155. results.Push(result);
  156. }
  157. }
  158. }
  159. void BillboardSet::UpdateBatches(const FrameInfo& frame)
  160. {
  161. // If beginning a new frame, assume no sorting first
  162. if (frame.frameNumber_ != sortFrameNumber_)
  163. {
  164. sortThisFrame_ = false;
  165. sortFrameNumber_ = frame.frameNumber_;
  166. }
  167. Vector3 worldPos = node_->GetWorldPosition();
  168. Vector3 offset = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
  169. // Sort if position relative to camera has changed
  170. if (offset != previousOffset_ || frame.camera_->IsOrthographic() != hasOrthoCamera_)
  171. {
  172. if (sorted_)
  173. sortThisFrame_ = true;
  174. if (faceCameraMode_ == FC_DIRECTION)
  175. bufferDirty_ = true;
  176. hasOrthoCamera_ = frame.camera_->IsOrthographic();
  177. }
  178. // Calculate fixed screen size scale factor for billboards. Will not dirty the buffer unless actually changed
  179. if (fixedScreenSize_)
  180. CalculateFixedScreenSize(frame);
  181. distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center());
  182. // Calculate scaled distance for animation LOD
  183. float scale = GetWorldBoundingBox().Size().DotProduct(DOT_SCALE);
  184. // If there are no billboards, the size becomes zero, and LOD'ed updates no longer happen. Disable LOD in that case
  185. if (scale > M_EPSILON)
  186. lodDistance_ = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  187. else
  188. lodDistance_ = 0.0f;
  189. batches_[0].distance_ = distance_;
  190. batches_[0].numWorldTransforms_ = 2;
  191. // Billboard positioning
  192. transforms_[0] = relative_ ? node_->GetWorldTransform() : Matrix3x4::IDENTITY;
  193. // Billboard rotation
  194. transforms_[1] = Matrix3x4(Vector3::ZERO, faceCameraMode_ != FC_NONE ? frame.camera_->GetFaceCameraRotation(
  195. node_->GetWorldPosition(), node_->GetWorldRotation(), faceCameraMode_, minAngle_) : node_->GetWorldRotation(), Vector3::ONE);
  196. }
  197. void BillboardSet::UpdateGeometry(const FrameInfo& frame)
  198. {
  199. // If rendering from multiple views and fixed screen size is in use, re-update scale factors before each render
  200. if (fixedScreenSize_ && viewCameras_.Size() > 1)
  201. CalculateFixedScreenSize(frame);
  202. // If using camera facing, re-update the rotation for the current view now
  203. if (faceCameraMode_ != FC_NONE)
  204. {
  205. transforms_[1] = Matrix3x4(Vector3::ZERO, frame.camera_->GetFaceCameraRotation(node_->GetWorldPosition(),
  206. node_->GetWorldRotation(), faceCameraMode_, minAngle_), Vector3::ONE);
  207. }
  208. if (bufferSizeDirty_ || indexBuffer_->IsDataLost())
  209. UpdateBufferSize();
  210. if (bufferDirty_ || sortThisFrame_ || vertexBuffer_->IsDataLost())
  211. UpdateVertexBuffer(frame);
  212. }
  213. UpdateGeometryType BillboardSet::GetUpdateGeometryType()
  214. {
  215. // If using camera facing, always need some kind of geometry update, in case the billboard set is rendered from several views
  216. if (bufferDirty_ || bufferSizeDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost() || sortThisFrame_ ||
  217. faceCameraMode_ != FC_NONE || fixedScreenSize_)
  218. return UPDATE_MAIN_THREAD;
  219. else
  220. return UPDATE_NONE;
  221. }
  222. void BillboardSet::SetMaterial(Material* material)
  223. {
  224. batches_[0].material_ = material;
  225. MarkNetworkUpdate();
  226. }
  227. void BillboardSet::SetNumBillboards(unsigned num)
  228. {
  229. // Prevent negative value being assigned from the editor
  230. if (num > M_MAX_INT)
  231. num = 0;
  232. unsigned oldNum = billboards_.Size();
  233. if (num == oldNum)
  234. return;
  235. billboards_.Resize(num);
  236. // Set default values to new billboards
  237. for (unsigned i = oldNum; i < num; ++i)
  238. {
  239. billboards_[i].position_ = Vector3::ZERO;
  240. billboards_[i].size_ = Vector2::ONE;
  241. billboards_[i].uv_ = Rect::POSITIVE;
  242. billboards_[i].color_ = Color(1.0f, 1.0f, 1.0f);
  243. billboards_[i].rotation_ = 0.0f;
  244. billboards_[i].direction_ = Vector3::UP;
  245. billboards_[i].enabled_ = false;
  246. billboards_[i].screenScaleFactor_ = 1.0f;
  247. }
  248. bufferSizeDirty_ = true;
  249. Commit();
  250. }
  251. void BillboardSet::SetRelative(bool enable)
  252. {
  253. relative_ = enable;
  254. Commit();
  255. }
  256. void BillboardSet::SetScaled(bool enable)
  257. {
  258. scaled_ = enable;
  259. Commit();
  260. }
  261. void BillboardSet::SetSorted(bool enable)
  262. {
  263. sorted_ = enable;
  264. Commit();
  265. }
  266. void BillboardSet::SetFixedScreenSize(bool enable)
  267. {
  268. fixedScreenSize_ = enable;
  269. Commit();
  270. }
  271. void BillboardSet::SetFaceCameraMode(FaceCameraMode mode)
  272. {
  273. if ((faceCameraMode_ != FC_DIRECTION && mode == FC_DIRECTION) || (faceCameraMode_ == FC_DIRECTION && mode != FC_DIRECTION))
  274. {
  275. faceCameraMode_ = mode;
  276. if (faceCameraMode_ == FC_DIRECTION)
  277. batches_[0].geometryType_ = GEOM_DIRBILLBOARD;
  278. else
  279. batches_[0].geometryType_ = GEOM_BILLBOARD;
  280. geometryTypeUpdate_ = true;
  281. bufferSizeDirty_ = true;
  282. Commit();
  283. }
  284. else
  285. {
  286. faceCameraMode_ = mode;
  287. MarkNetworkUpdate();
  288. }
  289. }
  290. void BillboardSet::SetMinAngle(float angle)
  291. {
  292. minAngle_ = angle;
  293. MarkNetworkUpdate();
  294. }
  295. void BillboardSet::SetAnimationLodBias(float bias)
  296. {
  297. animationLodBias_ = Max(bias, 0.0f);
  298. MarkNetworkUpdate();
  299. }
  300. void BillboardSet::Commit()
  301. {
  302. MarkPositionsDirty();
  303. MarkNetworkUpdate();
  304. }
  305. Material* BillboardSet::GetMaterial() const
  306. {
  307. return batches_[0].material_;
  308. }
  309. Billboard* BillboardSet::GetBillboard(unsigned index)
  310. {
  311. return index < billboards_.Size() ? &billboards_[index] : nullptr;
  312. }
  313. void BillboardSet::SetMaterialAttr(const ResourceRef& value)
  314. {
  315. auto* cache = GetSubsystem<ResourceCache>();
  316. SetMaterial(cache->GetResource<Material>(value.name_));
  317. }
  318. void BillboardSet::SetBillboardsAttr(const VariantVector& value)
  319. {
  320. unsigned index = 0;
  321. unsigned numBillboards = index < value.Size() ? value[index++].GetUInt() : 0;
  322. SetNumBillboards(numBillboards);
  323. // Dealing with old billboard format
  324. if (value.Size() == billboards_.Size() * 6 + 1)
  325. {
  326. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End() && index < value.Size(); ++i)
  327. {
  328. i->position_ = value[index++].GetVector3();
  329. i->size_ = value[index++].GetVector2();
  330. Vector4 uv = value[index++].GetVector4();
  331. i->uv_ = Rect(uv.x_, uv.y_, uv.z_, uv.w_);
  332. i->color_ = value[index++].GetColor();
  333. i->rotation_ = value[index++].GetFloat();
  334. i->enabled_ = value[index++].GetBool();
  335. }
  336. }
  337. // New billboard format
  338. else
  339. {
  340. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End() && index < value.Size(); ++i)
  341. {
  342. i->position_ = value[index++].GetVector3();
  343. i->size_ = value[index++].GetVector2();
  344. Vector4 uv = value[index++].GetVector4();
  345. i->uv_ = Rect(uv.x_, uv.y_, uv.z_, uv.w_);
  346. i->color_ = value[index++].GetColor();
  347. i->rotation_ = value[index++].GetFloat();
  348. i->direction_ = value[index++].GetVector3();
  349. i->enabled_ = value[index++].GetBool();
  350. }
  351. }
  352. Commit();
  353. }
  354. void BillboardSet::SetNetBillboardsAttr(const PODVector<unsigned char>& value)
  355. {
  356. MemoryBuffer buf(value);
  357. unsigned numBillboards = buf.ReadVLE();
  358. SetNumBillboards(numBillboards);
  359. for (PODVector<Billboard>::Iterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  360. {
  361. i->position_ = buf.ReadVector3();
  362. i->size_ = buf.ReadVector2();
  363. i->uv_ = buf.ReadRect();
  364. i->color_ = buf.ReadColor();
  365. i->rotation_ = buf.ReadFloat();
  366. i->direction_ = buf.ReadVector3();
  367. i->enabled_ = buf.ReadBool();
  368. }
  369. Commit();
  370. }
  371. ResourceRef BillboardSet::GetMaterialAttr() const
  372. {
  373. return GetResourceRef(batches_[0].material_, Material::GetTypeStatic());
  374. }
  375. VariantVector BillboardSet::GetBillboardsAttr() const
  376. {
  377. VariantVector ret;
  378. ret.Reserve(billboards_.Size() * 7 + 1);
  379. ret.Push(billboards_.Size());
  380. for (PODVector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  381. {
  382. ret.Push(i->position_);
  383. ret.Push(i->size_);
  384. ret.Push(Vector4(i->uv_.min_.x_, i->uv_.min_.y_, i->uv_.max_.x_, i->uv_.max_.y_));
  385. ret.Push(i->color_);
  386. ret.Push(i->rotation_);
  387. ret.Push(i->direction_);
  388. ret.Push(i->enabled_);
  389. }
  390. return ret;
  391. }
  392. const PODVector<unsigned char>& BillboardSet::GetNetBillboardsAttr() const
  393. {
  394. attrBuffer_.Clear();
  395. attrBuffer_.WriteVLE(billboards_.Size());
  396. for (PODVector<Billboard>::ConstIterator i = billboards_.Begin(); i != billboards_.End(); ++i)
  397. {
  398. attrBuffer_.WriteVector3(i->position_);
  399. attrBuffer_.WriteVector2(i->size_);
  400. attrBuffer_.WriteRect(i->uv_);
  401. attrBuffer_.WriteColor(i->color_);
  402. attrBuffer_.WriteFloat(i->rotation_);
  403. attrBuffer_.WriteVector3(i->direction_);
  404. attrBuffer_.WriteBool(i->enabled_);
  405. }
  406. return attrBuffer_.GetBuffer();
  407. }
  408. void BillboardSet::OnWorldBoundingBoxUpdate()
  409. {
  410. unsigned enabledBillboards = 0;
  411. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  412. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  413. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  414. BoundingBox worldBox;
  415. for (unsigned i = 0; i < billboards_.Size(); ++i)
  416. {
  417. if (!billboards_[i].enabled_)
  418. continue;
  419. float size = INV_SQRT_TWO * (billboards_[i].size_.x_ * billboardScale.x_ + billboards_[i].size_.y_ * billboardScale.y_);
  420. if (fixedScreenSize_)
  421. size *= billboards_[i].screenScaleFactor_;
  422. Vector3 center = billboardTransform * billboards_[i].position_;
  423. Vector3 edge = Vector3::ONE * size;
  424. worldBox.Merge(BoundingBox(center - edge, center + edge));
  425. ++enabledBillboards;
  426. }
  427. // Always merge the node's own position to ensure particle emitter updates continue when the relative mode is switched
  428. worldBox.Merge(node_->GetWorldPosition());
  429. worldBoundingBox_ = worldBox;
  430. }
  431. void BillboardSet::UpdateBufferSize()
  432. {
  433. unsigned numBillboards = billboards_.Size();
  434. if (vertexBuffer_->GetVertexCount() != numBillboards * 4 || geometryTypeUpdate_)
  435. {
  436. if (faceCameraMode_ == FC_DIRECTION)
  437. {
  438. vertexBuffer_->SetSize(numBillboards * 4, MASK_POSITION | MASK_NORMAL | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2, true);
  439. geometry_->SetVertexBuffer(0, vertexBuffer_);
  440. }
  441. else
  442. {
  443. vertexBuffer_->SetSize(numBillboards * 4, MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1 | MASK_TEXCOORD2, true);
  444. geometry_->SetVertexBuffer(0, vertexBuffer_);
  445. }
  446. geometryTypeUpdate_ = false;
  447. }
  448. bool largeIndices = (numBillboards * 4) >= 65536;
  449. if (indexBuffer_->GetIndexCount() != numBillboards * 6)
  450. indexBuffer_->SetSize(numBillboards * 6, largeIndices);
  451. bufferSizeDirty_ = false;
  452. bufferDirty_ = true;
  453. forceUpdate_ = true;
  454. if (!numBillboards)
  455. return;
  456. // Indices do not change for a given billboard capacity
  457. void* destPtr = indexBuffer_->Lock(0, numBillboards * 6, true);
  458. if (!destPtr)
  459. return;
  460. if (!largeIndices)
  461. {
  462. auto* dest = (unsigned short*)destPtr;
  463. unsigned short vertexIndex = 0;
  464. while (numBillboards--)
  465. {
  466. dest[0] = vertexIndex;
  467. dest[1] = vertexIndex + 1;
  468. dest[2] = vertexIndex + 2;
  469. dest[3] = vertexIndex + 2;
  470. dest[4] = vertexIndex + 3;
  471. dest[5] = vertexIndex;
  472. dest += 6;
  473. vertexIndex += 4;
  474. }
  475. }
  476. else
  477. {
  478. auto* dest = (unsigned*)destPtr;
  479. unsigned vertexIndex = 0;
  480. while (numBillboards--)
  481. {
  482. dest[0] = vertexIndex;
  483. dest[1] = vertexIndex + 1;
  484. dest[2] = vertexIndex + 2;
  485. dest[3] = vertexIndex + 2;
  486. dest[4] = vertexIndex + 3;
  487. dest[5] = vertexIndex;
  488. dest += 6;
  489. vertexIndex += 4;
  490. }
  491. }
  492. indexBuffer_->Unlock();
  493. indexBuffer_->ClearDataLost();
  494. }
  495. void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame)
  496. {
  497. // If using animation LOD, accumulate time and see if it is time to update
  498. if (animationLodBias_ > 0.0f && lodDistance_ > 0.0f)
  499. {
  500. animationLodTimer_ += animationLodBias_ * frame.timeStep_ * ANIMATION_LOD_BASESCALE;
  501. if (animationLodTimer_ >= lodDistance_)
  502. animationLodTimer_ = fmodf(animationLodTimer_, lodDistance_);
  503. else
  504. {
  505. // No LOD if immediate update forced
  506. if (!forceUpdate_)
  507. return;
  508. }
  509. }
  510. unsigned numBillboards = billboards_.Size();
  511. unsigned enabledBillboards = 0;
  512. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  513. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  514. Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE;
  515. // First check number of enabled billboards
  516. for (unsigned i = 0; i < numBillboards; ++i)
  517. {
  518. if (billboards_[i].enabled_)
  519. ++enabledBillboards;
  520. }
  521. sortedBillboards_.Resize(enabledBillboards);
  522. unsigned index = 0;
  523. // Then set initial sort order and distances
  524. for (unsigned i = 0; i < numBillboards; ++i)
  525. {
  526. Billboard& billboard = billboards_[i];
  527. if (billboard.enabled_)
  528. {
  529. sortedBillboards_[index++] = &billboard;
  530. if (sorted_)
  531. billboard.sortDistance_ = frame.camera_->GetDistanceSquared(billboardTransform * billboards_[i].position_);
  532. }
  533. }
  534. batches_[0].geometry_->SetDrawRange(TRIANGLE_LIST, 0, enabledBillboards * 6, false);
  535. bufferDirty_ = false;
  536. forceUpdate_ = false;
  537. if (!enabledBillboards)
  538. return;
  539. if (sorted_)
  540. {
  541. Sort(sortedBillboards_.Begin(), sortedBillboards_.End(), CompareBillboards);
  542. Vector3 worldPos = node_->GetWorldPosition();
  543. // Store the "last sorted position" now
  544. previousOffset_ = (worldPos - frame.camera_->GetNode()->GetWorldPosition());
  545. }
  546. auto* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, true);
  547. if (!dest)
  548. return;
  549. if (faceCameraMode_ != FC_DIRECTION)
  550. {
  551. for (unsigned i = 0; i < enabledBillboards; ++i)
  552. {
  553. Billboard& billboard = *sortedBillboards_[i];
  554. Vector2 size(billboard.size_.x_ * billboardScale.x_, billboard.size_.y_ * billboardScale.y_);
  555. unsigned color = billboard.color_.ToUInt();
  556. if (fixedScreenSize_)
  557. size *= billboard.screenScaleFactor_;
  558. float rotationMatrix[2][2];
  559. SinCos(billboard.rotation_, rotationMatrix[0][1], rotationMatrix[0][0]);
  560. rotationMatrix[1][0] = -rotationMatrix[0][1];
  561. rotationMatrix[1][1] = rotationMatrix[0][0];
  562. dest[0] = billboard.position_.x_;
  563. dest[1] = billboard.position_.y_;
  564. dest[2] = billboard.position_.z_;
  565. ((unsigned&)dest[3]) = color;
  566. dest[4] = billboard.uv_.min_.x_;
  567. dest[5] = billboard.uv_.min_.y_;
  568. dest[6] = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  569. dest[7] = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  570. dest[8] = billboard.position_.x_;
  571. dest[9] = billboard.position_.y_;
  572. dest[10] = billboard.position_.z_;
  573. ((unsigned&)dest[11]) = color;
  574. dest[12] = billboard.uv_.max_.x_;
  575. dest[13] = billboard.uv_.min_.y_;
  576. dest[14] = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1];
  577. dest[15] = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1];
  578. dest[16] = billboard.position_.x_;
  579. dest[17] = billboard.position_.y_;
  580. dest[18] = billboard.position_.z_;
  581. ((unsigned&)dest[19]) = color;
  582. dest[20] = billboard.uv_.max_.x_;
  583. dest[21] = billboard.uv_.max_.y_;
  584. dest[22] = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  585. dest[23] = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  586. dest[24] = billboard.position_.x_;
  587. dest[25] = billboard.position_.y_;
  588. dest[26] = billboard.position_.z_;
  589. ((unsigned&)dest[27]) = color;
  590. dest[28] = billboard.uv_.min_.x_;
  591. dest[29] = billboard.uv_.max_.y_;
  592. dest[30] = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1];
  593. dest[31] = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1];
  594. dest += 32;
  595. }
  596. }
  597. else
  598. {
  599. for (unsigned i = 0; i < enabledBillboards; ++i)
  600. {
  601. Billboard& billboard = *sortedBillboards_[i];
  602. Vector2 size(billboard.size_.x_ * billboardScale.x_, billboard.size_.y_ * billboardScale.y_);
  603. unsigned color = billboard.color_.ToUInt();
  604. if (fixedScreenSize_)
  605. size *= billboard.screenScaleFactor_;
  606. float rot2D[2][2];
  607. SinCos(billboard.rotation_, rot2D[0][1], rot2D[0][0]);
  608. rot2D[1][0] = -rot2D[0][1];
  609. rot2D[1][1] = rot2D[0][0];
  610. dest[0] = billboard.position_.x_;
  611. dest[1] = billboard.position_.y_;
  612. dest[2] = billboard.position_.z_;
  613. dest[3] = billboard.direction_.x_;
  614. dest[4] = billboard.direction_.y_;
  615. dest[5] = billboard.direction_.z_;
  616. ((unsigned&)dest[6]) = color;
  617. dest[7] = billboard.uv_.min_.x_;
  618. dest[8] = billboard.uv_.min_.y_;
  619. dest[9] = -size.x_ * rot2D[0][0] + size.y_ * rot2D[0][1];
  620. dest[10] = -size.x_ * rot2D[1][0] + size.y_ * rot2D[1][1];
  621. dest[11] = billboard.position_.x_;
  622. dest[12] = billboard.position_.y_;
  623. dest[13] = billboard.position_.z_;
  624. dest[14] = billboard.direction_.x_;
  625. dest[15] = billboard.direction_.y_;
  626. dest[16] = billboard.direction_.z_;
  627. ((unsigned&)dest[17]) = color;
  628. dest[18] = billboard.uv_.max_.x_;
  629. dest[19] = billboard.uv_.min_.y_;
  630. dest[20] = size.x_ * rot2D[0][0] + size.y_ * rot2D[0][1];
  631. dest[21] = size.x_ * rot2D[1][0] + size.y_ * rot2D[1][1];
  632. dest[22] = billboard.position_.x_;
  633. dest[23] = billboard.position_.y_;
  634. dest[24] = billboard.position_.z_;
  635. dest[25] = billboard.direction_.x_;
  636. dest[26] = billboard.direction_.y_;
  637. dest[27] = billboard.direction_.z_;
  638. ((unsigned&)dest[28]) = color;
  639. dest[29] = billboard.uv_.max_.x_;
  640. dest[30] = billboard.uv_.max_.y_;
  641. dest[31] = size.x_ * rot2D[0][0] - size.y_ * rot2D[0][1];
  642. dest[32] = size.x_ * rot2D[1][0] - size.y_ * rot2D[1][1];
  643. dest[33] = billboard.position_.x_;
  644. dest[34] = billboard.position_.y_;
  645. dest[35] = billboard.position_.z_;
  646. dest[36] = billboard.direction_.x_;
  647. dest[37] = billboard.direction_.y_;
  648. dest[38] = billboard.direction_.z_;
  649. ((unsigned&)dest[39]) = color;
  650. dest[40] = billboard.uv_.min_.x_;
  651. dest[41] = billboard.uv_.max_.y_;
  652. dest[42] = -size.x_ * rot2D[0][0] - size.y_ * rot2D[0][1];
  653. dest[43] = -size.x_ * rot2D[1][0] - size.y_ * rot2D[1][1];
  654. dest += 44;
  655. }
  656. }
  657. vertexBuffer_->Unlock();
  658. vertexBuffer_->ClearDataLost();
  659. }
  660. void BillboardSet::MarkPositionsDirty()
  661. {
  662. Drawable::OnMarkedDirty(node_);
  663. bufferDirty_ = true;
  664. }
  665. void BillboardSet::CalculateFixedScreenSize(const FrameInfo& frame)
  666. {
  667. float invViewHeight = 1.0f / frame.viewSize_.y_;
  668. float halfViewWorldSize = frame.camera_->GetHalfViewSize();
  669. bool scaleFactorChanged = false;
  670. if (!frame.camera_->IsOrthographic())
  671. {
  672. Matrix4 viewProj(frame.camera_->GetProjection() * frame.camera_->GetView());
  673. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  674. Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY;
  675. for (unsigned i = 0; i < billboards_.Size(); ++i)
  676. {
  677. Vector4 projPos(viewProj * Vector4(billboardTransform * billboards_[i].position_, 1.0f));
  678. float newScaleFactor = invViewHeight * halfViewWorldSize * projPos.w_;
  679. if (newScaleFactor != billboards_[i].screenScaleFactor_)
  680. {
  681. billboards_[i].screenScaleFactor_ = newScaleFactor;
  682. scaleFactorChanged = true;
  683. }
  684. }
  685. }
  686. else
  687. {
  688. for (unsigned i = 0; i < billboards_.Size(); ++i)
  689. {
  690. float newScaleFactor = invViewHeight * halfViewWorldSize;
  691. if (newScaleFactor != billboards_[i].screenScaleFactor_)
  692. {
  693. billboards_[i].screenScaleFactor_ = newScaleFactor;
  694. scaleFactorChanged = true;
  695. }
  696. }
  697. }
  698. if (scaleFactorChanged)
  699. {
  700. bufferDirty_ = true;
  701. forceUpdate_ = true;
  702. worldBoundingBoxDirty_ = true;
  703. }
  704. }
  705. }