Have you ever made a custom view using only canvas? Now have you ever tried to animate it? If you found that problematic this presentation will help you grasp basic stuff about animating custom drawn views.
Animation is created by rapidly displaying a sequence of images to create the illusion of movement. There are two main methods for automated animation updates in a window: the idle callback, which is invoked when no other events are happening, and the timer callback, which is invoked after a specified time period. A simple line animation example is provided using single buffer rendering, but it is hardware dependent and inconsistently speeds up and slows down. Using double buffering and a timer callback that redraws and reschedules itself every 30 milliseconds results in a smoother animated line.
This document discusses graphics and game development in Java ME. It covers the class hierarchy for graphics elements, using the Canvas class to draw graphics, handling events, and using the Game API including the GameCanvas class, layers, sprites and animation. Key topics include drawing with the Graphics object, coordinates, repainting, handling input events, implementing a game loop to control frame rate, and using the LayerManager and Sprite classes to implement layers and sprite animation.
The document discusses framerate independence in games using libGDX. It explains that using delta time ensures games run at the same speed regardless of framerate. It provides an example of moving an object at a constant speed of 1 pixel per frame by multiplying the object's speed by delta time. The document also covers creating and rendering animations in libGDX using the Animation class and TextureRegions. It provides tips on extending the Sprite class to create customized sprite objects and animate them by calling animate() each frame.
This document provides an overview of Qt animation frameworks, including timers, timelines, the animation framework, state machine framework, and graphics view framework. It describes the key classes used in each framework, such as QTimer for timers, QTimeLine for timelines, QPropertyAnimation for the animation framework, and QGraphicsScene/QGraphicsView for graphics view. Examples are provided for animating a button using each technique.
2D Graphics. Description of 2D graphic operations in Qt4. In this Chapter, you can learn how to handle the graphic scenes, views, and items in the Qt program.
The document introduces the animation engine in enchant.js. It provides 14 features for timeline-based animation, including movement effects like moveTo and moveBy, non-movement effects like fadeIn and fadeOut, timing controls like delay and loop, and easing functions to control the speed of movements over time. It demonstrates how to use these features through code examples to animate a bear sprite in different ways, like moving, scaling, fading, and chaining multiple effects together in a timeline.
This document discusses iOS app design and provides examples of using timers, UIViews, and NSMutableArrays. It covers:
- Using timers (NSTimer) for time-based tasks like clocks and stopwatches, and discusses timer accuracy.
- Common operations on UIView objects like tags and UISegmentedControl.
- Storing and accessing data in NSMutableArrays, as in a numbers game.
It then provides code samples for a basic timer, specifying individual timer objects, and accurately measuring elapsed time between points. Overall the document provides an overview and examples of fundamental iOS app components.
The document provides an overview of Qt's advanced graphics view and animation frameworks. It discusses the graphics view classes like QGraphicsItem, QGraphicsScene and QGraphicsView which provide a surface for managing and interacting with graphical items. It also covers the Qt property system and animation framework which allows modifying object properties over time to create animated transitions and GUIs.
Animation is created by rapidly displaying a sequence of images to create the illusion of movement. There are two main methods for automated animation updates in a window: the idle callback, which is invoked when no other events are happening, and the timer callback, which is invoked after a specified time period. A simple line animation example is provided using single buffer rendering, but it is hardware dependent and inconsistently speeds up and slows down. Using double buffering and a timer callback that redraws and reschedules itself every 30 milliseconds results in a smoother animated line.
This document discusses graphics and game development in Java ME. It covers the class hierarchy for graphics elements, using the Canvas class to draw graphics, handling events, and using the Game API including the GameCanvas class, layers, sprites and animation. Key topics include drawing with the Graphics object, coordinates, repainting, handling input events, implementing a game loop to control frame rate, and using the LayerManager and Sprite classes to implement layers and sprite animation.
The document discusses framerate independence in games using libGDX. It explains that using delta time ensures games run at the same speed regardless of framerate. It provides an example of moving an object at a constant speed of 1 pixel per frame by multiplying the object's speed by delta time. The document also covers creating and rendering animations in libGDX using the Animation class and TextureRegions. It provides tips on extending the Sprite class to create customized sprite objects and animate them by calling animate() each frame.
This document provides an overview of Qt animation frameworks, including timers, timelines, the animation framework, state machine framework, and graphics view framework. It describes the key classes used in each framework, such as QTimer for timers, QTimeLine for timelines, QPropertyAnimation for the animation framework, and QGraphicsScene/QGraphicsView for graphics view. Examples are provided for animating a button using each technique.
2D Graphics. Description of 2D graphic operations in Qt4. In this Chapter, you can learn how to handle the graphic scenes, views, and items in the Qt program.
The document introduces the animation engine in enchant.js. It provides 14 features for timeline-based animation, including movement effects like moveTo and moveBy, non-movement effects like fadeIn and fadeOut, timing controls like delay and loop, and easing functions to control the speed of movements over time. It demonstrates how to use these features through code examples to animate a bear sprite in different ways, like moving, scaling, fading, and chaining multiple effects together in a timeline.
This document discusses iOS app design and provides examples of using timers, UIViews, and NSMutableArrays. It covers:
- Using timers (NSTimer) for time-based tasks like clocks and stopwatches, and discusses timer accuracy.
- Common operations on UIView objects like tags and UISegmentedControl.
- Storing and accessing data in NSMutableArrays, as in a numbers game.
It then provides code samples for a basic timer, specifying individual timer objects, and accurately measuring elapsed time between points. Overall the document provides an overview and examples of fundamental iOS app components.
The document provides an overview of Qt's advanced graphics view and animation frameworks. It discusses the graphics view classes like QGraphicsItem, QGraphicsScene and QGraphicsView which provide a surface for managing and interacting with graphical items. It also covers the Qt property system and animation framework which allows modifying object properties over time to create animated transitions and GUIs.
The document discusses Qt's state machine framework, animations with state machines, touch events, and gestures. The state machine framework allows defining application states and transitions between states. Animations can be applied to state transitions. Touch events are delivered via QTouchEvent and widgets must accept them. Standard gestures like pan and swipe are provided, and custom gestures can be created by subclassing QGestureRecognizer.
The document discusses various methods from the async module in Node.js for controlling asynchronous callback flow, including:
1) Executing tasks in series or parallel, cascading tasks together, queuing tasks with concurrency control, iterating over arrays, mapping arrays, and reducing arrays.
2) Additional methods for filtering arrays based on an async truth test, and detecting the first value in an array that passes an async truth test.
3) Examples are provided for each method demonstrating how to use the async module to control asynchronous control flow in Node.js applications.
This sample offers insights of how qubit superpositions and entanglements are possible and how these are represented in statevectors, blockspheres and amplitudes when statevector representations are not possible
Options and trade offs for parallelism and concurrency in Modern C++Satalia
While threads have become a first class citizen in C++ since C++11, it is not always the case that they are the best abstraction to express parallelism where the objective is to speed up computations. OpenMP is a parallelism API for C/C++ and Fortran that has been around for a long time. Intel's Threading Building Blocks (TBB) is only a little bit more than 10 years old, but is very mature, and specifically for C++.
Mats will introduce OpenMP and TBB and their use in modern C++ and provide some best practices for them as well as try to predict what the C++ standard has in store for us when it comes to parallelism in the future.
The document discusses various techniques for improving OpenGL application performance, including using vertex buffer objects (VBOs) and vertex array objects (VAOs) to store vertex data in graphics memory. It provides an example of creating a cube using VBOs and VAOs to initialize vertex position and color data and load it into a VBO. Display lists are described as allowing geometry to be defined once and executed multiple times to improve performance for redrawing the same geometry. Frustum culling and scissoring are introduced as clipping techniques. General memory management techniques like avoiding frequent memory allocations in loops are also covered.
1. WinCAM 2.23 includes new functions for NC program initialization where the tool command can specify the first axis to move to the tool change position.
2. WinCAM 2.22 includes 3 new functions - NC program initialization, cut off cycle, and sample ini sections. The initialization allows automating tasks like tool setup, init blocks, and tool change positions. The cut off cycle provides a simple cycle accessed from the toolbar.
3. The document provides details on configuring and using the new functions in the wincam.ini file, including sections for program initialization, cut off cycles, and sample ini entries.
Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019 Unity Technologies
This session addresses how we are expanding the scope of the Burst Compiler to enable even the most demanding, hand-coded engine and gameplay problems to be expressed in HPC# via direct CPU intrinsics. Andreas shares the reasoning and use cases; as well as discussing implementation challenges, debugging, and performance along with comparisons to C++ code.
Speaker: Andreas Fredriksson - Unity
Watch the session on YouTube: https://youtu.be/BpwvXkoFcp8
The document discusses various OpenGL graphics techniques including viewports, depth buffering, handling input, using 3D models, drawing primitives, fog, displaying text, collision detection, picking objects, lens flares, and particle systems. Specifically, it provides code examples for setting the viewport, depth testing, handling keyboard input, loading and drawing 3D models, drawing spheres and cylinders using GLU functions, applying fog, displaying text, approximating collision detection using spheres, picking objects using the picking matrix, creating lens flares using the projection matrix, and generating particle systems for effects like dust and fire.
(5) cpp dynamic memory_arrays_and_c-stringsNico Ludwig
This document provides an overview of dynamic memory allocation in C++. It discusses the differences between automatic and dynamic arrays, and how dynamic arrays are allocated on the heap using functions like malloc() and free(). The key points covered are:
- Automatic arrays have a fixed size set at compile-time, while dynamic arrays can have a size determined at runtime by allocating memory on the heap.
- Malloc() is used to request a block of memory on the heap and return a void pointer to it, which must then be cast to the proper type.
- When dynamic memory is allocated, the pointer must be checked for null and the memory freed using free() to avoid memory leaks.
- Responsibility for
This document discusses techniques for creating skyboxes and terrain in OpenGL graphics. It explains how to create a skydome using skybox textures and then generate terrain by mapping height data from a heightmap texture onto a grid and rendering it with additional textures. Methods are provided for scaling, translating and drawing the terrain as well as querying the heightmap to position the camera above the terrain. Advanced techniques discussed include using quad trees for efficient searching, multitexturing, adding detail textures, and raycasting against the terrain.
1. The document discusses various aspects of user input and frame animation in libGDX, including touch input, keyboard input, gestures, the accelerometer, and sprite animation.
2. It explains how to set up input processing using InputProcessor and GestureDetector, and how to read touch, keyboard, and accelerometer values.
3. It also provides examples of creating sprite animations by splitting textures into frames and using the Animation class.
The document discusses various classes and APIs in MIDP related to timers, user interfaces, games, and graphics including the Timer class, GameCanvas, Sprite, TiledLayer, LayerManager, Font, and Image. It provides details on methods for each class and examples of how to use timers, animate sprites, detect collisions, and manage game layers. The document also covers basics of the record management system in MIDP.
Graphics View becomes one of the prominent features of Qt these days, it also serves as the backbone for next-generation user-interface developments. This talk highlights several tips and tricks which you can employ to beautify your Graphics View-based application, in order to have much more exciting and interesting user interactions. In addition, a new addition in Qt 4.6, namely the graphics effect feature, will be introduced and demonstrated.
Presentation by Ariya Hidayat held during Qt Developer Days 2009.
http://qt.nokia.com/developer/learning/elearning
Value network analysis of malawian legume systems - 2015Gcazo14
Value network analysis of Malawian legume systems: implication for institutional entrepreneurship.
Dr. Domenico Dentoni, Felix Krussmann
Presentation held at the First Mediterranean Conference on Food Supply and Distribution Systems - FAO, Rome, 6th July, 2015
Paper: https://www.researchgate.net/publication/278019581_Value_Network_Analysis_of_Malawian_Legume_Systems_Implications_for_Institutional_Entrepreneurship
Steven A. Ballmer is the Chief Executive Officer of Microsoft. Bipin P Pankhania has completed the requirements to be recognized as a Microsoft Certified Technology Specialist in SharePoint 2010 Application Development. He achieved this certification on December 26, 2012 with the certification number E113-7856.
INCLUSIVE DESIGN: Going beyond AccessibilityMichael Miles
People are not ones(1) and zeros(0) and the world is not just black and white. Everyone identifies themselves differently and while it may be impossible to cater to everyones needs, it is important that we strive to make our websites, applications and tools as inclusive as possible.
Inclusive Design is a form of accessibility. It is the concept of begin mindful in making technology available to and usable by all people whatever their abilities, age, economic situation, orientation, language, etc...
In this session we will talk about some of the ways to think about inclusive design on your projects and why it is important. We will discuss what questions and conversations to have with clients, what considerations to think about when planning the UX and design of your site and what architectural decisions to think about when building your site. Along the way we will look at examples of inclusive design in the wild and the benefits they offer.
Este curso online de 50 horas tiene como objetivo principal enseñar los conocimientos básicos sobre la concepción, grabación y emisión de programas de radio. El curso está destinado a personas que deseen iniciarse en el mundo de la radio y consta de 5 módulos que cubren temas como los tipos de programas radiales, la conducción de programas, la grabación digital, la emisión a través de FM, AM y formatos digitales, y las técnicas para la radio en directo.
Toxic Plastic Trash Drift in the North Pacific Subtropical Gyre Final PaperKameron Johnson
The document discusses plastic pollution in the North Pacific Subtropical Gyre. It notes that this region currently has the highest accumulation of microplastics compared to other subtropical gyres. The plastic debris comes from various sources like land pollution from North America, China, and Japan as well as lost or discarded fishing nets. Microplastics are ingested by marine life and can accumulate toxins, entering the food chain. More research is needed to understand the long term impacts on ecosystems and potential policy solutions to address plastic pollution at its source.
This document provides an overview of integrated marketing communications and its importance for automotive aftercare businesses. It discusses how applying Dave Brailsford's concept of "aggregated marginal gains" by improving every small component of a business by 1% can lead to significant overall improvements. Some key components of a business that must work together include physical aspects like location, workshop, and products as well as emotional aspects like appearance, pricing, advertising, and customer service. The document advocates taking each component of the "marketing wheel" and ensuring it is well-maintained and coordinated. It highlights research from Nielsen showing the top influences on customer actions, like recommendations from others and branded websites, and how focusing on improving these areas can increase sales and profitability
This document provides information on how to get pregnant naturally without medical intervention. It discusses understanding a woman's menstrual cycle and ovulation to have sex on the most fertile days between days 12-15 of the cycle. Signs of ovulation like changes in vaginal discharge or cervical position can help determine the fertile window. Adopting a holistic approach through a healthy diet, exercise, stress reduction and addressing lifestyle factors like smoking or drinking can also help increase chances of conceiving naturally. Both partners should ensure sperm quality through factors like wearing loose-fitting underwear.
Emission Reductions from Electric Cars Will Increase Every Year – Isn’t that ...Katy Kidwell
Running a car on electricity today in Massachusetts or Rhode Island results in far fewer emissions because the mix of resources on the grid is cleaner than burning gas and electric motors move a car more efficiently than gas engines. That means electric vehicles will be come greener and greener over time! Get one today.
The document discusses Qt's state machine framework, animations with state machines, touch events, and gestures. The state machine framework allows defining application states and transitions between states. Animations can be applied to state transitions. Touch events are delivered via QTouchEvent and widgets must accept them. Standard gestures like pan and swipe are provided, and custom gestures can be created by subclassing QGestureRecognizer.
The document discusses various methods from the async module in Node.js for controlling asynchronous callback flow, including:
1) Executing tasks in series or parallel, cascading tasks together, queuing tasks with concurrency control, iterating over arrays, mapping arrays, and reducing arrays.
2) Additional methods for filtering arrays based on an async truth test, and detecting the first value in an array that passes an async truth test.
3) Examples are provided for each method demonstrating how to use the async module to control asynchronous control flow in Node.js applications.
This sample offers insights of how qubit superpositions and entanglements are possible and how these are represented in statevectors, blockspheres and amplitudes when statevector representations are not possible
Options and trade offs for parallelism and concurrency in Modern C++Satalia
While threads have become a first class citizen in C++ since C++11, it is not always the case that they are the best abstraction to express parallelism where the objective is to speed up computations. OpenMP is a parallelism API for C/C++ and Fortran that has been around for a long time. Intel's Threading Building Blocks (TBB) is only a little bit more than 10 years old, but is very mature, and specifically for C++.
Mats will introduce OpenMP and TBB and their use in modern C++ and provide some best practices for them as well as try to predict what the C++ standard has in store for us when it comes to parallelism in the future.
The document discusses various techniques for improving OpenGL application performance, including using vertex buffer objects (VBOs) and vertex array objects (VAOs) to store vertex data in graphics memory. It provides an example of creating a cube using VBOs and VAOs to initialize vertex position and color data and load it into a VBO. Display lists are described as allowing geometry to be defined once and executed multiple times to improve performance for redrawing the same geometry. Frustum culling and scissoring are introduced as clipping techniques. General memory management techniques like avoiding frequent memory allocations in loops are also covered.
1. WinCAM 2.23 includes new functions for NC program initialization where the tool command can specify the first axis to move to the tool change position.
2. WinCAM 2.22 includes 3 new functions - NC program initialization, cut off cycle, and sample ini sections. The initialization allows automating tasks like tool setup, init blocks, and tool change positions. The cut off cycle provides a simple cycle accessed from the toolbar.
3. The document provides details on configuring and using the new functions in the wincam.ini file, including sections for program initialization, cut off cycles, and sample ini entries.
Intrinsics: Low-level engine development with Burst - Unite Copenhagen 2019 Unity Technologies
This session addresses how we are expanding the scope of the Burst Compiler to enable even the most demanding, hand-coded engine and gameplay problems to be expressed in HPC# via direct CPU intrinsics. Andreas shares the reasoning and use cases; as well as discussing implementation challenges, debugging, and performance along with comparisons to C++ code.
Speaker: Andreas Fredriksson - Unity
Watch the session on YouTube: https://youtu.be/BpwvXkoFcp8
The document discusses various OpenGL graphics techniques including viewports, depth buffering, handling input, using 3D models, drawing primitives, fog, displaying text, collision detection, picking objects, lens flares, and particle systems. Specifically, it provides code examples for setting the viewport, depth testing, handling keyboard input, loading and drawing 3D models, drawing spheres and cylinders using GLU functions, applying fog, displaying text, approximating collision detection using spheres, picking objects using the picking matrix, creating lens flares using the projection matrix, and generating particle systems for effects like dust and fire.
(5) cpp dynamic memory_arrays_and_c-stringsNico Ludwig
This document provides an overview of dynamic memory allocation in C++. It discusses the differences between automatic and dynamic arrays, and how dynamic arrays are allocated on the heap using functions like malloc() and free(). The key points covered are:
- Automatic arrays have a fixed size set at compile-time, while dynamic arrays can have a size determined at runtime by allocating memory on the heap.
- Malloc() is used to request a block of memory on the heap and return a void pointer to it, which must then be cast to the proper type.
- When dynamic memory is allocated, the pointer must be checked for null and the memory freed using free() to avoid memory leaks.
- Responsibility for
This document discusses techniques for creating skyboxes and terrain in OpenGL graphics. It explains how to create a skydome using skybox textures and then generate terrain by mapping height data from a heightmap texture onto a grid and rendering it with additional textures. Methods are provided for scaling, translating and drawing the terrain as well as querying the heightmap to position the camera above the terrain. Advanced techniques discussed include using quad trees for efficient searching, multitexturing, adding detail textures, and raycasting against the terrain.
1. The document discusses various aspects of user input and frame animation in libGDX, including touch input, keyboard input, gestures, the accelerometer, and sprite animation.
2. It explains how to set up input processing using InputProcessor and GestureDetector, and how to read touch, keyboard, and accelerometer values.
3. It also provides examples of creating sprite animations by splitting textures into frames and using the Animation class.
The document discusses various classes and APIs in MIDP related to timers, user interfaces, games, and graphics including the Timer class, GameCanvas, Sprite, TiledLayer, LayerManager, Font, and Image. It provides details on methods for each class and examples of how to use timers, animate sprites, detect collisions, and manage game layers. The document also covers basics of the record management system in MIDP.
Graphics View becomes one of the prominent features of Qt these days, it also serves as the backbone for next-generation user-interface developments. This talk highlights several tips and tricks which you can employ to beautify your Graphics View-based application, in order to have much more exciting and interesting user interactions. In addition, a new addition in Qt 4.6, namely the graphics effect feature, will be introduced and demonstrated.
Presentation by Ariya Hidayat held during Qt Developer Days 2009.
http://qt.nokia.com/developer/learning/elearning
Value network analysis of malawian legume systems - 2015Gcazo14
Value network analysis of Malawian legume systems: implication for institutional entrepreneurship.
Dr. Domenico Dentoni, Felix Krussmann
Presentation held at the First Mediterranean Conference on Food Supply and Distribution Systems - FAO, Rome, 6th July, 2015
Paper: https://www.researchgate.net/publication/278019581_Value_Network_Analysis_of_Malawian_Legume_Systems_Implications_for_Institutional_Entrepreneurship
Steven A. Ballmer is the Chief Executive Officer of Microsoft. Bipin P Pankhania has completed the requirements to be recognized as a Microsoft Certified Technology Specialist in SharePoint 2010 Application Development. He achieved this certification on December 26, 2012 with the certification number E113-7856.
INCLUSIVE DESIGN: Going beyond AccessibilityMichael Miles
People are not ones(1) and zeros(0) and the world is not just black and white. Everyone identifies themselves differently and while it may be impossible to cater to everyones needs, it is important that we strive to make our websites, applications and tools as inclusive as possible.
Inclusive Design is a form of accessibility. It is the concept of begin mindful in making technology available to and usable by all people whatever their abilities, age, economic situation, orientation, language, etc...
In this session we will talk about some of the ways to think about inclusive design on your projects and why it is important. We will discuss what questions and conversations to have with clients, what considerations to think about when planning the UX and design of your site and what architectural decisions to think about when building your site. Along the way we will look at examples of inclusive design in the wild and the benefits they offer.
Este curso online de 50 horas tiene como objetivo principal enseñar los conocimientos básicos sobre la concepción, grabación y emisión de programas de radio. El curso está destinado a personas que deseen iniciarse en el mundo de la radio y consta de 5 módulos que cubren temas como los tipos de programas radiales, la conducción de programas, la grabación digital, la emisión a través de FM, AM y formatos digitales, y las técnicas para la radio en directo.
Toxic Plastic Trash Drift in the North Pacific Subtropical Gyre Final PaperKameron Johnson
The document discusses plastic pollution in the North Pacific Subtropical Gyre. It notes that this region currently has the highest accumulation of microplastics compared to other subtropical gyres. The plastic debris comes from various sources like land pollution from North America, China, and Japan as well as lost or discarded fishing nets. Microplastics are ingested by marine life and can accumulate toxins, entering the food chain. More research is needed to understand the long term impacts on ecosystems and potential policy solutions to address plastic pollution at its source.
This document provides an overview of integrated marketing communications and its importance for automotive aftercare businesses. It discusses how applying Dave Brailsford's concept of "aggregated marginal gains" by improving every small component of a business by 1% can lead to significant overall improvements. Some key components of a business that must work together include physical aspects like location, workshop, and products as well as emotional aspects like appearance, pricing, advertising, and customer service. The document advocates taking each component of the "marketing wheel" and ensuring it is well-maintained and coordinated. It highlights research from Nielsen showing the top influences on customer actions, like recommendations from others and branded websites, and how focusing on improving these areas can increase sales and profitability
This document provides information on how to get pregnant naturally without medical intervention. It discusses understanding a woman's menstrual cycle and ovulation to have sex on the most fertile days between days 12-15 of the cycle. Signs of ovulation like changes in vaginal discharge or cervical position can help determine the fertile window. Adopting a holistic approach through a healthy diet, exercise, stress reduction and addressing lifestyle factors like smoking or drinking can also help increase chances of conceiving naturally. Both partners should ensure sperm quality through factors like wearing loose-fitting underwear.
Emission Reductions from Electric Cars Will Increase Every Year – Isn’t that ...Katy Kidwell
Running a car on electricity today in Massachusetts or Rhode Island results in far fewer emissions because the mix of resources on the grid is cleaner than burning gas and electric motors move a car more efficiently than gas engines. That means electric vehicles will be come greener and greener over time! Get one today.
This lesson plan outlines learning about media codes and conventions. Students will analyze visual media like film trailers to understand how meaning is communicated through images and the "language" of different mediums. They will discuss what codes and conventions are, such as the accepted plot structures and character types of different genres. As an assignment, students will work in groups to design and pitch their own TV drama by developing the plot, characters, setting, and explaining how it fits the codes and conventions of the chosen genre.
Historia de México I: Bloque I.- Categorías teórico-metodológicas para el est...Moishef HerCo
Este documento presenta los bloques temáticos de un curso de Historia de México I para el segundo semestre de bachillerato. Incluye secciones sobre categorías teórico-metodológicas para el estudio de la historia, escuelas de interpretación histórica, poblamiento de América, procesos culturales de las sociedades mexicanas antiguas, la conquista de México, vida durante el virreinato, y el proceso de la guerra de independencia. También define conceptos históricos como espacio, tiempo, estructura,
The document discusses creating and animating custom views in Android. It covers topics like why to use custom views, the View class hierarchy, drawing and styling custom views, and different techniques for animating views including using Runnables, ValueAnimators, and ObjectAnimators. Key points include how to subclass View, override drawing methods like onDraw(), apply XML styling attributes, and animate view properties over time through interpolation of values.
I wanted to change the cloudsrectangles into an actuall image it do.pdffeelinggifts
I wanted to change the clouds/rectangles into an actuall image it doesnt matter the image.
import javax.swing.*;
import java.awt.*;
/**
* Created by Thomas on 11/27/2016.
*/
public class Renderer extends JPanel{
//private static final long serialVersionUID = 1L;
protected void paintComponent(Graphics g) {
Main.main.repaint(g);
}
public static int clamp(int greenValue, int i, int j) {
// TODO Auto-generated method stub
return 0;
}
}
OTHER PART:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
/**
* Created by Thomas on 11/27/2016.
*/
public class Main implements ActionListener, KeyListener{
public static Main main;
public final int WIDTH = 1400;
public final int HEIGHT = 600;
public HUD Hud;
public Renderer renderer;
public Rectangle character;
public ArrayList cloud;
public Random rand;
public boolean start = false, gameover = false;
public int tick;
public Main() {
JFrame jFrame = new JFrame();
Timer timer = new Timer(20, this);
renderer = new Renderer();
rand = new Random();
jFrame.setTitle(\"Example\");
jFrame.add(renderer);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(WIDTH, HEIGHT);
jFrame.addKeyListener(this);
jFrame.setVisible(true);
cloud = new ArrayList();
character = new Rectangle(200, 220, 20, 20);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
timer.start();
}
public void repaint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0,0, WIDTH, HEIGHT);
g.setColor(Color.blue);
g.fillRect(0, HEIGHT - 100, WIDTH, 100);
g.setColor(Color.green);
g.fillRect(character.x, character.y, character.width, character.height);
if (character.y >= HEIGHT - 100 || character.y < 0) {
gameover = true;
}
for (Rectangle rect : cloud) {
g.setColor(Color.white);
g.fillRect(rect.x, rect.y, rect.width, rect.height);
}
g.setColor(Color.WHITE);
g.setFont(new Font(\"Times New Roman\", 1 ,100));
if (!start) {
g.drawString(\"Press to start!\", 450, HEIGHT / 2);
}
else if (gameover) {
g.drawString(\"Game Over!\", 450, HEIGHT / 2);
}
}
public void addCloud(boolean start) {
int width = 400;
int height = 200;
if (start) {
cloud.add(new Rectangle(WIDTH + width + cloud.size() * 300, rand.nextInt(HEIGHT-120),
80, 100));
}
else {
cloud.add(new Rectangle(cloud.get(cloud.size() - 1).x + 300, rand.nextInt(HEIGHT-120), 80,
100));
}
}
public void flap() {
if (gameover) {
character = new Rectangle(300, 400, 40, 40);
cloud.clear();
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
addCloud(true);
gameover = false;
}
if (!start) {
start = true;
}
else if (!gameover) {
character.y -= 70;
tick = 0;
}
}
@Override
public void actionPerformed(ActionEvent e) {
int speed = 15;
//System.out.println(\"Space\");
if (start) {
for (int i = 0; i .
ITT 2014 - Chris Eidhof - Practical Concurrent ProgrammingIstanbul Tech Talks
This document discusses concurrency and threading concepts in iOS development. It provides recipes for moving drawing code to background threads to improve performance, loading data from networks efficiently using Grand Central Dispatch and NSURLSession, and importing data into Core Data in batches to reduce memory usage. It also covers how to make objects thread-safe when accessed concurrently, such as using locks or dispatch queues to synchronize access. The goal is to explain common concurrency patterns and challenges in order to write better multithreaded applications.
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
SurfaceViews allow drawing to a separate thread to achieve realtime performance. Key aspects include:
- Driving the SurfaceView with a thread that locks and draws to the canvas in a loop.
- Using input buffering and object pooling to efficiently process touch/key events from the main thread.
- Employing various timing and drawing techniques like fixed scaling to optimize for performance. Managing the SurfaceView lifecycle to ensure the drawing thread starts and stops appropriately.
The document provides explanations of various graphics functions from the graphics.h library in C language. It discusses functions for initializing graphics mode, drawing basic shapes like lines, rectangles, circles, getting and setting colors, reading and writing pixel values, loading and saving bitmap images, handling events and cleaning up graphics memory. It also includes code snippets to demonstrate drawing a rectangle, smiley and star using these graphics functions.
This document provides an overview and introduction to building a basic fraction calculator app in Objective-C. It begins with an overview of the project architecture using the MVC pattern with a Fraction model class to represent fractions, a Calculator class to perform operations, and a ViewController class to manage the user interface. It then details the implementation of each class, including the Fraction class with methods for creating, modifying, and performing operations on fractions, the Calculator class for setting operands and performing operations, and the ViewController class for handling user interface events and updating the display.
This document discusses different approaches for implementing multithreaded graphics in Java, including: redrawing everything in paint, having other routines draw directly on the window, overriding update to do incremental painting, and using double buffering. It provides code examples for each approach and discusses their advantages and disadvantages in terms of flicker, efficiency, and handling overlapping graphics. It also covers using timers to control animations.
The document discusses different animation systems available in Android including view animation, property animation, and drawable animation. View animation allows animating views and can translate, scale, rotate, and change opacity. Property animation applies animations to object properties and offers more flexibility. Drawable animation displays sequential drawables to create animation.
Java 8 was released in 2014 and introduced many new features including lambda expressions, default methods on interfaces, streams, date/time API improvements and more. Some key updates were the addition of lambda expressions to support functional programming, default and static methods on interfaces to allow interface evolution, and streams to provide a powerful abstraction for processing collections of elements. The date/time API was also overhauled, drawing inspiration from Joda-Time to provide an immutable and more logically structured date/time library.
Presented at All Things Open 2022
Presented by Danny McCormick
Title: Streaming Data Pipelines With Apache Beam
Abstract: Handling big data presents big problems. Along with traditional concerns like scalability and performance, the increasingly common need for live streaming data processing introduces problems like late or incomplete data from flaky data sources. Apache Beam is an open source, unified model for defining both batch and streaming data-parallel processing pipelines that addresses these challenges. Using one of the open source Beam SDKs, you can build a program that defines a pipeline to be executed by one of Beam’s supported distributed processing back-ends, which include Apache Flink, Apache Spark, and Google Cloud Dataflow.
This talk will explore some problems associated with processing large datasets at scale and how you can write Apache Beam pipelines that address those issues. It will include a demo of a basic Beam streaming pipeline.
Takeaways: an understanding of some challenges associated with large datasets, the Apache Beam model, and how to write a basic Beam streaming pipeline
Audience: anyone dealing with big datasets or interested in data processing at scale.
For all who wish to learn c graphics programming, no knowledge of graphics concepts is required. C Graphics programming is very easy and interesting. You can use graphics programming for developing your own games, in making projects, for animation etc. It's not like traditional C programming in which you have to apply complex logic in your program and then you end up with a lot of errors and warnings in your program. In C graphics programming you have to use standard library functions ( need not worry if you don't know functions ) to get your task done. Just you pass arguments to the functions and it's done. On this website you will find almost all functions with detailed explanation and a sample program showing the usage of a function. To make things easy you are provided with executable files which you can download and execute. Firstly you should know the function initgraph which is used to initialize the graphics mode . To initialize graphics mode we use initgraph function in our program. initgraph function is present in "graphics.h" header file, so your every graphics program should include "graphics.h" header file. We will discuss initgraph withe help of following sample program:-
This document discusses creating a web-based rotoscoping tool using HTML5 canvas. It proposes allowing users to place shapes over video frames and edit them to create light saber-like effects. Key features would include acquiring video, drawing closed shapes frame-by-frame, reviewing the output, and exporting results. Technical approaches covered include using canvas drawings over video playback, saving frame data to localStorage, and potential improvements like a database backend.
The document discusses computer graphics and the OpenGL rendering process. It describes the graphics pipeline which processes vertex data through various shader stages before fragments are rendered to the screen. These stages include vertex shading, tessellation, geometry processing, clipping, and fragment shading. OpenGL is introduced as a cross-platform graphics API that utilizes these shader programs to leverage the parallel processing capabilities of GPUs. Basic concepts like buffers, shaders, and drawing objects are also covered.
The document discusses high performance websites, introducing xDebug profiling, Kcachegrind, and JMeter. It provides instructions for installing necessary software on a virtual machine, including Apache, xDebug, JMeter, and Kcachegrind. The document then demonstrates how to use these tools to optimize website performance, including profiling a sample extension in TYPO3, identifying optimization opportunities, and implementing caching. Finally, it shows how to test website performance using JMeter, including building test plans, recording tests, distributed testing on Amazon EC2, and analyzing results.
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
NDC Sydney 2019 conference in Sydney, AU - 2019/10/15
Talk: War stories from .NET team by Karel Zikmund
https://sessionize.com/s/karel-zikmund/async-demystified/24175
https://www.youtube.com/watch?v=TgUYcZV-foM
Weather service, maps and navigation, photo viewer, instant messaging, web browser, flick list or kinetic scrolling. You want all these with Qt? You get it!
Presentation by Ariya Hidayat held during Qt Developer Days 2009.
http://qt.nokia.com/developer/learning/elearning
This document provides information about graphics functions in C. It begins by explaining graphics modes and how images are displayed on screens using pixels. It then provides details on the initgraph() function which initializes the graphics system. The rest of the document summarizes many common graphics functions like line(), rectangle(), circle(), putpixel(), getpixel() and more, explaining what they do and their parameters.
Similar to Breathing the life into the canvas (20)
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesChristina Lin
Traditionally, dealing with real-time data pipelines has involved significant overhead, even for straightforward tasks like data transformation or masking. However, in this talk, we’ll venture into the dynamic realm of WebAssembly (WASM) and discover how it can revolutionize the creation of stateless streaming pipelines within a Kafka (Redpanda) broker. These pipelines are adept at managing low-latency, high-data-volume scenarios.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
Comparative analysis between traditional aquaponics and reconstructed aquapon...bijceesjournal
The aquaponic system of planting is a method that does not require soil usage. It is a method that only needs water, fish, lava rocks (a substitute for soil), and plants. Aquaponic systems are sustainable and environmentally friendly. Its use not only helps to plant in small spaces but also helps reduce artificial chemical use and minimizes excess water use, as aquaponics consumes 90% less water than soil-based gardening. The study applied a descriptive and experimental design to assess and compare conventional and reconstructed aquaponic methods for reproducing tomatoes. The researchers created an observation checklist to determine the significant factors of the study. The study aims to determine the significant difference between traditional aquaponics and reconstructed aquaponics systems propagating tomatoes in terms of height, weight, girth, and number of fruits. The reconstructed aquaponics system’s higher growth yield results in a much more nourished crop than the traditional aquaponics system. It is superior in its number of fruits, height, weight, and girth measurement. Moreover, the reconstructed aquaponics system is proven to eliminate all the hindrances present in the traditional aquaponics system, which are overcrowding of fish, algae growth, pest problems, contaminated water, and dead fish.
A review on techniques and modelling methodologies used for checking electrom...nooriasukmaningtyas
The proper function of the integrated circuit (IC) in an inhibiting electromagnetic environment has always been a serious concern throughout the decades of revolution in the world of electronics, from disjunct devices to today’s integrated circuit technology, where billions of transistors are combined on a single chip. The automotive industry and smart vehicles in particular, are confronting design issues such as being prone to electromagnetic interference (EMI). Electronic control devices calculate incorrect outputs because of EMI and sensors give misleading values which can prove fatal in case of automotives. In this paper, the authors have non exhaustively tried to review research work concerned with the investigation of EMI in ICs and prediction of this EMI using various modelling methodologies and measurement setups.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Sinan KOZAK
Sinan from the Delivery Hero mobile infrastructure engineering team shares a deep dive into performance acceleration with Gradle build cache optimizations. Sinan shares their journey into solving complex build-cache problems that affect Gradle builds. By understanding the challenges and solutions found in our journey, we aim to demonstrate the possibilities for faster builds. The case study reveals how overlapping outputs and cache misconfigurations led to significant increases in build times, especially as the project scaled up with numerous modules using Paparazzi tests. The journey from diagnosing to defeating cache issues offers invaluable lessons on maintaining cache integrity without sacrificing functionality.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELgerogepatton
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
3. Intro
● Why custom views?
● Not everything can be solved with standard views
● We want to draw directly onto the Canvas
● Graphs and diagrams
● External data from sensors and mic (equalizer)
● ….
4.
5. Couple of advices 1 / 3 - Initialize paints early
public final class StaticGraph extends View {
public StaticGraph(final Context context) {
super(context);
init();
}
public StaticGraph(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
public StaticGraph(final Context context, final AttributeSet attrs, final
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
…..
6. Couple of advices 1 / 3 - Initialize paints early
private void init() {
axisPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
axisPaint.setColor(Color.BLACK);
axisPaint.setStyle(Paint.Style.STROKE);
axisPaint.setStrokeWidth(4.0f);
…..
}
7. Couple of advices 2 / 3 - Memorize all the measures necessary to draw early
private PointF xAxisStart;
private PointF xAxisEnd;
private PointF yAxisStart;
private PointF yAxisEnd;
……..
@Override
protected void onSizeChanged(final int width, final int height,
final int oldWidth, final int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
calculateAxis(width, height);
calculateDataPoints(width, height);
}
8. Couple of advices 3 / 3 - Use onDraw only to draw
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(xAxisStart.x, xAxisStart.y, xAxisEnd.x, xAxisEnd.y, axisPaint);
canvas.drawLine(yAxisStart.x, yAxisStart.y, yAxisEnd.x, yAxisEnd.y, axisPaint);
….
canvas.drawPath(graphPath, graphPaint);
}
10. ● Every view is a set of states
● State can be represented as a point in a state space
● Animation is a change of state through time
A bit of philosophy
Animating custom views
11. Animating custom views
Let’s start with simple example - just a dot
● State contains only two pieces of information, X and Y position
● We change X and Y position through time
12.
13. Animating custom views
The recipe
● Determine important constants
● Initialize paints and other expensive objects
● (Re)calculate size dependent stuff on size changed
● Implement main loop
● Calculate state
● Draw
14. Determine important constants
private static final long UI_REFRESH_RATE = 60L; // fps
private static final long ANIMATION_REFRESHING_INTERVAL = TimeUnit.SECONDS.toMillis(1L) / UI_REFRESH_RATE; //
millis
private static final long ANIMATION_DURATION_IN_MILLIS = 1500L; // millis
private static final long NUMBER_OF_FRAMES = ANIMATION_DURATION_IN_MILLIS /
ANIMATION_REFRESHING_INTERVAL;
15. Animating custom views
Determine important constants
● For animation that lasts 1500 milliseconds in framerate of 60 fps...
● We should refresh the screen every cca 16 milliseconds
● And we have cca 94 frames
16. Initialize paints and other expensive objects - business as usual
private void init() {
dotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
dotPaint.setColor(Color.RED);
dotPaint.setStyle(Paint.Style.FILL);
dotPaint.setStrokeWidth(1.0f);
endPointPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
endPointPaint.setColor(Color.GREEN);
endPointPaint.setStyle(Paint.Style.FILL);
endPointPaint.setStrokeWidth(1.0f);
}
17. (Re)calculate size dependent stuff on size changed
@Override
protected void onSizeChanged(final int width, final int height, final int oldWidth, final int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
startPoint = new PointF(width / 4.0f, height * 3.0f / 4.0f);
endPoint = new PointF(width * 3.0f / 4.0f, height / 4.0f);
….
}
18. Implement main loop
private final Handler uiHandler = new Handler(Looper.getMainLooper());
private void startAnimating() {
calculateFrames();
uiHandler.post(invalidateUI);
}
private void stopAnimating() {
uiHandler.removeCallbacks(invalidateUI);
}
19. Implement main loop
private Runnable invalidateUI = new Runnable() {
@Override
public void run() {
if (hasFrameToDraw()) {
invalidate();
uiHandler.postDelayed(this, ANIMATION_REFRESHING_INTERVAL);
} else {
isAnimating = false;
}
}
};
20. Calculate state
● Create frames array
● Determine step by which state changes
● Increase positions by step
Animating custom views
21. Calculate state
private void calculateFrames() {
frames = new PointF[NUMBER_OF_FRAMES + 1];
….
float x = animationStartPoint.x;
float y = animationStartPoint.y;
for (int i = 0; i < NUMBER_OF_FRAMES; i++) {
frames[i] = new PointF(x, y);
x += xStep;
y += yStep;
}
frames[frames.length - 1] = new PointF(animationEndPoint.x, animationEndPoint.y);
currentFrame = 0;
}
22. Animating custom views
Draw
● Now piece of cake
● Draw static stuff
● Take and draw current frame
● Increase the counter
24. Now we want to animate the graph from one state to another
25. Animating custom views
Now we to animate the graph from one state to another
Recipe is the same, state more complicated
Dot state:
private PointF[] frames;
Graph state:
private PointF[][] framesDataPoints;
private float[] framesAxisZoom;
private int[] framesColor;
27. Easing in and out
● Easing in - accelerating from the origin
● Easing out - decelerating to the destination
● Accelerate, hit the inflection point, decelerate to the destination
● Again - dot as an example
28. Easing in and out
Easing out (deceleration)
● Differences while calculating frames
● Replace linear trajectory with quadratic
● The step that we used in first animation isn’t valid anymore
float x = animationStartPoint.x;
float y = animationStartPoint.y;
for (int i = 0; i < NUMBER_OF_FRAMES; i++) {
frames[i] = new PointF(x, y);
x += xStep;
y += yStep;
}
30. ….gives us the following formula:
Xi = (- L / N^2) * i^2 + (2 * L / N) * i
● Xi - position (state) for the ith frame
● L - length of the dot trajectory
● N - number of frames
● i - order of the frame
31. The rest of the recipe is same:
● Calculation phase modified to use previous formula
final float aX = -pathLengthX / (NUMBER_OF_FRAMES * NUMBER_OF_FRAMES);
final float bX = 2 * pathLengthX / NUMBER_OF_FRAMES;
final float aY = -pathLengthY / (NUMBER_OF_FRAMES * NUMBER_OF_FRAMES);
final float bY = 2 * pathLengthY / NUMBER_OF_FRAMES;
for (int i = 0; i < NUMBER_OF_FRAMES; i++) {
final float x = calculateFunction(aX, bX, i, animationStartPoint.x);
final float y = calculateFunction(aY, bY, i, animationStartPoint.y);
frames[i] = new PointF(x, y);
}
private float calculateFunction(final float a, final float b, final int i, final float origin) {
return a * i * i + b * i + origin;
}
32. Easing in (acceleration)
● Same approach
● Different starting conditions - initial velocity zero
● Renders a bit different formula
33. Acceleration and deceleration in the same time
● Things more complicated (but not a lot)
● Use cubic formula instead of quadratic
● Again some high school math - sorry :(
34. The magic formula:
Xi = (- 2 * L / N^3) * i^3 + (3 * L) / N^2 * i^2
● Xi - position (state) for the ith frame
● L - length of the dot trajectory
● N - number of frames
● i - order of the frame
● Same as quadratic interpolation, slightly different constants and powers
35. Easing in and out
Graph example
● Again: Use same formulas, but on a more complicated state
37. Dynamic frame calculation
Actually 2 approaches for calculating state
● Pre-calculate all the frames (states) - we did this
● Calculate the next frame from the current one dynamically
38. Dynamic frame calculation
Pre-calculate all the frames (states)
● All the processing done at the beginning of the animation
● Everything is deterministic and known in advance
● Easy to determine when to stop the animation
● Con: takes more space - 94 positions in our example
39. Dynamic frame calculation
Dynamic state calculation
● Calculate the new state from the previous one every loop iteration
● Something like a mini game engine / physics simulator
● Wastes far less space
● Behaviour more realistic
● Con: if calculation is heavy frames could drop
● Respect sacred window of 16 (or less) milliseconds
40. Dynamic frame calculation
● First example - a dot that bounces off the walls
● Never-ending animation - duration isn’t determined
● Consequently we don’t know number of frames up-
front
● Perfect for using dynamic frame calculation
● Twist in our recipe
41. Dynamic frame calculation
The recipe
● Determine important constants - the same
● Initialize paints and other expensive objects - the same
● (Re)calculate size dependent stuff on size changed - the same
● Implement main loop - move frame calculation to drawing phase
● Calculate state - different
● Draw - almost the same
42. Implement the main loop
private final Handler uiHandler = new Handler(Looper.getMainLooper());
private void startAnimating() {
calculateFrames();
uiHandler.post(invalidateUI);
}
private void stopAnimating() {
uiHandler.removeCallbacks(invalidateUI);
}
43. Implement the main loop
private Runnable invalidateUI = new Runnable() {
@Override
public void run() {
if (hasFrameToDraw()) {
invalidate();
uiHandler.postDelayed(this, ANIMATION_REFRESHING_INTERVAL);
} else {
isAnimating = false;
}
}
};
44. Implement the main loop
private void startAnimating() {
uiHandler.post(invalidateUI);
}
private void stopAnimating() {
uiHandler.removeCallbacks(invalidateUI);
}
private Runnable invalidateUI = new Runnable() {
@Override
public void run() {
invalidate();
uiHandler.postDelayed(this, ANIMATION_REFRESHING_INTERVAL);
}
};
47. Calculate state
private void updateWorld() {
final float dx = currentVelocity.x; // * dt
final float dy = currentVelocity.y; // * dt
currentPosition.set(currentPosition.x + dx, currentPosition.y + dy);
if (hitRightWall()) {
currentVelocity.x = -currentVelocity.x;
currentPosition.set(topRight.x - WALL_THICKNESS, currentPosition.y);
}
//Same for every wall
}
private boolean hitRightWall() {
return currentPosition.x >= topRight.x - WALL_THICKNESS;
}
48. Dynamic frame calculation
Add gravity to previous example
● Just a couple of lines more
private void updateWorld() {
final float dvx = GRAVITY.x;
final float dvy = GRAVITY.y;
currentVelocity.set(currentVelocity.x + dvx, currentVelocity.y + dvy);
final float dx = currentVelocity.x; // * dt
final float dy = currentVelocity.y; // * dt
currentPosition.set(currentPosition.x + dx, currentPosition.y + dy);
…..
}
49. Springs
● Define a circle of given radius
● Define couple of control points with random
distance from the circle
● Let control points spring around the circle
50. private void updateWorld() {
final int angleStep = 360 / NUMBER_OD_CONTROL_POINTS;
for (int i = 0; i < controlPoints.length; i++) {
final PointF point = controlPoints[i];
final PointF velocity = controlPointsVelocities[i];
final PointF springCenter = CoordinateUtils.fromPolar((int) radius, i * angleStep, centerPosition);
final float forceX = -SPRING_CONSTANT * (point.x - springCenter.x);
final float forceY = -SPRING_CONSTANT * (point.y - springCenter.y);
final float dvx = forceX;
final float dvy = forceY;
velocity.set(velocity.x + dvx, velocity.y + dvy);
final float dx = velocity.x;
final float dy = velocity.y;
point.set(point.x + dx, point.y + dy);
}
}
51. Dynamic frame calculation
Usefulness of those animations
● Not very useful per se
● Use springs to snap the objects from one position to another
● Use gravity to collapse the scene
● You can simulate other scene properties instead of position such as color,
scale, etc...
53. Animating external input
● It sometimes happens that your state doesn’t depend only on internal
factors, but also on external
● For example equalizer
● Input is sound in fft (fast Fourier transform) data form
● Run data through the “pipeline” of transformations to get something that
you can draw
● The recipe is similar to the precalculation style, but animation isn’t
triggered by button push, but with new sound data arrival
54. Main loop - just invalidating in 60 fps
private void startAnimating() {
uiHandler.post(invalidateUI);
}
private void stopAnimating() {
uiHandler.removeCallbacks(invalidateUI);
}
private Runnable invalidateUI = new Runnable() {
@Override
public void run() {
invalidate();
uiHandler.postDelayed(this, ANIMATION_REFRESHING_INTERVAL);
}
};
55. Data input
private static final int SOUND_CAPTURE_RATE = 20; // Hz
private void startCapturingAudioSamples(int audioSessionId) {
visualizer = new Visualizer(audioSessionId);
visualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
visualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {
@Override
public void onWaveFormDataCapture(Visualizer visualizer, byte[] waveform, int samplingRate) {
}
@Override
public void onFftDataCapture(Visualizer visualizer, byte[] fft, int samplingRate) {
calculateData(fft);
}
}, SOUND_CAPTURE_RATE * 1000, false, true);
visualizer.setEnabled(true);
}
Triggered 20 times in a second
56. Transforming data
private void calculateData(byte[] bytes) {
final int[] truncatedData = truncateData(bytes);
final int[] magnitudes = calculateMagnitudes(truncatedData);
final int[] outerScaledData = scaleData(magnitudes, OUTER_SCALE_TARGET);
final int[] innerScaledData = scaleData(magnitudes, INNER_SCALE_TARGET);
final int[] outerAveragedData = averageData(outerScaledData);
final int[] innerAveragedData = averageData(innerScaledData);
this.outerPoints = calculateContours(outerPoints, outerAveragedData, OUTER_OFFSET, true);
this.innerPoints = calculateContours(innerPoints, innerAveragedData, INNER_OFFSET, false);
currentFrame = 0;
}
This is now drawable
57. Animating external input
Important!!! - interpolation
● Data arrives 20 times a second
● We want to draw 60 times a second
● We have to “make up” - interpolate 3 frames
58. Interpolation
private PointF[][] calculateContours(final PointF[][] currentData, final int[] averagedData, final int offset, final boolean goOutwards) {
…….
fillWithLinearyInterpolatedFrames(newFrames);
…….
return newFrames;
}
private void fillWithLinearyInterpolatedFrames(final PointF[][] data) {
for (int j = 0; j < NUMBER_OF_SAMPLES; j++) {
final PointF targetPoint = data[NUMBER_OF_INTERPOLATED_FRAMES - 1][j];
final PointF originPoint = data[0][j];
final double deltaX = (targetPoint.x - originPoint.x) / NUMBER_OF_INTERPOLATED_FRAMES;
final double deltaY = (targetPoint.y - originPoint.y) / NUMBER_OF_INTERPOLATED_FRAMES;
for (int i = 1; i < NUMBER_OF_INTERPOLATED_FRAMES - 1; i++) {
data[i][j] = new PointF((float) (originPoint.x + i * deltaX), (float) (originPoint.y + i * deltaY));
}
}
for (int i = 1; i < NUMBER_OF_INTERPOLATED_FRAMES - 1; i++) {
data[i][NUMBER_OF_SAMPLES] = data[i][0];
}
}
62. Conclusion
● Animation is change of state through time
● State can be anything from color to position
● Target 60 (or higher) fps main loop, beware of frame drops
● Pre-calculate whole frameset or calculate frame by frame
● Take it slow, make demo app, increment step by step
● Use code examples as a starting point and inform me where are memory
leaks :)
64. QA
To save myself from having to answer embarrassing questions face to face
● Have you measured how much does it suck life out of battery? - No, but
we’ve noticed it does
● Why don’t you use OpenGL or something. - It’s next level, this is first
approximation
● What about object animators - Same amount of code, took me same
amount of time, more expensive, less flexible if you know what are you
doing. Can’t apply to the equalizer. It is more OO approach though.