Does an event get fired after a Layer has finished rendering in Openlayers 3?

I am rendering about 27000 Markers in different layers on a mapview. Everything works fine on fast devices.

I have a problem on older devices (like the iPad3). When i hide one layer and set another layer to visible = true, it takes several seconds for the change to take affect on the mapview. The mapview is frozen in this time and any user interaction is delayed until the cluster layer has finished rendering. It would be better for me to show a loading popup and wait until the view has finally finished rendering.

Is there any event which gets fired after the rendering on the mapview has finished and how can I connect to it?

I found another question (register event "loadend" on layer) with one answer which lead me to the right event:

vectorLayer.on('postcompose', function(event) { if (vectorLayer.getVisible()) { doSomething(); } });

The methoddoSomething();is now called when the corresponding vector layer was completely rendered on the Canvas.

Exoplayer offer advance implementation which media player do not.

in Advance example of Exoplayer by Android, in FullPlayerActivity.java they have implemented onStateChanged, which offers STATE_ENDED

I know this is old, but just to expand on the accepted answer:

Google has deprecate ExoPlayer.STATE_ENDED and has replaced with Player.STATE_ENDED .

Since this post has been a while, I will write a Kotlin version of the listener down below.

UPDATE: 05-2020 Since DefaultEventListener and onPlayerStateChanged() are deprecated.

You can do this:

But @Murtaza Khursheed Hussain answer is right! Have a nice code day! Let me know if you need something else!

You have to implement the interface Player.EventLister and add to your exoPlayer.

Just write your code on the method onPlayerStateChanged. See the code.

For non-concatenated MediaSource (representing whatever individual piece of media you want to play), you'll receive STATE_ENDED when the piece of media has finished playing.

For a ConcatenatingMediaSource it occurs when the entire concatenation has finished playing (i.e. you've played up to the end of the final item in the concatenation). So, STATE_ENDED occurs when the entire MediaSource has finished playing.

For a ConcatenatingMediaSource, the best callback to detect end of current media and start of next media playback is "onPositionDiscontinuity" You should use onPositionDiscontinuity() to figure out when transitions occur. Please note, onPositionDiscontinuity is invoked for some other cases too, but you can call getCurrentWindowIndex() and compare it to what window you think you're in to determine whether a transition has occurred. You can do something like below:

You are correct in assuming that each tileloadstart event on the source should be followed by a tileloadend or tileloaderror for the corresponding tile. That can be used, as in the linked official example, to keep track of the number of loading tiles.

When the sum of emitted tileloadend and tileloaderror events equal the number of tileloadstart events, no loading is in progress. If this is not the case, you should try to make a reproducible example, as it would probably be a bug in the library.

It is however important to understand what these events mean. The tileloadend event does not mean that the tile is visible on the map, it means that the tile has finished loading and is usable for rendering. The actual rendering of the tile will be done after the event handler is invoked. So any tile loading logic requiring information about when all tiles are loaded and rendered (such when taking screenshots/creating prints) will have to wait until the next postrender event.

You mention 5-10 seconds between a tileloadend and the tile actually appearing on the map, which is too long for it to be rendering related (unless you do some really freaky rendering callbacks).

After looking at the setGeometry source code (feature.js), basically it will use the set method on geometryName_. So by explicitly setting the same property and set opt_silent to true, it will not fire the change event (object.js).

Once you have completed the changes, just fire the change event on the layer.

Don't skip the change events

The basic premise of the question - that each feature change results in a redraw of the layer - is incorrect.

When a feature changes, the map will request a redraw on the next animation frame. But if multiple features are changed within the same thread of execution, the browser won't redraw anything until the script finishes. You could loop through and change millions of features with only a single redraw.

You can verify when a render is done by listening to the postrender event:

You could set the geometry without triggering any events, as suggested in your answer. But doing so could cause issues such as a corrupt spatial index in the source. Omitting the change events should only be done if you know for sure that no one is interested in that change.

What delays are there then?

With that said, there's still a performance hit to updating a lot of features. I wrote this demo, which replaces all features' geometries on each map click. On my laptop, it takes around 600 milliseconds to replace all 10 000 geometries. During that time, the map and the browser is unresponsive and no updates are shown until the next redraw. The duration of the redraw depends on the zoom level.

When settings the geometry on a feature, it will:

• add the geometry to it's properties
• remove any listeners to the previous geometry.
• add change listeners to the new geometry.
• trigger a change event to notify listeners that it has changed.

On of the listeners of the feature will be the source, which will:

• update the spatial index, if used.
• trigger a change event to notify listeners that it has changed.

The layer and eventually the map will we notified of these changes, and queue a redraw.

Possible optimizations

If you wish to be able to change many features in a more performant way, I'd suggest considering:

Disabling the spatial index

As noted in the docs, setting useSpatialIndex to false may increase performance in some situations. Without the spatial index, the source has less computations to do on each feature change. Other uses of the source might become less performant without the index, though.

Modifying the geometry instead of replacing it

Using setCoordinates on the geometry is faster than using setGeometry on the feature. The whole Geometry instance creation can be skipped, and no listeners has to be modified. This assumes that you can modify the geometry, such as if the feature is the sole 'owner' of the geometry.

Trying to split the feature modifications into smaller chunks

This is contrary to the intent of the question. If it takes a lot of time to modify the features, you probably want to trigger a render more often. That would make the map appear more responsive, as well as allowing the browser to catch up on handling events and other pending tasks.

First: Features don't fire clicks! For information on the events features do fire, check http://openlayers.org/en/master/apidoc/ol.Feature.html.

For checking if a feature did get clicked, there is the .forEachFeatureAtPixel(pixel, callback) function of ol.Map. ( http://openlayers.org/en/master/apidoc/ol.Map.html#forEachFeatureAtPixel ) The callback is executed on every feature at the pixel. The callback gets passed 2 arguments: the feature and the layer the feature is in.

Good to know is the .getEventPixel(event) function, if you don't work with openlayers event handlers but with handlers on the viewport. If your using openlayers eventhandler, the event has a property .pixel . (http://openlayers.org/en/master/apidoc/ol.Map.html#getEventPixel) The methods .getEventCoordinate(event) and .getCoordinateFromPixels(pixels) might be useful, too.

So you would add it like this to your map.on("click", . :

You might also want to check this example, there are two uses of this function, first with openlayers events, the second with jQuery events: http://openlayers.org/en/master/examples/icon.js

There is also the possibility to do this with an ol.interaction.Select (http://openlayers.org/en/master/apidoc/ol.interaction.Select.html?unstable=true), but this is a little bit overpowered for this case. And it has some unintuitive caveats caused by openlayers internally moving the selected features to another so called unmanaged layer.

Anyhow this works by adding a listener to the collection belonging to the interaction. The collection can be retrieved with .getFeatures() .

As far as I know - none is fired. Render function is empty in source code.

The default implementation of render is a no-op

I would recommend just triggering it manually when necessary.

I ran into this post which seems interesting

Or you can do the following, which is what Backbone code is supposed to look like (Observer pattern, aka pub/sub). This is the way to go:

Edit: this.on('render', 'afterRender') will not work - because Backbone.Events.on accepts only functions. The .on('event', 'methodName') magic is made possible by Backbone.View.delegateEvents and as such is only available with DOM events.

If you happen to be using Marionette, Marionette adds show and render events on views. See this StackOverflow question for an example.

On a side note, Marionette adds a lot of other useful features that you might be interested in.

I realise this question is fairly old but I wanted a solution that allowed the same custom function to be called after every call to render , so came up with the following.

First, override the default Backbone render function:

The above code calls customRender on the view, then a generic custom function ( afterPageRender ), then the original Backbone render function.

Then in my views, I replaced all instances of render functions with customRender :

DIV does not fire a resize event, so you won't be able to do exactly what you've coded, but you could look into monitoring DOM properties.

If you are actually working with something like resizables, and that is the only way for a div to change in size, then your resize plugin will probably be implementing a callback of its own.

I was only interested for a trigger when a width of an element was changed (I don' care about height), so I created a jquery event that does exactly that, using an invisible iframe element.

It requires the following css :

You can see it in action here widthChanged fiddle

I've created jquery plugin jquery.resize it use resizeObserver if supported or solution based on marcj/css-element-queries scroll event, no setTimeout/setInterval.

I've created this for jQuery Terminal and extracted into separated repo and npm package, but in a mean time I switched to hidden iframe because I had problems with resize if element was inside iframe. I may update the plugin accordingly. You can look at iframe based resizer plugin in jQuery Terminal source code.

EDIT: new version use iframe and resize on it's window object because the previous solutions was not working when page was inside iframe.

EDIT2: Because the fallback use iframe you can't use it with form controls or images, you need to add it to the wrapper element.

EDIT3:: there is better solution using resizeObserver polyfill that use mutation observer (if resizeObserver is not supported) and work even in IE. It also have TypeScript typings.

renderedCallback called after every render of the component. This lifecycle hook is specific to Lightning Web Components, it isn’t from the HTML custom elements specification. This hook flows from child to parent.

Let's understand it better. See the below code:-

When this code runs and generate outputs, It is as below:-

First constructor gets fired then connected callback and then renderedcallback as it completes the lifecycle. Then wired method gets called and it sets the properties values and it fired the renderedcallback once again.

This gives you an explanation of order of execution of your js code.

Coming to your requirement to fire an event when both the arrayList form wire method are not equal to 0, see below points:-

Introduction to Archaeological Methods and Sources

Archaeology’s focus on material culture provides it with unparalleled opportunities to investigate the entire span of the human past. For periods for which historical records (verbal as well as textual) exist, this includes its ability to deliver insights into the lives of individuals and communities only partially represented, if at all, in those records. Its remit ranges from individual sites requiring excavation to surface scatters of artifacts, from upstanding monuments to entire landscapes. Interpreting archaeological observations depends upon establishing that they are in valid association with each other and can be accurately dated. In both cases the principles of stratigraphic superimposition, association, and context are key concerns. While analogies derived from ethnographic data sustain many archaeological interpretations, individual finds and assemblages of finds are also investigated using a wide range of scientific and other techniques.

Archaeology and History

African archaeology and African history have had a long and at times heated relationship. Until the 1950s, archaeologists were almost exclusively interested in the remoter past of hunter-gatherers and early hominins, coming to emphasize more recent periods only as the independence movement gathered strength. 1 Debate has focused on several topics. Has archaeological research on periods informed by historical sources been unduly dominated by the latter’s expectations and agendas, as in the well-known emphasis in the West African Sahel on excavating historically known sites like Gao or Kumbi Saleh? 2 If “historical archaeology” is to be recognized as a distinct sub-discipline, should it be restricted to the era of globalization and international capitalism set in motion by Europe’s voyages of discovery? 3 Or should it be broadened out to encompass all periods and contexts, before and after the 15th century , for which historical records exist, regardless of how they have been transmitted—via writing, by word of mouth, or in material form? 4 Has African archaeology been handicapped by what some historians may have considered as an undue dependence on neo-evolutionary thinking (as discussed in “Primary Historical Sources in Archaeology: Methods” and “Ethnographic Analogy in Archaeology: Methodological Insights from Southern Africa”)? 5

However these debates are resolved, there is widespread recognition that what ultimately distinguishes the practice of archaeology from other disciplines interested in Africa’s past is its emphasis on the material—as opposed to the verbal, textual, or biological—residues of human actions. Most obviously, those residues comprise the artifacts that people made and used in their daily lives, the remnants of the structures in which they lived, and their own physical remains. In addition there is everything else that people employed, altered, and ultimately discarded, from the bones of the animals they ate to the microscopic traces of plants consumed as food or fuel to chemical changes in the very soils on which they placed their houses, fields, and livestock enclosures.

Sometimes deliberately, but more often through the gradual accumulation of layers of sediment via natural processes and human actions, these residues become buried. Failing natural erosion, they can then only be uncovered via excavation. But archaeology is not just about digging holes in the ground. The material remains that people create also frequently survive on the surface, from the coral porites mosques of the Swahili coast to the drystone-walled livestock enclosures and houses of southern Africa’s highveld to the earthen tumuli of the Sahel. As well as such readily recognizable architecture for the living and the dead, there may also be evidence of mining, quarrying, or the production of metals (notably in the form of smelting furnaces and slag). Rock art, whether in the form of painted shelters and caves, engravings on more open rock surfaces or boulders, or inscriptions constitutes another major component of the above-ground record in many parts of the continent. So, too, do other forms of human modification of the landscape, from constructing field systems, terraces, and trackways through safeguarding sacred forests and groves to evidence of how people’s activities have altered whole ecologies by cutting down trees, cultivating fields, grazing their livestock, or hunting apex predators and key ecosystem engineers. 6

Even this quick overview makes clear how broad archaeology’s purview is and the scale of the challenge that it sets itself. Often met by drawing analogies between societies of the present and those of the past (see “Ethnographic Analogy in Archaeology: Methodological Insights from Southern Africa”), that challenge is all the greater when recognizing that ultimately what archaeologists seek to do is, in the words of David Clarke, to recover “unobservable . . . behaviour patterns from indirect traces in bad samples”: unobservable because for lack of a time machine they cannot directly see what people did indirect because those traces were rarely intended to convey the information that they seek and bad because of the many processes that intervene between what once existed in the past and what survives to be located and recovered in the present. 7 Identifying those processes and accounting for their effects in determining what survives and what does not and how archaeological deposits form (something archaeologists generally term “taphonomy”) is a critical part of any analysis (see discussion in “Archaeozoology: Methods”).

This article examines how archaeologists working in Africa recover and make sense of those traces, though for lack of space it does not review the theoretical frameworks they use. 8 It also introduces all of the other articles included in the Archaeological Methods and Sources section of the Oxford Research Encyclopedia of African History so that readers can better grasp where those contributions fit within the broader scope of archaeological activity in Africa as a whole. The article begins by reviewing how archaeological sites are found and documented, whether by excavation or through the study of upstanding monuments and landscapes. Because bringing order to the past is essential for its study, it next considers how archaeologists order their material chronologically and spatially, stressing the importance of “context” and “association”. It then introduces some of the key approaches archaeologists employ to answer such basic questions as: How were African societies organized? In what kinds of environment did they live? What foods did they eat and what tools did they use? How were these made and obtained? What were people like physically, and what contacts did they have with others? How did they construct a sense of identity for themselves as individuals and communities, whether in terms of gender (see “The Archaeology of Gender in Sub-Saharan Africa”), age, ethnicity, descent, or any other parameter? Archaeologists’ answers to these questions hold importance for all aspects of Africa’s past, particularly those out of reach of written or remembered histories by reason of their antiquity or those whose histories focus on politics and the concerns of the elite few rather than the day-to-day lives of the many (see “Documenting Precolonial Trade in Africa” and “Primary Historical Sources in Archaeology: Methods”).

Locating Sites

Although some sites of archaeological interest (e.g., Great Zimbabwe) may be obvious, the majority are not and require systematic search if they are to be identified. 9 Previous work in an area, consultations with local communities, and references in historical sources are all potential sources of information, but in many cases systematic field survey is required in order to find and record as wide a range of sites as possible. For reasons of time and cost archaeologists typically select parts of their overall study area for intensive examination. Although not always used, probabilistic sampling techniques allow the results obtained from that sample to be generalized to the wider region with a quantifiable degree of confidence. Variables thought relevant to the past societies in question—for example, topography and ecology—can be used to “stratify” a sample, combining the benefits of random selection with prior knowledge when selecting the areas to be searched.

Typically, those areas are inspected on foot (but sometimes from vehicle or even horseback), recording the position, context, and content of such traces of past human activity as may be present using maps, GPS technology, photographs, and predesigned forms intended to produce data of comparable quality across all sites. Traversing linear transects set across a region’s environmental grain may be particularly productive as they are, in principle, easy to lay out and follow, will intersect a range of ecological variability, and require less movement back and forth than visits to multiple individual sampling locations within the same area. On a very large geographical scale development projects such as the Chad-Cameroon oil pipeline provide a special case of such transects over hundreds of kilometers. 10 However, all over Africa archaeological fieldwork is increasingly undertaken where infrastructural projects (dams, pipelines, roads, housing developments, etc.) are located, rather than because of purely research considerations. 11

Pedestrian survey is far from the only way of finding sites. Aerial photography, for example, played a major part in detecting stone-built settlements of the 2nd millennium ad in South Africa’s Free State province in the 1960s. 12 A decade later Jim Denbow realized that in eastern Botswana farmer villages could be picked out from the air as dense, lighter-colored stands of African foxtail grass ( Cenchrus ciliaris ) growing in dung-enriched former cattle enclosures. 13 Today, satellite imagery and other forms of remote sensing (such as airborne laser scanning), including Google Earth, provide new means of locating sites ahead of ever entering a region. Recent examples include further work on the distribution of stonewalled structures on South Africa’s highveld, mapping of Garamantian and early Islamic settlements in the Libyan Sahara, and detection of Holocene shell middens on the coast of Eritrea. 14 Documenting sites in areas of conflict as part of efforts to mitigate damage from looting and other forms of vandalism, an increasing problem across North Africa, in particular, also draws on remote sensing techniques. 15 Offshore, however, exploration of shipwrecks, an important source of evidence for intercontinental contact and trade, continues to focus largely on already known wreck sites and harbors or to depend upon serendipitous discoveries. 16

Whether on land or under the water, archaeologists select only some sites for excavation and even in these cases less intrusive forms of on-site reconnaissance normally come first. The techniques involved are numerous and at their most basic involve planning whatever may be visible at the surface and locating, identifying, and—in some cases—removing for more detailed study visible scatters of ceramics, stone tools, or other artifacts. On thickly stratified sites, such as those found in West Africa’s Sahel, however, such material may only reflect the most recent periods of occupation, with older levels left unrepresented. Various forms of subsurface detection can be used to get around this or to explore sites that are otherwise beyond the archaeologist’s reach. At Jenné, Mali, for example, a densely built-up town of more than 30,000 people, coring was used to access ceramics, datable charcoal, and other finds at multiple locations across the site. 17

Geophysical survey is also increasingly common, although the availability of what is typically costly equipment still disproportionately favors its deployment north of the Sahara. Several techniques exist, notably magnetometry, fluxgate gradiometry, and electrical resistivity survey. They vary in the speed with which they can be applied, the depths they can reach (1 to 0.3–1.5 m, but much deeper in the case of ground-penetrating radar), and the kinds of features they can detect (brick, fired clay floors, potsherd concentrations, smelting furnaces, ditches, pits etc.). A recent review emphasizes their complementarity, along with the (perhaps obvious) fact that best results will come where, as at the Swahili town of Songo Mnara, Tanzania, they are integrated with studies of surface artifact distributions and geochemical analyses of soils. 18

Excavation

Confirmation of what is below the surface and access to it on more than the most limited scale can, however, come only from excavation. In this sense digging remains a fundamental part of the archaeologist’s toolkit. Several principles are key, foremost among them once again the necessity of keeping as detailed a set of records as possible given that the removal of archaeological deposits necessarily entails their destruction. Insofar as future researchers can replicate any particular excavation, this depends entirely on the quality of the plans, drawings, photographs, written records, and—sometimes—video recordings made during the original fieldwork. Collectively, such records provide the context of the finds made, that is, the specific patterns of physical association relating them to each other and to the sediments in which they were found. Finds without context may still be informative, but their scientific significance is inevitably compromised by the lack of data regarding where and with what they were found the majority of the well-known terracotta figurines from Mali’s Inland Niger Delta or Nigeria’s Jos Plateau are cases in point and underline the destruction of information that looting entails. 19

Along with context and association, stratigraphy is a third essential principle of excavation. Put simply, archaeological deposits build up in sequence, with younger layers lying above those that are older in date. The archaeologist’s task is to differentiate between those layers and to remove them in the reverse order to that in which they formed. Differences in the color and texture of sediments provide the basis for distinguishing between one layer and another, aided in some cases by traces of surviving architecture (brick, mudbrick, or stone walls, daga, stone, or gravel floors) in some sites. Where differences in the soil cannot be discerned, or where natural stratigraphic layers are considered too thick to maintain adequate control, arbitrary horizontal “spits” may be used instead. Varying in depth between as little as 2 cm and as much as 10 cm in modern excavations, their use should always be a matter of last recourse to avoid conflating finds from different sedimentary contexts. However, the ease with which spits can be employed compared to the slow teasing out of complex stratigraphic relationships has meant that they have often been used much more widely than is ideal, with an inevitable loss of contextual control.

If stratigraphy and—where necessary—spits provide control in the vertical dimension, then a metric grid mapped in relation to a fixed datum point underpins it horizontally. Minimally, such grids can locate finds to within a single square meter or less (for example, a 0.5 x 0.5 m quadrant). However, modern technology provides ways of rapidly recording the precise location of individual finds in three dimensions in ways unimaginable just a couple of decades ago using such technologies as a Total Station. It and similar devices have also facilitated larger scale, open-plan exposures of archaeological horizons, not least where architectural remains able to provide a spatial framework for excavation are absent one important consequence for many urban sites has been the recognition of more ephemeral buildings and of the social importance of open spaces between structures. 20

Rarely, if ever, can—or should—archaeological sites be excavated in their entirety logistics, funding, and ethics all counsel against this. They must therefore be sampled in ways that attempt to explore as representative a range of locations as possible. Sieving deposits enhances the recovery of smaller finds, such as beads or rodent dentitions that may be invaluable as evidence of past trade or environmental conditions once identified. However, sieving (screening) was far from universally employed in the past, and its effectiveness varies enormously depending on the mesh sizes employed and on whether water is used to help break down sediments, something that is not always feasible. Taking samples with specific aims in mind can further enhance the comprehensiveness of what is recovered, for example the soil samples intended for morphological, geochemical, and phytolith analyses to investigate the use of space in domestic and public areas at Songo Mnara. 21 But whatever combination of strategies is employed, they need to be fully documented, especially with regard to whether sieving has been used (and with what size of mesh) and to any decisions not to keep—or analyze—everything found. Older excavations frequently failed to do this, compromising their ability to answer questions posed using newly invented methodologies and different research agendas.

Rock Art and Other Monuments

What is sometimes referred to as the “built” component of the archaeological record provides opportunities for learning about the past that do not require excavation. Once found through regional survey projects, rock art sites, for example, are typically documented using a combination of written records with photography and/or tracing. Although it is an exaggeration to claim that photography is in some sense more “objective,” it undoubtedly has the advantage of speed, allowing more images and sites to be recorded in a given span of time. New digital enhancement techniques allow details of now-faded images to be seen much more clearly, revealing important new information. 22 Tracing, on the other hand, while slow and requiring considerable experience, can identify subtleties that escape the camera. Scientific advances across a range of fields allow micro-sampling of individual painted images to deliver an increasing wealth of information about the pigments used to make them, the inclusion in them of ritually significant substances of plant or animal origin, and the date at which they were created. 23 Rock engravings, on other hand, remain much more difficult to date except by content and context. As to what rock art meant, archaeologists can, in some areas, draw upon the ethnography of the descendants of those who made it, or that of their relatives: Bushman (San) rock art in southern Africa is the best known example of this (“Ethnographic Analogy in Archaeology: Methodological Insights from Southern Africa” “The Archaeology of Gender in Sub-Saharan Africa”), although even here alternative—or, more accurately, complementary—perspectives exist, emphasizing, among other topics, considerations of gender, the spatial organization of images, and the behavior of the animals depicted (see “Interdisciplinary Perspectives on Precolonial Sub-Saharan African Farming and Herding Communities” and “Researching Rock Art: Methods”). 24 Beyond southern Africa, ethnographically grounded understandings of rock art have been advanced in Zambia/Malawi (for Chewa initiation ceremonies and secret societies, see “The Archaeology of Gender in Sub-Saharan Africa), Uganda, and Kenya/Tanzania (Maa cattle brands and shields), but convincing explanations of meaning that go beyond speculation are still lacking in other areas, such as the Sahara. 25 There, phenomenologically influenced interpretations focusing on how rock art was materially constituted and experienced offer a new way forward. 26

Other “built” aspects of the archaeological record invite different interpretive strategies. Monumental architecture, for example, can be approached through formal analyses of spatial structure that explore its potential for movement and visibility. At the Swahili town of Gede, Kenya, this has shown how the so-called “palace” complex underwent a series of changes reflecting shifting concerns regarding privacy, accessibility, and control of access. 27 Though their study is informed by known Swahili uses of space, it does not depend upon them. 28 Other approaches to the “built” record rest more heavily upon claims of continuity between the archaeological past and the ethnographic present or historic records. Tom Huffman’s interpretation of the organization of space at Great Zimbabwe and other stonewalled, elite-linked settlements of the Zimbabwe Culture is perhaps the best-known example, but is contested by other researchers, in part because of concerns that it does not readily allow for changes in how individual sites grew and developed over time (“Primary Historical Sources in Archaeology: Methods”). 29

Archaeological Landscapes

Archaeological sites do (did) not exist in a vacuum, but rather within a landscape minimally comprising themselves, the relations between those living at them, and the physical environment in which they and those relations are (were) embedded and expressed. That environment, moreover, is (was) not merely a set of resources (firewood, plant foods, animals, soils, etc.) that people exploit(ed), but also a complex system of ideas conferring meaning on and attributing history to specific features within it (hills, lakes, streams, rivers, forests, etc., as well as humanly made or modified monuments). Landscapes, then, are material manifestations of the relationship between humans and the environment, the perspective, in other words, of historical ecology and one that explicitly recognizes how humans transform and alter the settings in which they live (“Interactions between Precolonial Foragers, Herders, and Farmers in Southern Africa” “Primary Historical Sources in Archaeology: Methods” “Interdisciplinary Perspectives on Precolonial Sub-Saharan African Farming and Herding Communities”). 30

Archaeologists have explored these ideas in several ways. One involves joining hands with palaeoenvironmental scientists to emphasize the recovery of evidence that speaks to how landscapes and the ecological communities associated with them have changed over time (“Paleoenvironmental Science: Methods”): geomorphological work, studies of soil profiles, and retrieval of cores from wetland settings suitable for pollen analysis may all be involved here, as exemplified by projects in Tanzania that have revealed much more complex interactions between people’s farming, herding, and iron-smelting activities, climate change, and ecological succession than official colonial or postcolonial emphases on human destructiveness suggested. 31 Other studies have placed greater emphasis on the ritual and sacred aspects of landscapes, for example in investigating Talensi shrines in northern Ghana, or the ways in which the inhabitants of the Hueda kingdom in southern Bénin constructed and maintained shrines as places of veneration and political action that helped bind them together. 32 Investigating how people deliberately set out to alter the environment in which they lived in order to enhance agropastoral production represents a third concern, most clearly evident perhaps in investigations of the irrigation systems at the Tanzanian site of Engaruka and the agricultural terraces of Zimbabwe’s Nyanga Highlands, but they are far from alone, as work on South Africa’s Bokoni Escarpment or in Kenya’s Pokot and Marakwet regions readily shows (“Archaeozoology: Methods”). 33 All these projects combine historical and ethnographic research with careful archaeological mapping, survey, and excavation, along with attempts at reconstructing past environmental conditions.

Though not unique to archaeology, Geographic Information Systems (GIS) finds increasing application in all these endeavors. GIS offers a way of acquiring, storing, manipulating, interrogating, and displaying a wide range of spatial information, including the production of maps and the statistical analysis of data. GIS also provides a highly versatile means of combining archaeological evidence with information about environmental variation and can directly incorporate information on site and find locations obtained using GPS technology and Total Stations. 34 Examples include: analysis of spatiotemporal patterning in the location of hunter-gatherer activities in South Africa’s Seacow Valley over the past 700,000 years, a study drawing on almost 14,000 individual sites investigation of the placement (for enhanced conspicuousness and visibility) of DGB sites with their associated stone walls, platforms, and terraces in Cameroon’s Mandara Mountains and definition of tourist access to rock art sites in Libya’s Acacus Mountains. 35 Combining GIS with remote sensing data to explore environmental influences on archaeological site distributions may prove particularly valuable, especially where, as in Libya, physical access is difficult. 36

A Matter of Time

One of the pioneers of precolonial African history, Roland Oliver, once declared that what archaeologists could offer him and his colleagues was “dates.” 37 Even in the 1960s, of course, archaeology was more than a mere calendrical handmaiden of history, but setting what it discovers in temporal sequence remains a fundamental concern. Without a sound chronology, in short, there can be no convincing interpretation of the African past. How do archaeologists tackle this challenge (“Primary Historical Sources in Archaeology: Methods”)? At the level of the individual site, the principles of stratigraphic superimposition and association remain key: individual features and layers of sediment are deposited and created one above the other with the youngest on top, and items found together are—in the absence of evidence of disturbance—presumed to belong together. A third basic tool is seriation, that is, the ordering of assemblages of artifacts by changes in their attributes. Most frequently for those periods of principal interest to historians, this involves the decoration applied to pottery, and its application has been a mainstay of ceramic analysis across Africa and beyond. However, seriation per se does not tell us the direction in which a sequence of changes is to be read (though stratigraphy and association may) nor the rates at which the changes identified happened. Indeed, with all three principles we are left only with a relative chronology that says nothing about how old any part of a given sequence is. For that, additional information is required.

One means of placing archaeological materials in absolute time is to use what is known as cross-dating, in other words the presence in an archaeological assemblage of items that are, within limits, already known to be of a certain age. Given the very limited use of writing in sub-Saharan Africa only rarely will such items carry an absolute date of their own, though examples exist, such as the early second-millennium Islamic tombstones from Gao in Mali. 38 Much more commonly, archaeologists work with objects such as pottery made in chronologically well-defined contexts beyond Africa and subsequently imported to the continent through complex systems of trade and exchange (“Documenting Precolonial Trade in Africa”). Blue-on-white Chinese porcelain, for example, of the reign of the Ming emperor Hongzhi ( 1488–1521 ) found at Great Zimbabwe confirms that the site continued to be occupied into the sixteenth century . 39 While we cannot be sure precisely when such porcelain reached Great Zimbabwe or was deposited there, we do know that it cannot have been before the end of the 1400s, that is, its presence serves as a terminus post quem—a date after which—for the context in which it was found. Conversely, a late- 19th-century copper percussion cap in undisturbed deposits at the surface of Volstruisfontein rock shelter, South Africa, provides a terminus ante quem—an upper age limit—for the glass beads and other items of European manufacture left there by the site’s post-contact Bushman inhabitants. 40 Glass beads can themselves, of course, carry chronological information, although the temporal boundaries associated with specific types or production centers are often broader than those for pottery. 41 So, too, do the clay tobacco pipes found at many 17th - to 19th-century centers of European trade and settlement along the African coast. 42

Advances in physics and chemistry have produced many techniques now able to give tolerably precise absolute ages to a wide range of materials (“Scientific Dating Methods in African Archaeology”). 43 Note, however, the adverb “tolerably” because in all cases the “absolute” ages obtained will be accompanied by a standard error and must actually be understood as a statement of probability rather than as a direct equivalent to the calendrical age inscribed on a coin or in a text. Discussion of what is by far the most widely used technique—radiocarbon dating—will make this clear.

In very simple terms, radiocarbon dating depends upon the fact that while alive all organisms acquire carbon from their environment in the form of food (carbon dioxide for use in photosynthesis in the case of plants). But there are, in fact, three isotopes of carbon, one of which ( 14 C) is radioactive. Because carbon is continually being absorbed, the ratio between it and the most common isotope, 12 C, remains constant during life, but changes after death as 14 C atoms continue to undergo radioactive decay and transform into atoms of nitrogen. Knowing the ratio of 12 C to 14 C in the atmosphere when an organism was alive, the rate at which decay occurs, and the amount of 14 C remaining in an organic sample, it is thus possible to calculate when that sample ceased to absorb 14 C, that is, when it died. For example, a seed of pearl millet ( Pennisetum glaucum ) from the site of Karkarichinkat, Mali, has been dated using the radiocarbon method to 4011±33 years bp (Before Present, a conventional baseline equivalent to ad 1950 , the year after the technique was invented). 44 Given unavoidable uncertainties involved in the measurement process, what this means is that this seed has a 68.2 percent probability of being between 4044 and 3978 years older, and a 95.4 percent probability of being 4077 to 3945 years older, than ad 1950 .

In fact, matters are not so simple given that the quantity of 14 C in the atmosphere, and thus available to living plants and animals, has not remained constant over time. Radiocarbon “dates” are thus not expressed in true, solar years, but must instead be calibrated in order to convert them to calendrical ages. Several calibration curves exist and are available online (e.g.,OxCal), being based for the last 10,000 years or so primarily on dating the annual growth rings in certain tree species. In the case of our Malian millet seed, calibration shows that it has a 95.4 percent probability of having formed and been harvested between 2620 and 2467 bc , an “absolute” time span of almost 200 years. Though this may seem a large range, within individual site sequences and across them it is possible to narrow this by using Bayesian statistics, a methodology that is being increasingly applied. Also increasingly common are detailed reassessments of the reliability of existing sets of dates that take into account variation in the quality of the materials dated and the techniques used to remove potential contaminants before dating, as well as the size of the associated errors. Much more work of this kind is likely in the near future as archaeologists exploit the growing numbers of radiocarbon dates to assess large-scale spatial and temporal trends in cultural processes such as the spread of food production, pottery, and metallurgy. 45

Another important development has been the increasing application of Accelerator Mass Spectrometry (AMS) radiocarbon dating. Instead of estimating the ratio of 12 C to 14 C by the number of 14 C atoms that decay over a given time, this directly counts those that are present. The result is that, as with the Karkarichinkat millet seed, much tinier samples can be dated than was once the case. One important advantage of this is that it is often now possible to obtain an age for what one wishes to know rather than having to assume that that event is correctly associated with the material (typically charcoal) being dated. For example, AMS dating of several sheep bones from sites in South Africa showed that in most cases they were several hundred years younger than the deposits in which they had been found, that is, that they were out of context and not correctly associated with the charcoal-based radiocarbon dates with which they had previously been linked, rendering them irrelevant to determining when sheep first entered that region. 46 Conversely, AMS dating of a cow horn core from northwestern South Africa established the presence of cattle there several centuries earlier than was once thought. 47

For the historian, what this means can be summarized in a few brief statements: radiocarbon dating can be applied to anything that is organic, with short-lived organisms providing the tightest possible dating and charcoal—usually ubiquitous on most archaeological sites—a highly suitable material its wide applicability makes it the basis of most archaeological chronologies in Africa for the past 40,000 years individual dates are less dependable than broad patterns if contamination or context are in question they are also always probability statements, not precise calendrical ages it is essential to be clear whether one is citing calibrated or uncalibrated ages and what calibration program has been used and the original “raw” determination, standard error, and identifying laboratory code should always be provided alongside any calibrated age because calibration programs are subject to continual revision.

What has been said of radiocarbon dating applies in general terms to many of the other dating techniques that can provide ages for archaeological finds in absolute time. Over the time spans of interest to most historians two, in particular, are important in Africa: thermoluminescence (TL) and optically stimulated luminescence (OSL). The first measures the amount of energy trapped in the lattice structure of crystalline materials (typically clay) as radioactive elements decay. As heating those materials above 500˚C releases that energy as light (hence the term “thermoluminescence”), the effect of firing pottery or otherwise baking clay (for example, in a house floor) is to reset that clock to zero subsequent measurement of the energy accumulated by reheating the sample in a laboratory allows the time elapsed since the first heating to be estimated. Though less widely used than radiocarbon, TL has proved important in dating West African terracotta figurines and statues for which contextual information is often lacking, including those from the Jenné area of Mali. 48 Potsherds, burnt stone, and fired clay crucibles have also been dated, for example to provide a chronology for glass production at Ife, Nigeria. 49

OSL dating works in a similar way, but dates minerals that have been exposed to light, rather than heat, with sunlight acting as the trigger for “resetting the clock.” As with TL, measurement of background radiation at the site concerned is essential, as is avoiding any possibility of contamination from potentially mixed sedimentary environments more so than for radiocarbon dating, samples therefore frequently need to be taken by specialists. Average values derived from measuring multiple quartz grains from individual sediment samples are preferable to bulk sampling in order to identify and discard aberrant grains whose presence may reflect post-depositional mixing of sediments of different age. 50 Compared to TL, however, OSL has thus far found most of its applications either in the Pleistocene or in dating geomorphological features, such as sand dunes or flood deposits. OSL dating of sediments containing stone tools at Lakaton’i Anja rock shelter, Madagascar, to the 2nd and 3rd millennia bc is an outstanding example to the contrary, because it documented a wholly unsuspected human (hunter-gatherer, presumably ex-African) presence on the island millennia before its settlement by Austronesian-speaking farmers from Southeast Asia. 51

One final point is worth making. Because of fluctuations in 14 C production in the upper atmosphere, there have been moments at which the radiocarbon calibration curve is essentially “flat.” At such times a single radiocarbon determination may cover several hundred actual years, rendering it impossible to use radiocarbon to produce a precise chronology. One such “plateau” inconveniently falls midway through the mid-1st millennium bc , exactly the time at which iron-smelting seems likely to have been adopted in parts of West and East Africa. Pinpointing where and when metallurgy came into use will therefore demand much greater use of alternative techniques like TL and OSL that can be applied directly to ancient furnaces instead of having to work with unacceptably broad estimates based on dating charcoal of uncertain age and association. 52 Dating of more recent iron-smelting furnaces in Swaziland exemplifies the potential of these other methodologies. 53

The Spatial Organization of African Cultures

As well as ordering their material in time, archaeologists also devote considerable efforts to ordering it in space. Here, the concept of “culture” (sometimes replaced by “tradition” or “industry”) is key. Archaeologists have used it to group together sites with recurring associations of similar artifacts within definable geographical areas (“Primary Historical Sources in Archaeology: Methods”). Typological classification of pottery, an inherently plastic material offering endless opportunities for variation in shape, size, and decoration, forms the basis for many of these groupings (see “Ceramics, Foodways, and Consumption: Methods” and “Pottery chaînes opératoires as Historical Documents”), but other forms of material culture have also been employed, including stone tools and patterns of settlement organization. Often, the groupings thus defined have been assumed to equate to an ethnically or linguistically definable “people,” one often identified with entities known from ethnographic, historical, or linguistic evidence. Older archaeological literature, in particular, was prone to such equations, in part because of a wish to contribute to broader historical debates in the absence of much explicitly archaeological evidence: repeated efforts to correlate different cultural groupings in East African prehistory with various Cushitic- and Nilotic-speaking populations offer one illustration. 54

Several caveats are in order, however. First, emphasizing the creation of “types” to which artifacts are assigned, while providing a ready means of recognizing similarities at the grand scale, obscures variation and change within those types themselves, particularly in attributes deemed unimportant. 55 Second, definitions of archaeological cultures inevitably incorporate a degree of arbitrariness based on the criteria and starting point chosen using different criteria and different assemblages as the basis for comparison generates different results. 56 Third, the assumption that the degree of interaction between human groups—and thus the likelihood of their belonging to the same “people”—straightforwardly mirrors the degree of similarity in their artifacts does not always hold, any more than the assumption that artifacts reflect ethnic identity. Ian Hodder’s work among the Tugen, Pokot, and Njemps communities of Kenya’s Lake Baringo Basin unambiguously showed instead that clear boundaries might not be matched by a lack of interaction, that identities, while springing from shared histories and cultural norms, are malleable, and that people actively use material culture according to their needs and circumstances (“Ceramics, Foodways, and Consumption: Methods” “Pottery Chaînes Opératoires as Historical Documents” “The Archaeology of Gender in Sub-Saharan Africa”). 57 Ever since, archaeologists have increasingly recognized that the stylistic identities they define “may not necessarily correspond to other linguistic, ethnic, or social models” and that people frequently draw instead upon common and long-standing shared systems of symbols to express multiple, variable, often situationally fluid identities. 58 Even in southern Africa, where ethnographic data do support a close correspondence between settlement pattern, beadwork, and ceramic design, most of the archaeological groups recognized likely equate to large-scale linguistic groupings rather than specific polities, and other approaches to understanding ceramic variation are increasingly being explored. 59 The takeaway message for non-archaeologists? Be aware that archaeologically defined entities reflect particular theoretical and methodological trajectories that demand critical questioning, rather than direct transference into ethnic or other identities. 60

Analyzing Archaeological Finds

A short introductory article like this leaves little scope for a comprehensive assessment of the kinds of artifacts and other remains of past human activity that archaeologists may recover in excavation or from surface collections. Thus, no more than a sample of the kinds of research domains that perhaps command (and merit) greatest attention is presented here. That no one individual is likely to be competent in more than one or two of those domains underlines the overwhelming importance of multidisciplinary research in tackling almost all archaeological fieldwork or post-excavation projects (for example, “Interactions between Precolonial Foragers, Herders, and Farmers in Southern Africa” and “Interdisciplinary Perspectives on Precolonial Sub-Saharan African Farming and Herding Communities).

One of the things of which we can be certain is that people in the past had to eat. Analysis of plant and animal remains is one way through which information about their diet can be obtained (“Archaeobotany: Methods” “Interdisciplinary Perspectives on Precolonial Sub-Saharan African Farming and Herding Communities” “Archaeozoology: Methods”). Bones, for example, when carefully analyzed with the benefit of a comparative reference collection will identify the species present at a site, something to which newly evolving techniques capable of identifying species-specific proteins (ZooMS proteomics) or ancient DNA will increasingly contribute (for example, by documenting the earliest evidence for ivory trading in southern Africa). 61 Calculating the relative importance of different taxa is less easy. Of two commonly used measures, the Number of Identified Specimens (NISP) does not take account of differences in the number of skeletal parts between species, bone fragmentation, or whether animals arrived at a site whole or already butchered (in which case some bones may have remained at the kill site). Conversely, while the Minimum Number of Individuals (MNI) needed to account for the bones present avoids the risk of counting the same specimen twice, it exaggerates the importance of rare taxa and again does not address the question of how the remains arrived. Calculations of available meat weight (which may be affected by age, sex, and cultural preferences regarding edibility) also require careful evaluation. Moving beyond the realm of calculation, an animal’s age at death may—in conjunction with a clearly defined breeding season—allow its time of death (and thus the season of a site’s occupation) to be defined. 62 Analysis of age/sex patterns across an assemblage can suggest whether certain kinds of animals were selectively hunted or, for livestock, kept primarily for meat or dairy production. 63 Cut marks on bones can in turn identify how animals were butchered and processed, not only for food, but also for products such as leather. 64

Plant remains usually survive far less well, partly because plant tissues are often less resistant to the ravages of time, partly because plants contain fewer inedible residues (cf. bone, horn, teeth). Being smaller and less obvious to begin with, plant remains are also more difficult to recover from excavation, especially without using flotation or wet-screening deposits. Tubers, roots, and other soft tissues may be particularly difficult to retrieve relative to seeds, though even these often survive poorly in tropical African soils. 65 In hyperarid conditions, however, as in Roman and Islamic ports on Egypt’s Red Sea coast, preservation may be excellent, and carbonized remains also often survive well, along with the impressions left on the surface of pottery by seeds and grains when it was fired one of the earliest investigations of sub-Saharan cereal domestication (at Dhar Tichitt, Mauritania) depended almost entirely on their analysis. 66 Phytoliths—microscopic silica bodies found in plant cells—also survive well and have the added virtue of being produced in large numbers. Perhaps the best-known example of their application to recent African history is the identification of banana (Musa sp.) phytoliths in a mid-1st-millennium bc context at Nkang, Cameroon, 1,000 years or so before their supposed introduction to the other side of the African continent, though as its critiques show the identifiability of phytoliths to particular taxa of archaeological or historical interest can be an issue. 67

How people used the preparation, consumption, and disposal of the foodstuffs that they ate and drank in ways that asserted, contested, or created identities for themselves and vis-à-vis others is something that can also be addressed—in conjunction with the analysis of plant and animal remains—by considering the kinds of ceramics and other vessels (for example, those of glass) employed to cook and serve meals or beverages (“Ceramics, Foodways, and Consumption: Methods”). However, for more direct evidence of what people ate we must turn to human remains themselves. Coprolites and stomach contents have only rarely been reported in Africa, but the continent’s archaeologists have a long history of using stable isotope analyses to learn about the diets of past individuals. 68 Differences in the ratio of 12 C to 13 C between different plant groups or between marine versus land plants, translated into the tissues of animals and then of people at higher trophic levels, can allow estimates to be made of the intake of terrestrial versus marine foods in areas like South Africa’s Cape or of shifts between consuming tropical and temperate cereals. The ratio of two nitrogen isotopes ( 15 N, 14 N), on the other hand, estimates animal to plant food consumption (“Interdisciplinary Perspectives on Precolonial Sub-Saharan African Farming and Herding Communities”). At the late- 17th-century site of Vergelegen near Cape Town, for example, these methods suggested that a woman (probably enslaved) had grown up eating rice somewhere in the Indian Ocean world only to switch to a diet heavy in fish later in life. 69 Strontium isotopes provide yet another source of information, though as this case shows their analysis too may be relevant to diet: the 87 Sr/ 86 Sr ratio varies according to bedrock geology, is transmitted up the food chain with negligible change, and can thus be used to track movements across a landscape, for example of livestock herds in precolonial southern Africa hunter-gatherers, pastoralists, and farmers in the Libyan Sahara or even the transportation of first-generation enslaved Africans to the Caribbean. 70

So too are laboratory-based analyses of artifacts (“African Iron Production and Iron Working Technologies: Methods”). Growing ever more informative and abundant, they can address how objects were made and used and from where they came. Archaeometallurgists, for example, employ a wide variety of techniques (including reflected and transmitted light optical microscopy, X-ray fluorescence, and X-ray diffraction) to analyze slags, clay tuyères and furnaces, and finished metal artifacts in order to ascertain the details of metal production, revealing both geographical and temporal differences in how this was conducted (“Precolonial Metallurgy and Mining across Africa” “African Iron Production and Iron Working Technologies: Methods”). Iron has attracted the most attention, but copper, tin, gold, and bronze have all been investigated. 74 Metal was, of course, also widely traded, both into and out of Africa. Some studies have used isotope ratios to track this, suggesting, for example, that some of the copper employed to make the famous Igbo Ukwu bronzes is likely to have been of North African (i.e., trans-Saharan) origin, but that bronze items from sites of the Zimbabwe culture were definitely produced in southern Africa from local sources, rather than using metal imported from across the Indian Ocean. 75

Glass and glass beads constitute another important pyrotechnology. It is now clear that glass was manufactured in late 1st/2nd-millennium ad Nigeria rather than always being imported to sub-Saharan Africa, but even where this was so glass beads themselves might be melted down and recast into novel forms, as at Mapungubwe in 13th-century South Africa. 76 The vast majority of glass beads used in precolonial Africa were nevertheless introduced via complex trade networks from sources ultimately as distant as South and Southeast Asia, the Middle East, and Europe. 77 Analyses of their chemical composition provide increasing precision on the sources used at particular times and in particular networks (“Documenting Precolonial Trade in Africa”). 78 Ceramics, too, can be sourced from their physico-chemical make-up, although here thin-section petrography is the dominant technique used. 79 Scientific studies of pottery technology, as opposed to ethnographically informed investigations of how pots are made, are nevertheless still rare. 80

Biomolecular studies are also now expanding apace (“Ceramics, Foodways, and Consumption: Methods” “Interdisciplinary Perspectives on Precolonial Sub-Saharan African Farming and Herding Communities” “Archaeozoology: Methods”). As well as documenting early dairy use in early Holocene ceramics from the Sahara, they have suggested that pots used by pastoralists in South Africa’s southwestern Cape were mainly used to process seal meat, identified adhesives used to mount stone tools (in conjunction with morphological studies of surviving micro-residues and use-wear), and provided new ways of identifying plant consumption and cooking techniques in pre-agricultural and agricultural populations in Sudan. 81 But it is perhaps the possibilities of recovering and identifying ancient DNA from plant, animal, and human sources that have elicited greatest interest. 82 Africa—outside Egypt—remains grossly understudied in this regard, and in many areas high temperatures or humidity may render preservation difficult. Nevertheless, several impressive studies have already been undertaken, including identifying the possible progenitors of the domestic donkey and of the wheat grown by the indigenous inhabitants of the Canary Islands. 83 Analysis of the DNA of modern plant and animal populations is also proving informative, for example in showing that Madagascar’s chickens, cattle, and other domestic animals have African, rather than Southeast Asian, origins (“Interdisciplinary Perspectives on Precolonial Sub-Saharan African Farming and Herding Communities” “Archaeozoology: Methods” “Paleoenvironmental Science: Methods”). 84 Similar analyses, of course, are also increasingly commonplace for assessing the history of Africa’s human inhabitants, though they have not always been undertaken with due care for sample provenance, appropriate caution concerning the correlation of results with archaeological phenomena, or recognition of the malleability of individual and group identities. 85 Recovery of ancient DNA from human remains is, however, still rare south of the Sahara. 86 Along with the stable isotope studies discussed earlier, most bioanthropological studies therefore continue to emphasize more traditional approaches focused on markers of diet, disease, and life history evident in individual skeletons. 87

Animation update loop

These functions and Profiler A window that helps you to optimize your game. It shows how much time is spent in the various areas of your game. For example, it can report the percentage of time spent rendering, animating or in your game logic. More info
See in Glossary Markers are called when Unity evaluates the Animation system.

OnStateMachineEnter: During the State Machine Update step, this callback is called on the first update frame when a controller’s state machine makes a transition that flows through an Entry state. It is not called for a transition to a StateMachine sub-state.

Note: Adding this callback to a StateMachineBehaviour component disables multithreaded state machine The set of states in an Animator Controller that a character or animated GameObject can be in, along with a set of transitions between those states and a variable to remember the current state. The states available will depend on the type of gameplay, but typical states include things like idling, walking, running and jumping. More info
See in Glossary evaluation.

OnStateMachineExit: During the State Machine Update step, this callback is called on the last update frame when a controller’s state machine makes a transition that flows through an Exit state. It is not called for a transition to a StateMachine sub-state.

Note: Adding this callback to a StateMachineBehaviour component disables multithreaded state machine evaluation.

Fire Animation Events Allows you to add data to an imported clip which determines when certain actions should occur in time with the animation. For example, for an animated character you might want to add events to walk and run cycles to indicate when the footstep sounds should play. More info
See in Glossary :
Calls all animation events from all clips sampled between the time of the last update and the time of the current update.

StateMachineBehaviour (OnStateEnter/OnStateUpdate/OnStateExit): A layer can have up to 3 active states: current state, interrupted state, and next state. This function is called for each active state with a StateMachineBehaviour component that defines the OnStateEnter, OnStateUpdate, or OnStateExit callback.

The function is called for the current state first, then the interrupted state, and finally the next state.

OnAnimatorMove: Every update frame, this is called once for each Animator component A component on a model that animates that model using the Animation system. The component has a reference to an Animator Controller asset that controls the animation. More info
See in Glossary to modify the Root Motion Motion of character’s root node, whether it’s controlled by the animation itself or externally. More info
See in Glossary .

StateMachineBehaviour(OnStateMove): This is called on each active state with a StateMachineBehaviour that defines this callback.

OnAnimatorIK: Sets up animation IK. This is called once for each Animator Controller layer with IK pass enabled.

This event executes only if you are using a Humanoid rig.

StateMachineBehaviour(OnStateIK): This is called on each active state with a StateMachineBehaviour component that defines this callback on a layer with IK pass enabled.

WriteProperties: Writes all other animated properties to the Scene from the main thread.

Useful profile markers

Some of the animation functions shown in the Script Lifecycle Flowchart are not Event functions that you can call they are internal functions called when Unity processes your animation.

These functions have Profiler Markers, so you can use the Profiler to see when in the frame Unity calls them. Knowing when Unity calls these functions can help you understand exactly when the Event functions you do call are executed.

For example, suppose you call Animator.Play in the FireAnimationEvents callback. If you know that the FireAnimationEvents callback is fired only after the State Machine Update and Process Graph functions execute, you can anticipate that your animation clip Animation data that can be used for animated characters or simple animations. It is a simple “unit” piece of motion, such as (one specific instance of) “Idle”, “Walk” or “Run”. More info
See in Glossary will play on the next frame, and not right away.

State Machine Update: All state machines are evaluated at this step in the execution sequence. This step occurs only if there is a controller component (for example, AnimatorController or AnimatorOverrideController or AnimatorControllerPlayable) in the animation graph.

Note: State machine evaluation is normally multithreaded, but adding certain callbacks (for example OnStateMachineEnter and OnStateMachineExit) disables multithreading. See Animation update loop above for details.

ProcessGraph: Evaluates all animation graphs. This includes sampling all animation clips that need to be evaluated, and computing Root Motion.

ProcessAnimation: Blends the results of the animation graph.

WriteTransforms: Writes all animated transforms to the scene from a worker thread.

A Humanoid rig with multiple layers that have IK pass enabled can have multiple WriteTransforms passes (See the Script Lifecycle Flowchart.

Отслеживание визуализации

Оптимизация невозможна без анализа данных. С помощью Navigation Timing API вы можете отследить каждый этап визуализации веб-страницы!

• С помощью Navigation Timing API можно получать детальные временные отметки для анализа визуализации.
• Браузер делит визуализацию на несколько этапов, названия которых можно использовать для анализа.

Стратегия оптимизации строится на анализе времени загрузки страниц. Его удобно проводить с помощью Navigation Timing API.

При загрузке страницы браузер отслеживает время, затраченное на каждый отмеченный на диаграмме этап. Обратите внимание, что мы пока не учитываем сетевые этапы. К ним вы вернемся в одном из следующих уроков.

А пока давайте выясним, что означают эти названия на диаграмме.

• domLoading. Начальная отметка. В этот момент браузер начинает анализировать первые байты HTML- документа.
• domInteractive. В это время браузер завершил анализ документа и создал модель DOM.
• domContentLoaded. К этому моменту модели DOM и CSSOM уже готовы, поэтому ничто не мешает запуску скриптов JavaScript. Это значит, что браузер может приступать к созданию модели визуализации.
• Если ваш фреймворк JavaScript запускается на этом этапе, вы можете отследить, как долго он выполняется, с помощью меток EventStart и EventEnd.

В спецификации HTML подробно оговаривается, когда каждое событие должно быть инифиировано, при каких условиях и т. д. Для анализа визуализации нам потребуются только следующие события:

• domInteractive. Модель DOM готова.
• domContentLoaded. Модели DOM и CSSOM готовы.
• Если в HTML-документе нет встроенного кода JavaScript, событие DOMContentLoaded инициируется сразу после domInteractive.

Этот код на первый взгляд может показаться пугающим, однако на самом деле все очень просто! Navigation Timing API записывает нужные временные отметки, дожидается инициации события onload (после завершения этапов domInteractive, domContentLoaded и domComplete) и вычисляет разницу во времени между отметками.

Теперь вы знаете, какие этапы визуализации нужно отслеживать и как вывести результаты на страницу. Кстати, вместо этого можно отправить данные на сервер (в Google Analytics это происходит автоматически), немного изменив код. Так вы сможете отслеживать скорость загрузки и определять, какие страницы необходимо оптимизировать.