BillboardSet.cpp 29 KB

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