Coverage Report

Created: 2026-11-20 06:23

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ogre/OgreMain/include/OgreSkeleton.h
Line
Count
Source
1
/*
2
-----------------------------------------------------------------------------
3
This source file is part of OGRE
4
    (Object-oriented Graphics Rendering Engine)
5
For the latest info, see http://www.ogre3d.org/
6
7
Copyright (c) 2000-2014 Torus Knot Software Ltd
8
9
Permission is hereby granted, free of charge, to any person obtaining a copy
10
of this software and associated documentation files (the "Software"), to deal
11
in the Software without restriction, including without limitation the rights
12
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
copies of the Software, and to permit persons to whom the Software is
14
furnished to do so, subject to the following conditions:
15
16
The above copyright notice and this permission notice shall be included in
17
all copies or substantial portions of the Software.
18
19
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25
THE SOFTWARE.
26
-----------------------------------------------------------------------------
27
*/
28
29
#ifndef __Skeleton_H__
30
#define __Skeleton_H__
31
32
#include "OgrePrerequisites.h"
33
#include "OgreResource.h"
34
#include "OgreStringVector.h"
35
#include "OgreAnimation.h"
36
#include "OgreHeaderPrefix.h"
37
#include "OgreSharedPtr.h"
38
39
namespace Ogre {
40
    /** \addtogroup Core
41
    *  @{
42
    */
43
    /** \addtogroup Animation
44
    *  @{
45
    */
46
47
    /**  */
48
    enum SkeletonAnimationBlendMode : uint8 {
49
        /// Animations are applied by calculating a weighted average of all animations
50
        ANIMBLEND_AVERAGE = 0,
51
        /// Animations are applied by calculating a weighted cumulative total
52
        ANIMBLEND_CUMULATIVE = 1
53
    };
54
    
55
    /// Link to another skeleton to share animations
56
    struct LinkedSkeletonAnimationSource
57
    {
58
        String skeletonName;
59
        SkeletonPtr pSkeleton;
60
        Real scale;
61
        LinkedSkeletonAnimationSource(const String& skelName, Real scl)
62
0
            : skeletonName(skelName), scale(scl) {}
63
            LinkedSkeletonAnimationSource(const String& skelName, Real scl,
64
                const SkeletonPtr& skelPtr)
65
0
                : skeletonName(skelName), pSkeleton(skelPtr), scale(scl) {}
66
    };
67
68
    /** A collection of Bone objects used to animate a skinned mesh.
69
70
        Skeletal animation works by having a collection of 'bones' which are 
71
        actually just joints with a position and orientation, arranged in a tree structure.
72
        For example, the wrist joint is a child of the elbow joint, which in turn is a
73
        child of the shoulder joint. Rotating the shoulder automatically moves the elbow
74
        and wrist as well due to this hierarchy.
75
    @par
76
        So how does this animate a mesh? Well every vertex in a mesh is assigned to one or more
77
        bones which affects it's position when the bone is moved. If a vertex is assigned to 
78
        more than one bone, then weights must be assigned to determine how much each bone affects
79
        the vertex (actually a weight of 1.0 is used for single bone assignments). 
80
        Weighted vertex assignments are especially useful around the joints themselves
81
        to avoid 'pinching' of the mesh in this region. 
82
    @par
83
        Therefore by moving the skeleton using preset animations, we can animate the mesh. The
84
        advantage of using skeletal animation is that you store less animation data, especially
85
        as vertex counts increase. In addition, you are able to blend multiple animations together
86
        (e.g. walking and looking around, running and shooting) and provide smooth transitions
87
        between animations without incurring as much of an overhead as would be involved if you
88
        did this on the core vertex data.
89
    @par
90
        Skeleton definitions are loaded from datafiles, namely the .skeleton file format. They
91
        are loaded on demand, especially when referenced by a Mesh.
92
    */
93
    class _OgreExport Skeleton : public Resource, public AnimationContainer
94
    {
95
        friend class SkeletonInstance;
96
    private:
97
        /// Internal constructor for use by SkeletonInstance only
98
        Skeleton(const String& name, ResourceHandle handle, const String& group);
99
100
    public:
101
        /** Constructor, don't call directly, use SkeletonManager.
102
103
            On creation, a Skeleton has a no bones, you should create them and link
104
            them together appropriately. 
105
        */
106
        Skeleton(ResourceManager* creator, const String& name, ResourceHandle handle,
107
            const String& group, bool isManual = false, ManualResourceLoader* loader = 0);
108
        virtual ~Skeleton();
109
110
111
        /** Creates a brand new Bone owned by this Skeleton. 
112
113
            This method creates an unattached new Bone for this skeleton.
114
            Unless this is to be a root bone (there may be more than one of 
115
            these), you must attach it to another Bone in the skeleton using addChild for it to be any use.
116
            For this reason you will likely be better off creating child bones using the
117
            Bone::createChild method instead, once you have created the root bone. 
118
        @par
119
            Note that this method automatically generates a handle for the bone, which you
120
            can retrieve using Bone::getHandle. If you wish the new Bone to have a specific
121
            handle, use the alternate form of this method which takes a handle as a parameter,
122
            although you should note the restrictions.
123
        */
124
        virtual Bone* createBone(void);
125
126
        /** Creates a brand new Bone owned by this Skeleton. 
127
128
            This method creates an unattached new Bone for this skeleton and assigns it a 
129
            specific handle. Unless this is to be a root bone (there may be more than one of 
130
            these), you must attach it to another Bone in the skeleton using addChild for it to be any use. 
131
            For this reason you will likely be better off creating child bones using the
132
            Bone::createChild method instead, once you have created a root bone. 
133
        @param handle The handle to give to this new bone - must be unique within this skeleton. 
134
            You should also ensure that all bone handles are eventually contiguous (this is to simplify
135
            their compilation into an indexed array of transformation matrices). For this reason
136
            it is advised that you use the simpler createBone method which automatically assigns a
137
            sequential handle starting from 0.
138
        */
139
        virtual Bone* createBone(unsigned short handle);
140
141
        /** Creates a brand new Bone owned by this Skeleton. 
142
143
            This method creates an unattached new Bone for this skeleton and assigns it a 
144
            specific name.Unless this is to be a root bone (there may be more than one of 
145
            these), you must attach it to another Bone in the skeleton using addChild for it to be any use.
146
            For this reason you will likely be better off creating child bones using the
147
            Bone::createChild method instead, once you have created the root bone. 
148
        @param name The name to give to this new bone - must be unique within this skeleton. 
149
            Note that the way OGRE looks up bones is via a numeric handle, so if you name a
150
            Bone this way it will be given an automatic sequential handle. The name is just
151
            for your convenience, although it is recommended that you only use the handle to 
152
            retrieve the bone in performance-critical code.
153
        */
154
        virtual Bone* createBone(const String& name);
155
156
        /** Creates a brand new Bone owned by this Skeleton. 
157
158
            This method creates an unattached new Bone for this skeleton and assigns it a 
159
            specific name and handle. Unless this is to be a root bone (there may be more than one of 
160
            these), you must attach it to another Bone in the skeleton using addChild for it to be any use.
161
            For this reason you will likely be better off creating child bones using the
162
            Bone::createChild method instead, once you have created the root bone. 
163
        @param name The name to give to this new bone - must be unique within this skeleton. 
164
        @param handle The handle to give to this new bone - must be unique within this skeleton. 
165
        */
166
        virtual Bone* createBone(const String& name, unsigned short handle);
167
168
        /** Returns the number of bones in this skeleton. */
169
0
        unsigned short getNumBones(void) const { return (unsigned short)mBoneList.size(); }
170
171
        typedef std::vector<Bone*> BoneList;
172
        typedef VectorIterator<BoneList> BoneIterator;
173
        /// Get an iterator over the root bones in the skeleton, ie those with no parents
174
        /// @deprecated use Skeleton::getRootBones
175
        OGRE_DEPRECATED virtual BoneIterator getRootBoneIterator(void);
176
177
        /** Get the root bones in the skeleton, ie those with no parents
178
179
            The system derives the root bone the first time you ask for it. The root bone is the
180
            only bone in the skeleton which has no parent. The system locates it by taking the
181
            first bone in the list and going up the bone tree until there are no more parents,
182
            and saves this top bone as the root. If you are building the skeleton manually using
183
            createBone then you must ensure there is only one bone which is not a child of
184
            another bone, otherwise your skeleton will not work properly. If you use createBone
185
            only once, and then use Bone::createChild from then on, then inherently the first
186
            bone you create will by default be the root.
187
        */
188
        const BoneList& getRootBones() const;
189
190
        /// Get an iterator over all the bones in the skeleton
191
        /// @deprecated use getBones()
192
        OGRE_DEPRECATED virtual BoneIterator getBoneIterator(void);
193
        /// Get all the bones in the skeleton
194
0
        const BoneList& getBones() const {
195
0
            return mBoneList;
196
0
        }
197
198
        /** Gets a bone by it's handle. */
199
        Bone* getBone(unsigned short handle) const
200
0
        {
201
0
            assert(handle < mBoneList.size() && "Index out of bounds");
202
0
            return mBoneList[handle];
203
0
        }
204
205
        /** Gets a bone by it's name. */
206
        Bone* getBone(const String& name) const;
207
208
        /** Returns whether this skeleton contains the named bone. */
209
        bool hasBone(const String& name) const;
210
211
        /** Sets the current position / orientation to be the 'binding pose' i.e. the layout in which 
212
            bones were originally bound to a mesh.
213
        */
214
        void setBindingPose(void);
215
216
        /** Resets the position and orientation of all bones in this skeleton to their original binding position.
217
218
            A skeleton is bound to a mesh in a binding pose. Bone positions are then modified from this
219
            position during animation. This method returns all the bones to their original position and
220
            orientation.
221
        @param resetManualBones If set to true, causes the state of manual bones to be reset
222
            too, which is normally not done to allow the manual state to persist even 
223
            when keyframe animation is applied.
224
        */
225
        void reset(bool resetManualBones = false);
226
227
        /** Creates a new Animation object for animating this skeleton. 
228
        @copydetails AnimationContainer::createAnimation
229
        */
230
        Animation* createAnimation(const String& name, Real length) override;
231
232
        /** Returns the named Animation object. 
233
234
            Will pick up animations in linked skeletons 
235
            (@see addLinkedSkeletonAnimationSource). 
236
        @param name The name of the animation
237
        @param linker Optional pointer to a pointer to the linked skeleton animation
238
            where this is coming from.
239
        */
240
        virtual Animation* getAnimation(const String& name, 
241
            const LinkedSkeletonAnimationSource** linker) const;
242
243
        /** Returns the named Animation object.
244
245
             Will pick up animations in linked skeletons 
246
             (@see addLinkedSkeletonAnimationSource). 
247
         @param name The name of the animation
248
         */
249
        Animation* getAnimation(const String& name) const override;
250
251
        /// Internal accessor for animations (returns null if animation does not exist)
252
        virtual Animation* _getAnimationImpl(const String& name, 
253
            const LinkedSkeletonAnimationSource** linker = 0) const;
254
255
256
        bool hasAnimation(const String& name) const override;
257
        void removeAnimation(const String& name) override;
258
259
        /** Changes the state of the skeleton to reflect the application of the passed in collection of animations.
260
261
            Animating a skeleton involves both interpolating between keyframes of a specific animation,
262
            and blending between the animations themselves. Calling this method sets the state of
263
            the skeleton so that it reflects the combination of all the passed in animations, at the
264
            time index specified for each, using the weights specified. Note that the weights between 
265
            animations do not have to sum to 1.0, because some animations may affect only subsets
266
            of the skeleton. If the weights exceed 1.0 for the same area of the skeleton, the 
267
            movement will just be exaggerated.
268
        */
269
        virtual void setAnimationState(const AnimationStateSet& animSet);
270
271
272
        /** Initialise an animation set suitable for use with this skeleton. 
273
274
            Only recommended for use inside the engine, not by applications.
275
        */
276
        virtual void _initAnimationState(AnimationStateSet* animSet);
277
278
        /** Refresh an animation set suitable for use with this skeleton. 
279
280
            Only recommended for use inside the engine, not by applications.
281
        */
282
        virtual void _refreshAnimationState(AnimationStateSet* animSet);
283
284
        /** Populates the passed in array with the bone matrices based on the current position.
285
286
            Internal use only. The array pointed to by the passed in pointer must
287
            be at least as large as the number of bones.
288
            Assumes animation has already been updated.
289
        */
290
        void _getBoneMatrices(Affine3* pMatrices);
291
292
        unsigned short getNumAnimations(void) const override;
293
294
        /** Gets a single animation by index. 
295
296
            Will NOT pick up animations in linked skeletons 
297
            (@see addLinkedSkeletonAnimationSource).
298
        */
299
        Animation* getAnimation(unsigned short index) const override;
300
301
302
        /** Gets the animation blending mode which this skeleton will use. */
303
0
        SkeletonAnimationBlendMode getBlendMode() const { return mBlendState; }
304
        /** Sets the animation blending mode this skeleton will use. */
305
0
        void setBlendMode(SkeletonAnimationBlendMode state) { mBlendState = state; }
306
307
        /// Updates all the derived transforms in the skeleton
308
        virtual void _updateTransforms(void);
309
310
        /** Optimise all of this skeleton's animations.
311
        @see Animation::optimise
312
        @param
313
            preservingIdentityNodeTracks If true, don't destroy identity node tracks.
314
        */
315
        virtual void optimiseAllAnimations(bool preservingIdentityNodeTracks = false);
316
317
        /** Allows you to use the animations from another Skeleton object to animate
318
            this skeleton.
319
320
            If you have skeletons of identical structure (that means identically
321
            named bones with identical handles, and with the same hierarchy), but
322
            slightly different proportions or binding poses, you can re-use animations
323
            from one in the other. Because animations are actually stored as
324
            changes to bones from their bind positions, it's possible to use the
325
            same animation data for different skeletons, provided the skeletal
326
            structure matches and the 'deltas' stored in the keyframes apply
327
            equally well to the other skeletons bind position (so they must be
328
            roughly similar, but don't have to be identical). You can use the 
329
            'scale' option to adjust the translation and scale keyframes where
330
            there are large differences in size between the skeletons.
331
        @note
332
            This method takes a skeleton name, rather than a more specific 
333
            animation name, for two reasons; firstly it allows some validation 
334
            of compatibility of skeletal structure, and secondly skeletons are
335
            the unit of loading. Linking a skeleton to another in this way means
336
            that the linkee will be prevented from being destroyed until the 
337
            linker is destroyed.
338
339
            You cannot set up cyclic relationships, e.g. SkeletonA uses SkeletonB's
340
            animations, and SkeletonB uses SkeletonA's animations. This is because
341
            it would set up a circular dependency which would prevent proper 
342
            unloading - make one of the skeletons the 'master' in this case.
343
        @param skelName Name of the skeleton to link animations from. This 
344
            skeleton will be loaded immediately if this skeleton is already 
345
            loaded, otherwise it will be loaded when this skeleton is.
346
        @param scale A scale factor to apply to translation and scaling elements
347
            of the keyframes in the other skeleton when applying the animations
348
            to this one. Compensates for skeleton size differences.
349
        */
350
        virtual void addLinkedSkeletonAnimationSource(const String& skelName, 
351
            Real scale = 1.0f);
352
        /// Remove all links to other skeletons for the purposes of sharing animation
353
        virtual void removeAllLinkedSkeletonAnimationSources(void);
354
        
355
        typedef std::vector<LinkedSkeletonAnimationSource> 
356
            LinkedSkeletonAnimSourceList;
357
        typedef ConstVectorIterator<LinkedSkeletonAnimSourceList> 
358
            LinkedSkeletonAnimSourceIterator;
359
        /// Get the linked skeletons used as animation sources
360
        virtual const LinkedSkeletonAnimSourceList& getLinkedSkeletonAnimationSources() const
361
0
        {
362
0
            return mLinkedSkeletonAnimSourceList;
363
0
        }
364
365
        /// @deprecated use getLinkedSkeletonAnimationSources
366
        OGRE_DEPRECATED virtual LinkedSkeletonAnimSourceIterator
367
            getLinkedSkeletonAnimationSourceIterator(void) const;
368
369
        /// Internal method for marking the manual bones as dirty
370
        virtual void _notifyManualBonesDirty(void);
371
        /// Internal method for notifying that a bone is manual
372
        virtual void _notifyManualBoneStateChange(Bone* bone);
373
374
        /// Have manual bones been modified since the skeleton was last updated?
375
0
        virtual bool getManualBonesDirty(void) const { return mManualBonesDirty; }
376
        /// Are there any manually controlled bones?
377
0
        virtual bool hasManualBones(void) const { return !mManualBones.empty(); }
378
379
        /// Map to translate bone handle from one skeleton to another skeleton.
380
        typedef std::vector<ushort> BoneHandleMap;
381
382
        /** Merge animations from another Skeleton object into this skeleton.
383
384
            This function allow merge two structures compatible skeletons. The
385
            'compatible' here means identically bones will have same hierarchy,
386
            but skeletons are not necessary to have same number of bones (if
387
            number bones of source skeleton's more than this skeleton, they will
388
            copied as is, except that duplicate names are disallowed; and in the
389
            case of bones missing in source skeleton, nothing happen for those
390
            bones).
391
        @par
392
            There are also unnecessary to have same binding poses, this function
393
            will adjust keyframes of the source skeleton to match this skeleton
394
            automatically.
395
        @par
396
            It's useful for exporting skeleton animations separately. i.e. export
397
            mesh and 'master' skeleton at the same time, and then other animations
398
            will export separately (even if used completely difference binding
399
            pose), finally, merge separately exported animations into 'master'
400
            skeleton.
401
        @param
402
            source Pointer to source skeleton. It'll keep unmodified.
403
        @param
404
            boneHandleMap A map to translate identically bone's handle from source
405
            skeleton to this skeleton. If mapped bone handle doesn't exists in this
406
            skeleton, it'll created. You can populate bone handle map manually, or
407
            use predefined functions build bone handle map for you. (@see 
408
            _buildMapBoneByHandle, _buildMapBoneByName)
409
        @param
410
            animations A list name of animations to merge, if empty, all animations
411
            of source skeleton are used to merge. Note that the animation names
412
            must not presented in this skeleton, and will NOT pick up animations
413
            in linked skeletons (@see addLinkedSkeletonAnimationSource).
414
        */
415
        virtual void _mergeSkeletonAnimations(const Skeleton* source,
416
            const BoneHandleMap& boneHandleMap,
417
            const StringVector& animations = StringVector());
418
419
        /** Build the bone handle map to use with Skeleton::_mergeSkeletonAnimations.
420
421
            Identically bones are determine by handle.
422
        */
423
        virtual void _buildMapBoneByHandle(const Skeleton* source,
424
            BoneHandleMap& boneHandleMap) const;
425
426
        /** Build the bone handle map to use with Skeleton::_mergeSkeletonAnimations.
427
428
            Identically bones are determine by name.
429
        */
430
        virtual void _buildMapBoneByName(const Skeleton* source,
431
            BoneHandleMap& boneHandleMap) const;
432
433
    protected:
434
        /// Storage of animations, lookup by name
435
        AnimationList mAnimationsList;
436
    private:
437
        /// Lookup by bone name
438
        typedef std::map<String, Bone*> BoneListByName;
439
        BoneListByName mBoneListByName;
440
441
        /// Pointer to root bones (can now have multiple roots)
442
        mutable BoneList mRootBones;
443
        typedef std::set<Bone*> BoneSet;
444
        /// Manual bones
445
        BoneSet mManualBones;
446
447
        /// List of references to other skeletons to use animations from 
448
        mutable LinkedSkeletonAnimSourceList mLinkedSkeletonAnimSourceList;
449
450
        SkeletonAnimationBlendMode mBlendState;
451
        /// Manual bones dirty?
452
        bool mManualBonesDirty;
453
        /// Storage of bones, indexed by bone handle
454
        BoneList mBoneList;
455
456
        /** Internal method which parses the bones to derive the root bone. 
457
458
            Must be const because called in getRootBone but mRootBone is mutable
459
            since lazy-updated.
460
        */
461
        void deriveRootBone(void) const;
462
463
        /// Debugging method
464
        _OgreExport friend std::ostream& operator<<(std::ostream& o, const Skeleton& s);
465
466
0
        void loadImpl() override {}
467
0
        void unloadImpl() override { unprepareImpl(); }
468
469
        void prepareImpl(void) override;
470
        void unprepareImpl(void) override;
471
        /// @copydoc Resource::calculateSize
472
        size_t calculateSize(void) const override;
473
474
    };
475
    /** @} */
476
    /** @} */
477
478
}
479
480
#include "OgreHeaderSuffix.h"
481
482
#endif
483