Хрупкие объекты

Материал из CryWiki Russia

Версия от 15:25, 30 марта 2013; Sodiet (Обсуждение | вклад)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск
Эта страница страница помечена как находящиеся в процессе перевода.


Содержание

Хрупкие объекты

Хрупкие объекты содержат отдельные части соединённые в одной модели сочленениями. Каждая часть может быть отделена физической силой (пулями, взаимодействием с игроком, взрывами) превосходящей ограничения сочленения. В основном, хрупкие объекты размещаются в Sandbox как браши (кисти). Наилучшим примером хрупких объектов являются дорожные знаки или деревянные заборы.

Файл-пример

Файл-пример: Хрупкие объекты

Основные настройки в 3D-приложении

  • Объекты должны иметь несколько узлов и каждый должен иметь свою собственную физику.
  • Узлы соединены сочленениями (каждое сочленение может быть соединено с 2 частями).
  • Порядок наименования сочленений: $joint01, $joint02, и т. д.
  • Сочленения в 3D-приложении представляют собой вспомогательные объекты (дамми, пустышки). Они должны пересекать физическую прокси одного или максимум двух геометрических объектов.
  • Z-ориентация точки опоры сочленения должна быть направлена наверх (см. раздел «Отладка»).
  • Помимо этого, можно явно указать название части в названии сочленения используя такой формат: $joint1_part1_part2. Это полезно в сложных узлах, где геометрия пересекает более чем две части.
  • Когда сочленение объекта пересекает только один узел, создаёт сочленение между объектом и миром.
  • Размер дамми-объекта никак не влияет на силу воздействия.
  • Это, однако, используется при повторном приклеплении сочленений к хрупким частями, если некая геометрия также имеет процедурные разрушения (а именно: когда часть процедурно разрушена, все сочленения, которые прикреплены к ней, проверяются на пересечение с вновь образованными частями, и повторно прикрепляет к ним, если это необходимо).
  • Сила и масса сочленения отдельно определяются в свойствах узла (в каждом 3D-приложении называются по-разному; в 3ds Max: Objects Properties [Свойства объекта]).
  • Определённые ограничения сочленения относятся к нормалям сочленения, представленным вспомогательным узлов оси Z. Для сочленений, в которых имена частей определены явно, необходимо соблюдать осторожность с точками нормалей в перво части (иначе ограничения push и pull сменять значения).
  • При экспорте отключите «Merge All Nodes».
  • Объекты размещаются как браши или геометрические сущности (Brush\GeomEntity).
  • пример размещения пустышки (Dummy):

PrebrokenObject dummyplacement.jpg

  • пример свойств сочленения (joint):

PrebrokenObject objectproperties.jpg

Каждый раз, когда внешние силы (коллизия других объектов или попадание пули) воздействуют на объект, система просчитывает внутренние силы, удерживающие части объекта вместе, и если какие-то силы превышают этот порог, то соответствующие сочленения удаляются. Затем связанные части через удаление сочленений заново рассчитанные и изолированные переносятся к новой сущности.

Свойства узлов

Узлам необходимы свойства присоединения (зависят от программного обеспечения) для корректной работы в движке.

entity (свойства рендера)
Если настройки рендера геометрии включают в себя «entity», то объект не исчезнет после отсоединения от главного объекта.
box (свойства рендера)
Если настройки рендера геометрии включают в себя «box», то движок будет использовать упрощенный куб (основанный на ограничивающем кубе физического прокси объекта) как коллизию геометрии. Это помогает увеличить скорость просчета физики.
mass=VALUE (свойства рендера)
Масса определяет вес объекта, основываясь на том, что значение параметра, равное нулю, делает объект неподвижным. Это используется, к примеру, при создании основания дома или одинокого столба, который должен оставаться на определенном месте. Когда используются кисти ("brush") или Геометрические Сущности ("Geom Entities"), масса остается постоянной. При использовании обычных Сущностей ("Entities"), все части массово масштабируются так, что их общая масса равна массе, указанной в параметрах Сущности.

Предупреждение:
Вы должны указать массу или плотность, дабы быть уверенным в корректно симуляции физики.

density=VALUE
Движок автоматически рассчитывает массу для объекта, основываясь на плотности и ограничивающем кубе. Значение может использоваться как альтернатива параметру "Масса".
limit=VALUE (Свойство шарнира у объекта)
Лимит - это основное значение для нескольких различных видов сил, приложенных к соединению. Содержит комбинации значений, приведенных далее. Внимание! Это значение необходимо задать, иначе симуляция физики будет работать некорректно. Пример значений из "Crysis": 100-500 - можно разрушить снарядом; 10000 - разрушается при столкновении с движущейся машиной или большим взрывом.

Следующие значение являются дополнительными и нужны для уточнения настроек параметра "Лимит".

bend=VALUE (Свойство шарнира у объекта) 
Максимальный крутящий момент вокруг оси перпендикулярно нормали.
twist=VALUE (Свойство шарнира у объекта)
Максимальный крутящий момент вокруг нормали.
pull=VALUE (Свойство шарнира у объекта)
Максимальная сила, применимая к шарниру первого объекта против нормали шарнира (части "стягиваются", как реакция на натяжение внешними силами).
push=VALUE (Свойство шарнира у объекта)
Максимальная сила, применимая к шарниру первого объекта (то есть первый, чье имя первое в списке шарниров, или оно не указано, шарнир объекта вращается вокруг оси Z) вдоль нормали шарнира; нормаль шарнира - ось Z шарнира. Части "пружинят" (как реакция на внешние силы, сжимающие части). Эта ось должна быть направлена внутрь первого объекта.
shift=VALU (Свойство шарнира у объекта)
Максимальная сила в направлении, перпендикулярном нормали.

Дополнение:
Шарниры также поддерживают не полностью жесткие ограничители ("non-fully-figid constraints"). Полностью жесткие ограничители станут динамическими, если их объект скручивают, после превышения лимита объект "ломается" и параметр "constrant_limit" приравнивается к нулю.

Broken «bends» will become «socket» constraints, and «twists» will become hinges. The newly created dynamic constraint will inherit pull and shift limits from the joint. The constraint’s frame will be that of the joint’s helper in max. In order to preserve the meaning of «twisting», however, the axes will be swapped (z of the joint’s helper will become the constraint’s x — since both represent the «twising» axis, x will become y, and y wil become z). Thus, for hinges, z asis of the helper should be directed along the desired hinge direction. For socket’s, z axis should be the axis the attached part «bends around».

Here is the list of related properties:

constraint_limit=VALUE (Joint object property)
Force limit for the newly created constraint, is checked when the constraint hits a rotation limit and is being pushed further
constraint_minang=VALUE (Joint object property)
constraint_maxang=VALUE (Joint object property)
Rotation limits for the constraint (the interpretation is the same as in standalone constraints). The default is no limits
constraint_damping=VALUE (Joint object property)
Angular damping (default 0)
constraint_collides=VALUE (Joint object property)
Whether the constraint parts will ignore collisions with each other (default 1)

For example, to quickly create an unbreakable hinge constraint, one should put this into the joint’s properties: twist = 0 (the constraint will created at the first activation, regardless of force) constraint_limit = 1E20 (just something big enough) Примечание that the general «limit = xx» is not required, since we want the limits other than twist to remain unbreakable. Also note that the nodes that have dynamic constraints between them should always be physicalized as entities (not particles).

Dissolving into particlespieces

Jointed Objects can be set up to break in smaller pieces when being detached from the joint. i.e. a wooden sheet breaks into several planks. The object properties must contain the information about the pieces used. i.e. «pieces=$blah1», «pieces=$rock1». Several objects can share the same name, but it is also possible to set up the pieces with different names, i.e. «pieces=$blah1,$blah2». Pieces need to be linked to the object they should replace later on. NOTE: make sure the names of the objects you want to use as pieces are in lower case only i.e. $debris or $piece1. Debris would not work.

WARNING Be aware that the search function in the code also returns nodes with only partially matching strings. If you have problems with pieces spawning out of nowhere or existing nodes being cloned for no reason, look into the name strings and change them to avoid this issue.

If you don’t specify anything in the piece properties, they will be spawned as particles, which means they will have no collision and will disappear after a few seconds. If you want the pieces to behave like actual physicalized objects, you have to add «entity» into their properties box.

  • Sample setup:

PrebrokenObject pieces.jpg

Practical examples of how pieces can be used:

Optimization

If you create a dummy object with a nodraw material (like a simple cube) and spawn it as a piece, the jointed object will simply disappear once the joint breaks — it will be replaced by an invisible object. This can be helpful since the piece that is broken off will not fall down and interact with the remaining pieces, potentially causing problems, and it is also beneficial performance-wise. Once the original object is seperated from its joint, no further physics calculations will be necessary.

Adding dynamic detail

Pieces replace their original object once this object is «broken off» (seperated from it’s joint), so you can take the original object and cut it up into smaller pieces. An example of this is the huts in crysis, most roof panels have two sub-pieces that spawn once the panel breaks off. This results in more detailed breaking and smaller debris. Don’t forget to add «entity» and a realistic mass to the piece properties, and make sure the piece is physicalized, or else the pieces will fall through the ground and/or disappear after a few seconds. (in case they are only small «fluff» pieces, this might actually be intended)

Adding static detail

You can also spawn small debris pieces, that, instead of falling down, stay where they appear (for example steel cables sticking out of a concrete wall). To do this, you have to add the following lines to the properties of the piece:

entity
mass=0
density=0

Entity because you want the object to stay where it is once it is spawned, and because you want it to be physicalized. The object needs to be physicalized (i.e. contain polygons with a physicalized material) in order for this to work. Mass and density need to be 0 to assign the objects infinite mass, which results in the object staying where it spawns and not reacting to force. If it wasn’t 0, it would fall down upon spawning.

Level of detail settings

LodCreation per object can easily be added by naming them $lod1; $lod2, $lod3… and linking them to the relevant subobjects. In order to make differentiation easier, a postfix can be added; i.e. «$lod1_wooden plank»

Occlusion Proxy

An OcclusionProxy can be added by naming it $occlusion and linking it to the relevant jointed object; like a big sheet of metal on a metal fence or a wooden wall on a hut. Occlusion proxy is allowed to have open edges and need to be as low as possible (something around 2-10 polys).

Instancing within breakable objects

Instancing objects is used to optimize render time by reducing drawcalls and memory consumption. The engine automatically detects identical geometry elements within the exported objects. There is no special setup needed to take advantage of this feature. UVs and relative point position to the pivot need to be identical in objects in order to qualify them for instancing.

Linking Objects to simplify export

Linked objects don’t need to be exported, just the Root node needs to be added to the exporter list. All child nodes will automatically be exported. The name and pivot will be derived from the root joint.

  • Example of linking objects and joints for simpler export:

PrebrokenObject NamingAndHierarchy.jpg

Setup in Sandbox

Add the object as a brush or a GeomEntity. In case of a brush, the engine will detext automatically that the object is breakable. For multiplayer where breaking objects has a massive impact on the data transfer, breakability is automatically disabled (might change later)

Debugging

  • p_debug_joints 1 shows the default debug mode for joints (see picture below); p_draw_helpers needs to be activated
  • CAUTION Never scale a joint If you need a new size, create a new joint. the scaling value will be passed on to the engine and causes wrong results in the simulation.
  • The «spikes» on the joint objects show the orientation. For limits to properly reflect their names (i.e. pull, twist, etc), the spikes must be directed along the «natural» joints axes. However, it’s also possible to keep them always pointing up, for consistency.
  • The blue colored numbers show the mass of the single pieces. Примечание the «0.00kg» this is the mass of the top node — in this case a dummy.
  • Joints linked to the world are displayed red.
  • When a force is applied to a joint, the direction is shown (in this case shift and bend), together with the strength and the limit of the particular joint. Green text represents an impact with an impulse much lower then the joint limit. Yellow represents values closer to the joint limit. Red represents values which were higher than the limit — in this case the joint is broken.
  • NOTE: the debug mode is handy to see how the impulse of weapons react with the breakable object. set the general limit first and then fine tune the specific limits by setting them explicitly for shift, bend…
  • Example of debug display:

PrebrokenObject sign example.jpg