code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php
namespace Drupal\search_api_autocomplete\Suggestion;
use Drupal\Core\Render\RenderableInterface;
/**
* Defines a single autocompletion suggestion.
*/
interface SuggestionInterface extends RenderableInterface {
/**
* Retrieves the keywords this suggestion will autocomplete to.
*
* @return string|null
* The suggested keywords, or NULL if the suggestion should direct to a URL
* instead.
*/
public function getSuggestedKeys();
/**
* Retrieves the URL to which the suggestion should redirect.
*
* A URL to which the suggestion should redirect instead of completing the
* user input in the text field. This overrides the normal behavior and thus
* makes the suggested keys obsolete.
*
* @return \Drupal\Core\Url|null
* The URL to which the suggestion should redirect to, or NULL if none was
* set.
*/
public function getUrl();
/**
* Retrieves the prefix for the suggestion.
*
* For special kinds of suggestions, this will contain some kind of prefix
* describing them.
*
* @return string|null
* The prefix, if set.
*/
public function getPrefix();
/**
* Retrieves the label to use for the suggestion.
*
* Should only be used if the other fields that will be displayed (suggestion
* prefix/suffix and user input) are empty.
*
* @return string
* The suggestion's label.
*/
public function getLabel();
/**
* Retrieves the prefix suggested for the entered keys.
*
* @return string|null
* The suggested prefix, if any.
*/
public function getSuggestionPrefix();
/**
* The input entered by the user, if it should be included in the label.
*
* @return string|null
* The input provided by the user.
*/
public function getUserInput();
/**
* A suggested suffix for the entered input.
*
* @return string|null
* A suffix.
*/
public function getSuggestionSuffix();
/**
* Returns the estimated number of results for this suggestion.
*
* @return int|null
* The estimated number of results, or NULL if no estimate is available.
*/
public function getResultsCount();
/**
* Returns the render array set for this suggestion.
*
* This should be displayed to the user for this suggestion. If missing, the
* suggestion is instead rendered with the
* "search_api_autocomplete_suggestion" theme.
*
* @return array|null
* A renderable array of the suggestion results, or NULL if none was set.
*/
public function getRender();
/**
* Sets the keys.
*
* @param string|null $keys
* The keys.
*
* @return $this
*/
public function setSuggestedKeys($keys);
/**
* Sets the URL.
*
* @param \Drupal\Core\Url|null $url
* The URL.
*
* @return $this
*/
public function setUrl($url);
/**
* Sets the prefix.
*
* @param string|null $prefix
* The prefix.
*
* @return $this
*/
public function setPrefix($prefix);
/**
* Sets the label.
*
* @param string|null $label
* The new label.
*
* @return $this
*/
public function setLabel($label);
/**
* Sets the suggestion prefix.
*
* @param string|null $suggestion_prefix
* The suggestion prefix.
*
* @return $this
*/
public function setSuggestionPrefix($suggestion_prefix);
/**
* Sets the user input.
*
* @param string|null $user_input
* The user input.
*
* @return $this
*/
public function setUserInput($user_input);
/**
* Sets the suggestion suffix.
*
* @param string|null $suggestion_suffix
* The suggestion suffix.
*
* @return $this
*/
public function setSuggestionSuffix($suggestion_suffix);
/**
* Sets the result count.
*
* @param string|null $results
* The result count.
*
* @return $this
*/
public function setResultsCount($results);
/**
* Sets the render array.
*
* @param array|null $render
* The render array.
*
* @return $this
*/
public function setRender($render);
}
| Java |
/*
* PROJECT: Boot Loader
* LICENSE: BSD - See COPYING.ARM in the top level directory
* FILE: boot/armllb/hw/versatile/hwclcd.c
* PURPOSE: LLB CLCD Routines for Versatile
* PROGRAMMERS: ReactOS Portable Systems Group
*/
#include "precomp.h"
#define LCDTIMING0_PPL(x) ((((x) / 16 - 1) & 0x3f) << 2)
#define LCDTIMING1_LPP(x) (((x) & 0x3ff) - 1)
#define LCDCONTROL_LCDPWR (1 << 11)
#define LCDCONTROL_LCDEN (1)
#define LCDCONTROL_LCDBPP(x) (((x) & 7) << 1)
#define LCDCONTROL_LCDTFT (1 << 5)
#define PL110_LCDTIMING0 (PVOID)0x10120000
#define PL110_LCDTIMING1 (PVOID)0x10120004
#define PL110_LCDTIMING2 (PVOID)0x10120008
#define PL110_LCDUPBASE (PVOID)0x10120010
#define PL110_LCDLPBASE (PVOID)0x10120014
#define PL110_LCDCONTROL (PVOID)0x10120018
PUSHORT LlbHwVideoBuffer;
VOID
NTAPI
LlbHwVersaClcdInitialize(VOID)
{
/* Set framebuffer address */
WRITE_REGISTER_ULONG(PL110_LCDUPBASE, (ULONG)LlbHwGetFrameBuffer());
WRITE_REGISTER_ULONG(PL110_LCDLPBASE, (ULONG)LlbHwGetFrameBuffer());
/* Initialize timings to 720x400 */
WRITE_REGISTER_ULONG(PL110_LCDTIMING0, LCDTIMING0_PPL(LlbHwGetScreenWidth()));
WRITE_REGISTER_ULONG(PL110_LCDTIMING1, LCDTIMING1_LPP(LlbHwGetScreenHeight()));
/* Enable the TFT/LCD Display */
WRITE_REGISTER_ULONG(PL110_LCDCONTROL,
LCDCONTROL_LCDEN |
LCDCONTROL_LCDTFT |
LCDCONTROL_LCDPWR |
LCDCONTROL_LCDBPP(4));
}
ULONG
NTAPI
LlbHwGetScreenWidth(VOID)
{
return 720;
}
ULONG
NTAPI
LlbHwGetScreenHeight(VOID)
{
return 400;
}
PVOID
NTAPI
LlbHwGetFrameBuffer(VOID)
{
return (PVOID)0x000A0000;
}
ULONG
NTAPI
LlbHwVideoCreateColor(IN ULONG Red,
IN ULONG Green,
IN ULONG Blue)
{
return (((Blue >> 3) << 11)| ((Green >> 2) << 5)| ((Red >> 3) << 0));
}
/* EOF */
| Java |
<?php
/**
* @package FrameworkOnFramework
* @subpackage database
* @copyright Copyright (C) 2010-2016 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*
* This file is adapted from the Joomla! Platform. It is used to iterate a database cursor returning FOFTable objects
* instead of plain stdClass objects
*/
// Protect from unauthorized access
defined('FOF_INCLUDED') or die;
/**
* Query Building Class.
*
* @package Joomla.Platform
* @subpackage Database
* @since 3.4
*/
class FOFDatabaseQueryPdomysql extends FOFDatabaseQueryMysqli
{
}
| Java |
/*
* Copyright (C) 2011 ST-Ericsson SA.
* Copyright (C) 2009 Motorola, Inc.
*
* License Terms: GNU General Public License v2
*
* Simple driver for National Semiconductor LM3530 Backlight driver chip
*
* Author: Shreshtha Kumar SAHU <shreshthakumar.sahu@stericsson.com>
* based on leds-lm3530.c by Dan Murphy <D.Murphy@motorola.com>
*/
#include <linux/i2c.h>
#include <linux/leds.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/led-lm3530.h>
#include <linux/types.h>
#include <linux/regulator/consumer.h>
#include <linux/module.h>
#define LM3530_LED_DEV "lcd-backlight"
#define LM3530_NAME "lm3530-led"
#define LM3530_GEN_CONFIG 0x10
#define LM3530_ALS_CONFIG 0x20
#define LM3530_BRT_RAMP_RATE 0x30
#define LM3530_ALS_IMP_SELECT 0x41
#define LM3530_BRT_CTRL_REG 0xA0
#define LM3530_ALS_ZB0_REG 0x60
#define LM3530_ALS_ZB1_REG 0x61
#define LM3530_ALS_ZB2_REG 0x62
#define LM3530_ALS_ZB3_REG 0x63
#define LM3530_ALS_Z0T_REG 0x70
#define LM3530_ALS_Z1T_REG 0x71
#define LM3530_ALS_Z2T_REG 0x72
#define LM3530_ALS_Z3T_REG 0x73
#define LM3530_ALS_Z4T_REG 0x74
#define LM3530_REG_MAX 14
/* General Control Register */
#define LM3530_EN_I2C_SHIFT (0)
#define LM3530_RAMP_LAW_SHIFT (1)
#define LM3530_MAX_CURR_SHIFT (2)
#define LM3530_EN_PWM_SHIFT (5)
#define LM3530_PWM_POL_SHIFT (6)
#define LM3530_EN_PWM_SIMPLE_SHIFT (7)
#define LM3530_ENABLE_I2C (1 << LM3530_EN_I2C_SHIFT)
#define LM3530_ENABLE_PWM (1 << LM3530_EN_PWM_SHIFT)
#define LM3530_POL_LOW (1 << LM3530_PWM_POL_SHIFT)
#define LM3530_ENABLE_PWM_SIMPLE (1 << LM3530_EN_PWM_SIMPLE_SHIFT)
/* ALS Config Register Options */
#define LM3530_ALS_AVG_TIME_SHIFT (0)
#define LM3530_EN_ALS_SHIFT (3)
#define LM3530_ALS_SEL_SHIFT (5)
#define LM3530_ENABLE_ALS (3 << LM3530_EN_ALS_SHIFT)
/* Brightness Ramp Rate Register */
#define LM3530_BRT_RAMP_FALL_SHIFT (0)
#define LM3530_BRT_RAMP_RISE_SHIFT (3)
/* ALS Resistor Select */
#define LM3530_ALS1_IMP_SHIFT (0)
#define LM3530_ALS2_IMP_SHIFT (4)
/* Zone Boundary Register defaults */
#define LM3530_ALS_ZB_MAX (4)
#define LM3530_ALS_WINDOW_mV (1000)
#define LM3530_ALS_OFFSET_mV (4)
/* Zone Target Register defaults */
#define LM3530_DEF_ZT_0 (0x7F)
#define LM3530_DEF_ZT_1 (0x66)
#define LM3530_DEF_ZT_2 (0x4C)
#define LM3530_DEF_ZT_3 (0x33)
#define LM3530_DEF_ZT_4 (0x19)
/* 7 bits are used for the brightness : LM3530_BRT_CTRL_REG */
#define MAX_BRIGHTNESS (127)
struct lm3530_mode_map {
const char *mode;
enum lm3530_mode mode_val;
};
static struct lm3530_mode_map mode_map[] = {
{ "man", LM3530_BL_MODE_MANUAL },
{ "als", LM3530_BL_MODE_ALS },
{ "pwm", LM3530_BL_MODE_PWM },
};
/**
* struct lm3530_data
* @led_dev: led class device
* @client: i2c client
* @pdata: LM3530 platform data
* @mode: mode of operation - manual, ALS, PWM
* @regulator: regulator
* @brighness: previous brightness value
* @enable: regulator is enabled
*/
struct lm3530_data {
struct led_classdev led_dev;
struct i2c_client *client;
struct lm3530_platform_data *pdata;
enum lm3530_mode mode;
struct regulator *regulator;
enum led_brightness brightness;
bool enable;
};
static const u8 lm3530_reg[LM3530_REG_MAX] = {
LM3530_GEN_CONFIG,
LM3530_ALS_CONFIG,
LM3530_BRT_RAMP_RATE,
LM3530_ALS_IMP_SELECT,
LM3530_BRT_CTRL_REG,
LM3530_ALS_ZB0_REG,
LM3530_ALS_ZB1_REG,
LM3530_ALS_ZB2_REG,
LM3530_ALS_ZB3_REG,
LM3530_ALS_Z0T_REG,
LM3530_ALS_Z1T_REG,
LM3530_ALS_Z2T_REG,
LM3530_ALS_Z3T_REG,
LM3530_ALS_Z4T_REG,
};
static int lm3530_get_mode_from_str(const char *str)
{
int i;
for (i = 0; i < ARRAY_SIZE(mode_map); i++)
if (sysfs_streq(str, mode_map[i].mode))
return mode_map[i].mode_val;
return -1;
}
static int lm3530_init_registers(struct lm3530_data *drvdata)
{
int ret = 0;
int i;
u8 gen_config;
u8 als_config = 0;
u8 brt_ramp;
u8 als_imp_sel = 0;
u8 brightness;
u8 reg_val[LM3530_REG_MAX];
u8 zones[LM3530_ALS_ZB_MAX];
u32 als_vmin, als_vmax, als_vstep;
struct lm3530_platform_data *pdata = drvdata->pdata;
struct i2c_client *client = drvdata->client;
struct lm3530_pwm_data *pwm = &pdata->pwm_data;
gen_config = (pdata->brt_ramp_law << LM3530_RAMP_LAW_SHIFT) |
((pdata->max_current & 7) << LM3530_MAX_CURR_SHIFT);
switch (drvdata->mode) {
case LM3530_BL_MODE_MANUAL:
case LM3530_BL_MODE_ALS:
gen_config |= LM3530_ENABLE_I2C;
break;
case LM3530_BL_MODE_PWM:
gen_config |= LM3530_ENABLE_PWM | LM3530_ENABLE_PWM_SIMPLE |
(pdata->pwm_pol_hi << LM3530_PWM_POL_SHIFT);
break;
}
if (drvdata->mode == LM3530_BL_MODE_ALS) {
if (pdata->als_vmax == 0) {
pdata->als_vmin = 0;
pdata->als_vmax = LM3530_ALS_WINDOW_mV;
}
als_vmin = pdata->als_vmin;
als_vmax = pdata->als_vmax;
if ((als_vmax - als_vmin) > LM3530_ALS_WINDOW_mV)
pdata->als_vmax = als_vmax =
als_vmin + LM3530_ALS_WINDOW_mV;
/* n zone boundary makes n+1 zones */
als_vstep = (als_vmax - als_vmin) / (LM3530_ALS_ZB_MAX + 1);
for (i = 0; i < LM3530_ALS_ZB_MAX; i++)
zones[i] = (((als_vmin + LM3530_ALS_OFFSET_mV) +
als_vstep + (i * als_vstep)) * LED_FULL)
/ 1000;
als_config =
(pdata->als_avrg_time << LM3530_ALS_AVG_TIME_SHIFT) |
(LM3530_ENABLE_ALS) |
(pdata->als_input_mode << LM3530_ALS_SEL_SHIFT);
als_imp_sel =
(pdata->als1_resistor_sel << LM3530_ALS1_IMP_SHIFT) |
(pdata->als2_resistor_sel << LM3530_ALS2_IMP_SHIFT);
}
brt_ramp = (pdata->brt_ramp_fall << LM3530_BRT_RAMP_FALL_SHIFT) |
(pdata->brt_ramp_rise << LM3530_BRT_RAMP_RISE_SHIFT);
if (drvdata->brightness)
brightness = drvdata->brightness;
else
brightness = drvdata->brightness = pdata->brt_val;
if (brightness > drvdata->led_dev.max_brightness)
brightness = drvdata->led_dev.max_brightness;
reg_val[0] = gen_config; /* LM3530_GEN_CONFIG */
reg_val[1] = als_config; /* LM3530_ALS_CONFIG */
reg_val[2] = brt_ramp; /* LM3530_BRT_RAMP_RATE */
reg_val[3] = als_imp_sel; /* LM3530_ALS_IMP_SELECT */
reg_val[4] = brightness; /* LM3530_BRT_CTRL_REG */
reg_val[5] = zones[0]; /* LM3530_ALS_ZB0_REG */
reg_val[6] = zones[1]; /* LM3530_ALS_ZB1_REG */
reg_val[7] = zones[2]; /* LM3530_ALS_ZB2_REG */
reg_val[8] = zones[3]; /* LM3530_ALS_ZB3_REG */
reg_val[9] = LM3530_DEF_ZT_0; /* LM3530_ALS_Z0T_REG */
reg_val[10] = LM3530_DEF_ZT_1; /* LM3530_ALS_Z1T_REG */
reg_val[11] = LM3530_DEF_ZT_2; /* LM3530_ALS_Z2T_REG */
reg_val[12] = LM3530_DEF_ZT_3; /* LM3530_ALS_Z3T_REG */
reg_val[13] = LM3530_DEF_ZT_4; /* LM3530_ALS_Z4T_REG */
if (!drvdata->enable) {
ret = regulator_enable(drvdata->regulator);
if (ret) {
dev_err(&drvdata->client->dev,
"Enable regulator failed\n");
return ret;
}
drvdata->enable = true;
}
for (i = 0; i < LM3530_REG_MAX; i++) {
/* do not update brightness register when pwm mode */
if (lm3530_reg[i] == LM3530_BRT_CTRL_REG &&
drvdata->mode == LM3530_BL_MODE_PWM) {
if (pwm->pwm_set_intensity)
pwm->pwm_set_intensity(reg_val[i],
drvdata->led_dev.max_brightness);
continue;
}
ret = i2c_smbus_write_byte_data(client,
lm3530_reg[i], reg_val[i]);
if (ret)
break;
}
return ret;
}
static void lm3530_brightness_set(struct led_classdev *led_cdev,
enum led_brightness brt_val)
{
int err;
struct lm3530_data *drvdata =
container_of(led_cdev, struct lm3530_data, led_dev);
struct lm3530_platform_data *pdata = drvdata->pdata;
struct lm3530_pwm_data *pwm = &pdata->pwm_data;
u8 max_brightness = led_cdev->max_brightness;
switch (drvdata->mode) {
case LM3530_BL_MODE_MANUAL:
if (!drvdata->enable) {
err = lm3530_init_registers(drvdata);
if (err) {
dev_err(&drvdata->client->dev,
"Register Init failed: %d\n", err);
break;
}
}
/* set the brightness in brightness control register*/
err = i2c_smbus_write_byte_data(drvdata->client,
LM3530_BRT_CTRL_REG, brt_val);
if (err)
dev_err(&drvdata->client->dev,
"Unable to set brightness: %d\n", err);
else
drvdata->brightness = brt_val;
if (brt_val == 0) {
err = regulator_disable(drvdata->regulator);
if (err)
dev_err(&drvdata->client->dev,
"Disable regulator failed\n");
drvdata->enable = false;
}
break;
case LM3530_BL_MODE_ALS:
break;
case LM3530_BL_MODE_PWM:
if (pwm->pwm_set_intensity)
pwm->pwm_set_intensity(brt_val, max_brightness);
break;
default:
break;
}
}
static ssize_t lm3530_mode_get(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3530_data *drvdata;
int i, len = 0;
drvdata = container_of(led_cdev, struct lm3530_data, led_dev);
for (i = 0; i < ARRAY_SIZE(mode_map); i++)
if (drvdata->mode == mode_map[i].mode_val)
len += sprintf(buf + len, "[%s] ", mode_map[i].mode);
else
len += sprintf(buf + len, "%s ", mode_map[i].mode);
len += sprintf(buf + len, "\n");
return len;
}
static ssize_t lm3530_mode_set(struct device *dev, struct device_attribute
*attr, const char *buf, size_t size)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm3530_data *drvdata;
struct lm3530_pwm_data *pwm;
u8 max_brightness;
int mode, err;
drvdata = container_of(led_cdev, struct lm3530_data, led_dev);
pwm = &drvdata->pdata->pwm_data;
max_brightness = led_cdev->max_brightness;
mode = lm3530_get_mode_from_str(buf);
if (mode < 0) {
dev_err(dev, "Invalid mode\n");
return -EINVAL;
}
drvdata->mode = mode;
/* set pwm to low if unnecessary */
if (mode != LM3530_BL_MODE_PWM && pwm->pwm_set_intensity)
pwm->pwm_set_intensity(0, max_brightness);
err = lm3530_init_registers(drvdata);
if (err) {
dev_err(dev, "Setting %s Mode failed :%d\n", buf, err);
return err;
}
return sizeof(drvdata->mode);
}
static DEVICE_ATTR(mode, 0644, lm3530_mode_get, lm3530_mode_set);
static int __devinit lm3530_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct lm3530_platform_data *pdata = client->dev.platform_data;
struct lm3530_data *drvdata;
int err = 0;
if (pdata == NULL) {
dev_err(&client->dev, "platform data required\n");
err = -ENODEV;
goto err_out;
}
/* BL mode */
if (pdata->mode > LM3530_BL_MODE_PWM) {
dev_err(&client->dev, "Illegal Mode request\n");
err = -EINVAL;
goto err_out;
}
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
dev_err(&client->dev, "I2C_FUNC_I2C not supported\n");
err = -EIO;
goto err_out;
}
drvdata = kzalloc(sizeof(struct lm3530_data), GFP_KERNEL);
if (drvdata == NULL) {
err = -ENOMEM;
goto err_out;
}
drvdata->mode = pdata->mode;
drvdata->client = client;
drvdata->pdata = pdata;
drvdata->brightness = LED_OFF;
drvdata->enable = false;
drvdata->led_dev.name = LM3530_LED_DEV;
drvdata->led_dev.brightness_set = lm3530_brightness_set;
drvdata->led_dev.max_brightness = MAX_BRIGHTNESS;
i2c_set_clientdata(client, drvdata);
drvdata->regulator = regulator_get(&client->dev, "vin");
if (IS_ERR(drvdata->regulator)) {
dev_err(&client->dev, "regulator get failed\n");
err = PTR_ERR(drvdata->regulator);
drvdata->regulator = NULL;
goto err_regulator_get;
}
if (drvdata->pdata->brt_val) {
err = lm3530_init_registers(drvdata);
if (err < 0) {
dev_err(&client->dev,
"Register Init failed: %d\n", err);
err = -ENODEV;
goto err_reg_init;
}
}
err = led_classdev_register(&client->dev, &drvdata->led_dev);
if (err < 0) {
dev_err(&client->dev, "Register led class failed: %d\n", err);
err = -ENODEV;
goto err_class_register;
}
err = device_create_file(drvdata->led_dev.dev, &dev_attr_mode);
if (err < 0) {
dev_err(&client->dev, "File device creation failed: %d\n", err);
err = -ENODEV;
goto err_create_file;
}
return 0;
err_create_file:
led_classdev_unregister(&drvdata->led_dev);
err_class_register:
err_reg_init:
regulator_put(drvdata->regulator);
err_regulator_get:
kfree(drvdata);
err_out:
return err;
}
static int __devexit lm3530_remove(struct i2c_client *client)
{
struct lm3530_data *drvdata = i2c_get_clientdata(client);
device_remove_file(drvdata->led_dev.dev, &dev_attr_mode);
if (drvdata->enable)
regulator_disable(drvdata->regulator);
regulator_put(drvdata->regulator);
led_classdev_unregister(&drvdata->led_dev);
kfree(drvdata);
return 0;
}
static const struct i2c_device_id lm3530_id[] = {
{LM3530_NAME, 0},
{}
};
MODULE_DEVICE_TABLE(i2c, lm3530_id);
static struct i2c_driver lm3530_i2c_driver = {
.probe = lm3530_probe,
.remove = __devexit_p(lm3530_remove),
.id_table = lm3530_id,
.driver = {
.name = LM3530_NAME,
.owner = THIS_MODULE,
},
};
module_i2c_driver(lm3530_i2c_driver);
MODULE_DESCRIPTION("Back Light driver for LM3530");
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Shreshtha Kumar SAHU <shreshthakumar.sahu@stericsson.com>");
| Java |
package sergio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.GregorianCalendar;
//Ejercicio Metodos 18
//Realiza una clase llamada milibreria que contenga al menos cinco de los metodos realizados.
//Usalas de 3 formas diferentes
//Autor: Sergio Tobal
//Fecha: 12-02-2012
public class EjerMetods18 {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in));
int numsend=10,edad;
char nombre;
boolean nombreceive;
String msgname = null;
System.out.println("Dame tu inicial:");
nombre=lectura.readLine().charAt(0);
nombreceive=EsMayus(nombre);
if (nombreceive==true) {
msgname="MAYUSCULAS";
} else if (nombreceive==false) {
msgname="minusculas";
}
EsPerfecto(numsend);
System.out.println("Tu primer numero perfecto es "+numsend+" porque tienes "+(edad=ObtenerEdad())+" años, y tu inicial esta escrita en "+msgname);
}
private static boolean EsPerfecto(int numsend) {
int perfect=0;
for (int i = 1; i < numsend; i++) {
if (numsend % i == 0) {
perfect += i;
}
}
if (perfect == numsend) {
return true;
}else {
return false;
}
}
private static int ObtenerEdad()throws NumberFormatException, IOException{
BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in));
int year,month,day;
System.out.println("Dime tu dia de nacimiento: ");
day=Integer.parseInt(lectura.readLine());
System.out.println("Dime tu mes de nacimiento: ");
month=Integer.parseInt(lectura.readLine());
System.out.println("Dime tu año de nacimiento: ");
year=Integer.parseInt(lectura.readLine());
Calendar cal = new GregorianCalendar(year, month, day);
Calendar now = new GregorianCalendar();
int edad = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if ((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH)) || (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH) && cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))
{
edad--;
}
return edad;
}
private static int Factorial(int num) {
int factorial=1;
// Va multiplicando el numero del usuario por 1 hasta que el numero llega ha cero y retorna
// la multiplicacion de todos los numeros
while (num!=0) {
factorial=factorial*num;
num--;
}
return factorial;
}
private static boolean ValFecha(int day, int month) {
if ((day>=1 && day<=31) && (month>=1 && month<=12)) {
return true;
}else {
return false;
}
}
private static boolean EsMayus(char nombre) {
boolean opt=true;
// La funcion isUpperCase comprueba que el contenido de num sea mayuscula
if (Character.isUpperCase(nombre) == true) {
opt=true;
// La funcion isLowerCase comprueba que el contenido de num sea minuscula
} else if(Character.isLowerCase(nombre) == true){
opt=false;
}
return opt;
}
}
| Java |
@import judgels.fs.FileInfo
@import org.iatoki.judgels.sandalphon.problem.programming.grading.blackbox.BatchGradingConfigForm
@import play.api.mvc.Call
@(batchGradingConfigForm: Form[BatchGradingConfigForm], postUpdateGradingConfigCall: Call, testDataFiles: List[FileInfo], helperFiles: List[FileInfo])
@implicitFieldConstructor = @{ b3.horizontal.fieldConstructor("col-md-3", "col-md-9") }
<script type="text/javascript" src="@controllers.routes.Assets.at("lib/jquery/jquery.min.js")"></script>
<script type="text/javascript">
$(document).ready(function() {
var sampleTestCaseTemplate = $('#sample-test-case-template');
var sampleTestDataContainer = $('#sample-test-data');
var sampleTestData = {
container: sampleTestDataContainer,
newSampleTestCase: {
inSelect: sampleTestDataContainer.find('select').first(),
outSelect: sampleTestDataContainer.find('select').last(),
addButton: sampleTestDataContainer.find('a').last()
},
sampleTestCases: []
};
var testCaseTemplate = $('#test-case-template');
var testDataContainer = $('#test-data');
var testData = {
container: testDataContainer,
newTestCase: {
inSelect: testDataContainer.find('select').first(),
outSelect: testDataContainer.find('select').last(),
addButton: testDataContainer.find('a').last()
},
testCases: []
};
function addNewSampleTestCase(inputVal, outputVal) {
if (!inputVal || !outputVal) {
alert("You don't have any test data files");
return;
}
var container = sampleTestCaseTemplate.clone().removeAttr('id');
var inInput = container.find('input').first();
var outInput = container.find('input').last();
var removeButton = container.find('a').last();
var caseNo = sampleTestData.sampleTestCases.length;
// Update input values
inInput
.prop('name', 'sampleTestCaseInputs[' + caseNo + ']')
.val(inputVal);
outInput
.prop('name', 'sampleTestCaseOutputs[' + caseNo + ']')
.val(outputVal);
// Update remove test case button
removeButton.on('click', function() {
removeSampleTestCase(caseNo);
return false;
});
var sampleTestCase = {
container: container,
inInput: inInput,
outInput: outInput,
removeButton: removeButton
};
sampleTestData.sampleTestCases.push(sampleTestCase);
// Append this sample test case
container.insertBefore(sampleTestData.container.find('tr').last());
refreshSampleTestData();
container.show();
}
function removeSampleTestCase(caseNo) {
sampleTestData.sampleTestCases[caseNo].container.remove();
sampleTestData.sampleTestCases.splice(caseNo, 1);
refreshSampleTestData();
}
function refreshSampleTestData() {
var sampleTestCasesCount = sampleTestData.sampleTestCases.length;
for (var caseNo = 0; caseNo < sampleTestCasesCount; caseNo++) {
var sampleTestCase = sampleTestData.sampleTestCases[caseNo];
sampleTestCase.inInput.prop('name', 'sampleTestCaseInputs[' + caseNo + ']');
sampleTestCase.outInput.prop('name', 'sampleTestCaseOutputs[' + caseNo + ']');
(function(caseNo) {
sampleTestCase.removeButton.off('click').on('click', function() {
removeSampleTestCase(caseNo);
return false ;
});
})(caseNo);
}
}
function addNewTestCase(inputVal, outputVal) {
if (!inputVal || !outputVal) {
alert("You don't have any test data files");
return;
}
var container = testCaseTemplate.clone().removeAttr('id');
var inInput = container.find('input').first();
var outInput = container.find('input').last();
var removeButton = container.find('a').last();
var caseNo = testData.testCases.length;
// Update input values
inInput
.prop('name', 'testCaseInputs[0][' + caseNo + ']')
.val(inputVal);
outInput
.prop('name', 'testCaseOutputs[0][' + caseNo + ']')
.val(outputVal);
// Update remove test case button
removeButton.on('click', function() {
removeTestCase(caseNo);
return false;
});
var testCase = {
container: container,
inInput: inInput,
outInput: outInput,
removeButton: removeButton
};
testData.testCases.push(testCase);
// Append this test case
container.insertBefore(testData.container.find('tr').last());
refreshTestData();
container.show();
}
function removeTestCase(caseNo) {
testData.testCases[caseNo].container.remove();
testData.testCases.splice(caseNo, 1);
refreshTestData();
}
function refreshTestData() {
var testCasesCount = testData.testCases.length;
for (var caseNo = 0; caseNo < testCasesCount; caseNo++) {
var testCase = testData.testCases[caseNo];
testCase.inInput.prop('name', 'testCaseInputs[0][' + caseNo + ']');
testCase.outInput.prop('name', 'testCaseOutputs[0][' + caseNo + ']');
(function(caseNo) {
testCase.removeButton.off('click').on('click', function() {
removeTestCase(caseNo) ;
return false ;
});
})(caseNo);
}
}
sampleTestData.newSampleTestCase.addButton.on('click', function() {
addNewSampleTestCase(sampleTestData.newSampleTestCase.inSelect.val(), sampleTestData.newSampleTestCase.outSelect.val());
return false;
});
testData.newTestCase.addButton.on('click', function() {
addNewTestCase(testData.newTestCase.inSelect.val(), testData.newTestCase.outSelect.val());
return false;
});
@for(i <- 0 until batchGradingConfigForm.get.sampleTestCaseInputs.size) {
addNewSampleTestCase('@batchGradingConfigForm.get.sampleTestCaseInputs.get(i)', '@batchGradingConfigForm.get.sampleTestCaseOutputs.get(i)');
}
@for(i <- 0 until batchGradingConfigForm.get.testCaseInputs.size) {
@for(j <- 0 until batchGradingConfigForm.get.testCaseInputs.get(i).size) {
addNewTestCase('@batchGradingConfigForm.get.testCaseInputs.get(i).get(j)', '@batchGradingConfigForm.get.testCaseOutputs.get(i).get(j)');
}
}
});
</script>
@b3.form(postUpdateGradingConfigCall) {
@helper.CSRF.formField
@b3.inputWrapped("timeLimit", batchGradingConfigForm("timeLimit"), '_label -> "Time Limit") { input =>
<div class="input-group">
@input
<div class="input-group-addon">milliseconds</div>
</div>
}
@b3.inputWrapped("memoryLimit", batchGradingConfigForm("memoryLimit"), '_label -> "Memory Limit") { input =>
<div class="input-group">
@input
<div class="input-group-addon">kilobytes</div>
</div>
}
<div class="row" style="margin-bottom: 10px;">
<div class="col-md-3">
<label class="control-label">Sample Test Data</label>
</div>
<div class="col-md-9">
<div class="panel panel-default">
<div class="panel-body">
<table class="table table-condensed">
<thead>
<tr>
<th>Sample Input</th>
<th>Sample Output</th>
<th></th>
</tr>
</thead>
<tbody id="sample-test-data">
<tr id="sample-test-case-template" style="display: none">
<td>
<input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.in" />
</td>
<td>
<input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.out" />
</td>
<td class="text-center">
<a href="#"><span class="glyphicon glyphicon-remove"></span></a>
</td>
</tr>
<tr class="active">
<td>
<select>
@for(file <- testDataFiles) {
<option value="@file.getName">@file.getName</option>
}
</select>
</td>
<td>
<select>
@for(file <- testDataFiles) {
<option value="@file.getName">@file.getName</option>
}
</select>
</td>
<td class="text-center">
<a href=""><span class="glyphicon glyphicon-plus"></span></a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row" style="margin-bottom: 10px;">
<div class="col-md-3">
<label class="control-label">Test Data</label>
</div>
<div class="col-md-9">
<div class="panel panel-default">
<div class="panel-body">
<table class="table table-condensed">
<thead>
<tr>
<th>Input</th>
<th>Output</th>
<th></th>
</tr>
</thead>
<tbody id="test-data">
<tr id="test-case-template" style="display: none">
<td>
<input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.in" />
</td>
<td>
<input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.out" />
</td>
<td class="text-center">
<a href="#"><span class="glyphicon glyphicon-remove"></span></a>
</td>
</tr>
<tr class="active">
<td>
<select>
@for(file <- testDataFiles) {
<option value="@file.getName">@file.getName</option>
}
</select>
</td>
<td>
<select>
@for(file <- testDataFiles) {
<option value="@file.getName">@file.getName</option>
}
</select>
</td>
<td class="text-center">
<a href=""><span class="glyphicon glyphicon-plus"></span></a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
@b3.select(batchGradingConfigForm("customScorer"), helperFiles.map(f => f.getName -> f.getName).toSeq ++ Seq("(none)" -> "(None)"), '_label -> "Custom Scorer")
@b3.submit('class -> "btn btn-primary") { Update }
}
| Java |
#!/bin/sh
#
# Support routines for hand-crafting weird or malicious packs.
#
# You can make a complete pack like:
#
# pack_header 2 >foo.pack &&
# pack_obj e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 >>foo.pack &&
# pack_obj e68fe8129b546b101aee9510c5328e7f21ca1d18 >>foo.pack &&
# pack_trailer foo.pack
# Print the big-endian 4-byte octal representation of $1
uint32_octal () {
n=$1
printf '\%o' $(($n / 16777216)); n=$((n % 16777216))
printf '\%o' $(($n / 65536)); n=$((n % 65536))
printf '\%o' $(($n / 256)); n=$((n % 256))
printf '\%o' $(($n ));
}
# Print the big-endian 4-byte binary representation of $1
uint32_binary () {
printf "$(uint32_octal "$1")"
}
# Print a pack header, version 2, for a pack with $1 objects
pack_header () {
printf 'PACK' &&
printf '\0\0\0\2' &&
uint32_binary "$1"
}
# Print the pack data for object $1, as a delta against object $2 (or as a full
# object if $2 is missing or empty). The output is suitable for including
# directly in the packfile, and represents the entirety of the object entry.
# Doing this on the fly (especially picking your deltas) is quite tricky, so we
# have hardcoded some well-known objects. See the case statements below for the
# complete list.
pack_obj () {
case "$1" in
# empty blob
e69de29bb2d1d6434b8b29ae775ad8c2e48c5391)
case "$2" in
'')
printf '\060\170\234\003\0\0\0\0\1'
return
;;
esac
;;
# blob containing "\7\76"
e68fe8129b546b101aee9510c5328e7f21ca1d18)
case "$2" in
'')
printf '\062\170\234\143\267\3\0\0\116\0\106'
return
;;
01d7713666f4de822776c7622c10f1b07de280dc)
printf '\165\1\327\161\66\146\364\336\202\47\166' &&
printf '\307\142\54\20\361\260\175\342\200\334\170' &&
printf '\234\143\142\142\142\267\003\0\0\151\0\114'
return
;;
esac
;;
# blob containing "\7\0"
01d7713666f4de822776c7622c10f1b07de280dc)
case "$2" in
'')
printf '\062\170\234\143\147\0\0\0\20\0\10'
return
;;
e68fe8129b546b101aee9510c5328e7f21ca1d18)
printf '\165\346\217\350\22\233\124\153\20\32\356' &&
printf '\225\20\305\62\216\177\41\312\35\30\170\234' &&
printf '\143\142\142\142\147\0\0\0\53\0\16'
return
;;
esac
;;
esac
echo >&2 "BUG: don't know how to print $1${2:+ (from $2)}"
return 1
}
# Compute and append pack trailer to "$1"
pack_trailer () {
test-sha1 -b <"$1" >trailer.tmp &&
cat trailer.tmp >>"$1" &&
rm -f trailer.tmp
}
# Remove any existing packs to make sure that
# whatever we index next will be the pack that we
# actually use.
clear_packs () {
rm -f .git/objects/pack/*
}
| Java |
#region
using System.Collections.Generic;
using System.Data;
using Albian.Persistence.Model;
#endregion
namespace Albian.Persistence.Context
{
public interface IStorageContext
{
string StorageName { get; set; }
IList<IFakeCommandAttribute> FakeCommand { get; set; }
IDbConnection Connection { get; set; }
IDbTransaction Transaction { get; set; }
IList<IDbCommand> Command { get; set; }
IStorageAttribute Storage { get; set; }
}
} | Java |
/**
* $Id$
* Copyright (C) 2008 - 2014 Nils Asmussen
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <esc/proto/socket.h>
#include <esc/stream/fstream.h>
#include <esc/stream/istringstream.h>
#include <esc/stream/ostream.h>
#include <esc/dns.h>
#include <sys/common.h>
#include <sys/endian.h>
#include <sys/proc.h>
#include <sys/thread.h>
#include <signal.h>
namespace esc {
/* based on http://tools.ietf.org/html/rfc1035 */
#define DNS_RECURSION_DESIRED 0x100
#define DNS_PORT 53
#define BUF_SIZE 512
uint16_t DNS::_nextId = 0;
esc::Net::IPv4Addr DNS::_nameserver;
enum Type {
TYPE_A = 1, /* a host address */
TYPE_NS = 2, /* an authoritative name server */
TYPE_CNAME = 5, /* the canonical name for an alias */
TYPE_HINFO = 13, /* host information */
TYPE_MX = 15, /* mail exchange */
};
enum Class {
CLASS_IN = 1 /* the Internet */
};
struct DNSHeader {
uint16_t id;
uint16_t flags;
uint16_t qdCount;
uint16_t anCount;
uint16_t nsCount;
uint16_t arCount;
} A_PACKED;
struct DNSQuestionEnd {
uint16_t type;
uint16_t cls;
} A_PACKED;
struct DNSAnswer {
uint16_t name;
uint16_t type;
uint16_t cls;
uint32_t ttl;
uint16_t length;
} A_PACKED;
esc::Net::IPv4Addr DNS::getHost(const char *name,uint timeout) {
if(isIPAddress(name)) {
esc::Net::IPv4Addr addr;
IStringStream is(name);
is >> addr;
return addr;
}
return resolve(name,timeout);
}
bool DNS::isIPAddress(const char *name) {
int dots = 0;
int len = 0;
// ignore whitespace at the beginning
while(isspace(*name))
name++;
while(dots < 4 && len < 4 && *name) {
if(*name == '.') {
dots++;
len = 0;
}
else if(isdigit(*name))
len++;
else
break;
name++;
}
// ignore whitespace at the end
while(isspace(*name))
name++;
return dots == 3 && len > 0 && len < 4;
}
esc::Net::IPv4Addr DNS::resolve(const char *name,uint timeout) {
uint8_t buffer[BUF_SIZE];
if(_nameserver.value() == 0) {
FStream in(getResolveFile(),"r");
in >> _nameserver;
if(_nameserver.value() == 0)
VTHROWE("No nameserver",-EHOSTNOTFOUND);
}
size_t nameLen = strlen(name);
size_t total = sizeof(DNSHeader) + nameLen + 2 + sizeof(DNSQuestionEnd);
if(total > sizeof(buffer))
VTHROWE("Hostname too long",-EINVAL);
// generate a unique
uint16_t txid = (getpid() << 16) | _nextId;
// build DNS request message
DNSHeader *h = reinterpret_cast<DNSHeader*>(buffer);
h->id = cputobe16(txid);
h->flags = cputobe16(DNS_RECURSION_DESIRED);
h->qdCount = cputobe16(1);
h->anCount = 0;
h->nsCount = 0;
h->arCount = 0;
convertHostname(reinterpret_cast<char*>(h + 1),name,nameLen);
DNSQuestionEnd *qend = reinterpret_cast<DNSQuestionEnd*>(buffer + sizeof(*h) + nameLen + 2);
qend->type = cputobe16(TYPE_A);
qend->cls = cputobe16(CLASS_IN);
// create socket
esc::Socket sock(esc::Socket::SOCK_DGRAM,esc::Socket::PROTO_UDP);
// send over socket
esc::Socket::Addr addr;
addr.family = esc::Socket::AF_INET;
addr.d.ipv4.addr = _nameserver.value();
addr.d.ipv4.port = DNS_PORT;
sock.sendto(addr,buffer,total);
sighandler_t oldhandler;
if((oldhandler = signal(SIGALRM,sigalarm)) == SIG_ERR)
VTHROW("Unable to set SIGALRM handler");
int res;
if((res = ualarm(timeout * 1000)) < 0)
VTHROWE("ualarm(" << (timeout * 1000) << ")",res);
try {
// receive response
sock.recvfrom(addr,buffer,sizeof(buffer));
}
catch(const esc::default_error &e) {
if(e.error() == -EINTR)
VTHROWE("Received no response from DNS server " << _nameserver,-ETIMEOUT);
// ignore errors here
if(signal(SIGALRM,oldhandler) == SIG_ERR) {}
throw;
}
// ignore errors here
if(signal(SIGALRM,oldhandler) == SIG_ERR) {}
if(be16tocpu(h->id) != txid)
VTHROWE("Received DNS response with wrong transaction id",-EHOSTNOTFOUND);
int questions = be16tocpu(h->qdCount);
int answers = be16tocpu(h->anCount);
// skip questions
uint8_t *data = reinterpret_cast<uint8_t*>(h + 1);
for(int i = 0; i < questions; ++i) {
size_t len = questionLength(data);
data += len + sizeof(DNSQuestionEnd);
}
// parse answers
for(int i = 0; i < answers; ++i) {
DNSAnswer *ans = reinterpret_cast<DNSAnswer*>(data);
if(be16tocpu(ans->type) == TYPE_A && be16tocpu(ans->length) == esc::Net::IPv4Addr::LEN)
return esc::Net::IPv4Addr(data + sizeof(DNSAnswer));
}
VTHROWE("Unable to find IP address in DNS response",-EHOSTNOTFOUND);
}
void DNS::convertHostname(char *dst,const char *src,size_t len) {
// leave one byte space for the length of the first part
const char *from = src + len++;
char *to = dst + len;
// we start with the \0 at the end
int partLen = -1;
for(size_t i = 0; i < len; i++, to--, from--) {
if(*from == '.') {
*to = partLen;
partLen = 0;
}
else {
*to = *from;
partLen++;
}
}
*to = partLen;
}
size_t DNS::questionLength(const uint8_t *data) {
size_t total = 0;
while(*data != 0) {
uint8_t len = *data;
// skip this name-part
total += len + 1;
data += len + 1;
}
// skip zero ending, too
return total + 1;
}
}
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1">
<title>PushReceiver</title>
<link rel="stylesheet" href="style.css"/>
<!-- Inline scripts are forbidden in Firefox OS apps (CSP restrictions),
so we use a script file. -->
<script src="app.js" defer></script>
</head>
<body>
<!-- This code is in the public domain. Enjoy! -->
<h1>PushReceiver</h1>
<div class="row control"><button id="go">Register</button></div>
<div id="status">
Not Connected.
<div>
</body>
</html>
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef AUDIORECORD_H_
#define AUDIORECORD_H_
#include <binder/IMemory.h>
#include <cutils/sched_policy.h>
#include <media/AudioSystem.h>
#include <media/IAudioRecord.h>
#include <system/audio.h>
#include <utils/RefBase.h>
#include <utils/Errors.h>
#include <utils/threads.h>
#ifndef ANDROID_DEFAULT_CODE
#include <media/AudioEffect.h>
#endif
namespace android {
class audio_track_cblk_t;
// ----------------------------------------------------------------------------
class AudioRecord : virtual public RefBase
{
public:
static const int DEFAULT_SAMPLE_RATE = 8000;
#ifndef ANDROID_DEFAULT_CODE
static const int MATV_SAMPLE_RATE = 32000;
#endif
/* Events used by AudioRecord callback function (callback_t).
* Keep in sync with frameworks/base/media/java/android/media/AudioRecord.java NATIVE_EVENT_*.
*/
enum event_type {
EVENT_MORE_DATA = 0, // Request to read more data from PCM buffer.
EVENT_OVERRUN = 1, // PCM buffer overrun occured.
EVENT_MARKER = 2, // Record head is at the specified marker position
// (See setMarkerPosition()).
EVENT_NEW_POS = 3, // Record head is at a new position
// (See setPositionUpdatePeriod()).
#ifndef ANDROID_DEFAULT_CODE
EVENT_WAIT_TIEMOUT = 0xffff,
#endif
};
/* Create Buffer on the stack and pass it to obtainBuffer()
* and releaseBuffer().
*/
class Buffer
{
public:
enum {
MUTE = 0x00000001
};
uint32_t flags;
int channelCount;
audio_format_t format;
size_t frameCount;
size_t size; // total size in bytes == frameCount * frameSize
union {
void* raw;
short* i16;
int8_t* i8;
};
};
/* As a convenience, if a callback is supplied, a handler thread
* is automatically created with the appropriate priority. This thread
* invokes the callback when a new buffer becomes ready or an overrun condition occurs.
* Parameters:
*
* event: type of event notified (see enum AudioRecord::event_type).
* user: Pointer to context for use by the callback receiver.
* info: Pointer to optional parameter according to event type:
* - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read
* more bytes than indicated by 'size' field and update 'size' if less bytes are
* read.
* - EVENT_OVERRUN: unused.
* - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames.
* - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames.
*/
typedef void (*callback_t)(int event, void* user, void *info);
/* Returns the minimum frame count required for the successful creation of
* an AudioRecord object.
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - NO_INIT: audio server or audio hardware not initialized
* - BAD_VALUE: unsupported configuration
*/
static status_t getMinFrameCount(int* frameCount,
uint32_t sampleRate,
audio_format_t format,
audio_channel_mask_t channelMask);
/* Constructs an uninitialized AudioRecord. No connection with
* AudioFlinger takes place.
*/
AudioRecord();
/* Creates an AudioRecord track and registers it with AudioFlinger.
* Once created, the track needs to be started before it can be used.
* Unspecified values are set to the audio hardware's current
* values.
*
* Parameters:
*
* inputSource: Select the audio input to record to (e.g. AUDIO_SOURCE_DEFAULT).
* sampleRate: Track sampling rate in Hz.
* format: Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed
* 16 bits per sample).
* channelMask: Channel mask.
* frameCount: Total size of track PCM buffer in frames. This defines the
* latency of the track.
* cbf: Callback function. If not null, this function is called periodically
* to provide new PCM data.
* user: Context for use by the callback receiver.
* notificationFrames: The callback function is called each time notificationFrames PCM
* frames are ready in record track output buffer.
* sessionId: Not yet supported.
*/
//\\ AAMTF, Jau, Fix Build Error {
// FIXME consider removing this alias and replacing it by audio_in_acoustics_t
// or removing the parameter entirely if it is unused
enum record_flags {
RECORD_AGC_ENABLE = AUDIO_IN_ACOUSTICS_AGC_ENABLE,
RECORD_NS_ENABLE = AUDIO_IN_ACOUSTICS_NS_ENABLE,
RECORD_IIR_ENABLE = AUDIO_IN_ACOUSTICS_TX_IIR_ENABLE,
};
//\\ AAMTF, Jau, Fix Build Error }
AudioRecord(audio_source_t inputSource,
uint32_t sampleRate = 0,
audio_format_t format = AUDIO_FORMAT_DEFAULT,
audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO,
int frameCount = 0,
callback_t cbf = NULL,
void* user = NULL,
int notificationFrames = 0,
int sessionId = 0);
//MTK80721 HDRecord 2011-12-23
//#ifdef MTK_AUDIO_HD_REC_SUPPORT
#ifndef ANDROID_DEFAULT_CODE
AudioRecord(audio_source_t inputSource,
String8 Params,
uint32_t sampleRate = 0,
audio_format_t format = AUDIO_FORMAT_DEFAULT,
audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO,
int frameCount = 0,
callback_t cbf = NULL,
void* user = NULL,
int notificationFrames = 0,
int sessionId = 0);
#endif
//
/* Terminates the AudioRecord and unregisters it from AudioFlinger.
* Also destroys all resources associated with the AudioRecord.
*/
~AudioRecord();
/* Initialize an uninitialized AudioRecord.
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful intialization
* - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use
* - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
* - NO_INIT: audio server or audio hardware not initialized
* - PERMISSION_DENIED: recording is not allowed for the requesting process
* */
status_t set(audio_source_t inputSource = AUDIO_SOURCE_DEFAULT,
uint32_t sampleRate = 0,
audio_format_t format = AUDIO_FORMAT_DEFAULT,
audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO,
int frameCount = 0,
callback_t cbf = NULL,
void* user = NULL,
int notificationFrames = 0,
bool threadCanCallJava = false,
int sessionId = 0);
/* Result of constructing the AudioRecord. This must be checked
* before using any AudioRecord API (except for set()), using
* an uninitialized AudioRecord produces undefined results.
* See set() method above for possible return codes.
*/
status_t initCheck() const;
/* Returns this track's latency in milliseconds.
* This includes the latency due to AudioRecord buffer size
* and audio hardware driver.
*/
uint32_t latency() const;
/* getters, see constructor and set() */
audio_format_t format() const;
int channelCount() const;
uint32_t frameCount() const;
size_t frameSize() const;
audio_source_t inputSource() const;
/* After it's created the track is not active. Call start() to
* make it active. If set, the callback will start being called.
* if event is not AudioSystem::SYNC_EVENT_NONE, the capture start will be delayed until
* the specified event occurs on the specified trigger session.
*/
status_t start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
int triggerSession = 0);
/* Stop a track. If set, the callback will cease being called and
* obtainBuffer returns STOPPED. Note that obtainBuffer() still works
* and will fill up buffers until the pool is exhausted.
*/
void stop();
bool stopped() const;
/* get sample rate for this record track
*/
uint32_t getSampleRate() const;
/* Sets marker position. When record reaches the number of frames specified,
* a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
* with marker == 0 cancels marker notification callback.
* If the AudioRecord has been opened with no callback function associated,
* the operation will fail.
*
* Parameters:
*
* marker: marker position expressed in frames.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the AudioRecord has no callback installed.
*/
status_t setMarkerPosition(uint32_t marker);
status_t getMarkerPosition(uint32_t *marker) const;
/* Sets position update period. Every time the number of frames specified has been recorded,
* a callback with event type EVENT_NEW_POS is called.
* Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
* callback.
* If the AudioRecord has been opened with no callback function associated,
* the operation will fail.
*
* Parameters:
*
* updatePeriod: position update notification period expressed in frames.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - INVALID_OPERATION: the AudioRecord has no callback installed.
*/
status_t setPositionUpdatePeriod(uint32_t updatePeriod);
status_t getPositionUpdatePeriod(uint32_t *updatePeriod) const;
/* Gets record head position. The position is the total number of frames
* recorded since record start.
*
* Parameters:
*
* position: Address where to return record head position within AudioRecord buffer.
*
* Returned status (from utils/Errors.h) can be:
* - NO_ERROR: successful operation
* - BAD_VALUE: position is NULL
*/
status_t getPosition(uint32_t *position) const;
/* returns a handle on the audio input used by this AudioRecord.
*
* Parameters:
* none.
*
* Returned value:
* handle on audio hardware input
*/
audio_io_handle_t getInput() const;
/* returns the audio session ID associated with this AudioRecord.
*
* Parameters:
* none.
*
* Returned value:
* AudioRecord session ID.
*/
int getSessionId() const;
/* obtains a buffer of "frameCount" frames. The buffer must be
* filled entirely. If the track is stopped, obtainBuffer() returns
* STOPPED instead of NO_ERROR as long as there are buffers available,
* at which point NO_MORE_BUFFERS is returned.
* Buffers will be returned until the pool (buffercount())
* is exhausted, at which point obtainBuffer() will either block
* or return WOULD_BLOCK depending on the value of the "blocking"
* parameter.
*/
enum {
NO_MORE_BUFFERS = 0x80000001,
STOPPED = 1
};
status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
void releaseBuffer(Buffer* audioBuffer);
/* As a convenience we provide a read() interface to the audio buffer.
* This is implemented on top of obtainBuffer/releaseBuffer.
*/
ssize_t read(void* buffer, size_t size);
/* Return the amount of input frames lost in the audio driver since the last call of this
* function. Audio driver is expected to reset the value to 0 and restart counting upon
* returning the current value by this function call. Such loss typically occurs when the
* user space process is blocked longer than the capacity of audio driver buffers.
* Unit: the number of input audio frames
*/
unsigned int getInputFramesLost() const;
private:
/* copying audio tracks is not allowed */
AudioRecord(const AudioRecord& other);
AudioRecord& operator = (const AudioRecord& other);
#ifndef ANDROID_DEFAULT_CODE
void fn_ReleaseEffect(AudioEffect *&pEffect);
#endif
/* a small internal class to handle the callback */
class AudioRecordThread : public Thread
{
public:
AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
// Do not call Thread::requestExitAndWait() without first calling requestExit().
// Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
virtual void requestExit();
void pause(); // suspend thread from execution at next loop boundary
void resume(); // allow thread to execute, if not requested to exit
private:
friend class AudioRecord;
virtual bool threadLoop();
AudioRecord& mReceiver;
virtual ~AudioRecordThread();
Mutex mMyLock; // Thread::mLock is private
Condition mMyCond; // Thread::mThreadExitedCondition is private
bool mPaused; // whether thread is currently paused
};
// body of AudioRecordThread::threadLoop()
bool processAudioBuffer(const sp<AudioRecordThread>& thread);
status_t openRecord_l(uint32_t sampleRate,
audio_format_t format,
audio_channel_mask_t channelMask,
int frameCount,
audio_io_handle_t input);
audio_io_handle_t getInput_l();
status_t restoreRecord_l(audio_track_cblk_t*& cblk);
sp<AudioRecordThread> mAudioRecordThread;
mutable Mutex mLock;
bool mActive; // protected by mLock
// for client callback handler
callback_t mCbf;
void* mUserData;
// for notification APIs
uint32_t mNotificationFrames;
uint32_t mRemainingFrames;
uint32_t mMarkerPosition; // in frames
bool mMarkerReached;
uint32_t mNewPosition; // in frames
uint32_t mUpdatePeriod; // in ms
// constant after constructor or set()
uint32_t mFrameCount;
audio_format_t mFormat;
uint8_t mChannelCount;
audio_source_t mInputSource;
status_t mStatus;
uint32_t mLatency;
audio_channel_mask_t mChannelMask;
audio_io_handle_t mInput; // returned by AudioSystem::getInput()
int mSessionId;
// may be changed if IAudioRecord object is re-created
sp<IAudioRecord> mAudioRecord;
sp<IMemory> mCblkMemory;
audio_track_cblk_t* mCblk;
int mPreviousPriority; // before start()
SchedPolicy mPreviousSchedulingGroup;
};
}; // namespace android
#endif /*AUDIORECORD_H_*/
| Java |
<?php /* included from WPML_Translation_Management::icl_dashboard_widget_content */?>
<p><?php if ($docs_sent)
printf(__('%d documents sent to translation.<br />%d are complete, %d waiting for translation.', 'wpml-translation-management'),
$docs_sent, $docs_completed, $docs_waiting); ?></p>
<p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php" class="button secondary"><strong><?php
_e('Translate content', 'wpml-translation-management'); ?></strong></a></p>
<?php if(!defined('ICL_DONT_PROMOTE') || !ICL_DONT_PROMOTE):?>
<h5 style="margin: 15px 0 0 0;"><?php _e('Need translation work?', 'wpml-translation-management'); ?></h5>
<p><?php printf(__('%s offers affordable professional translation via a streamlined process.','wpml-translation-management'),
'<a target="_blank" href="http://www.icanlocalize.com/site/">ICanLocalize</a>') ?></p>
<p><a href="<?php echo admin_url('index.php?icl_ajx_action=quote-get'); ?>" class="button secondary thickbox"><strong><?php
_e('Get quote','wpml-translation-management') ?></strong></a>
<a href="admin.php?page=<?php echo WPML_TM_FOLDER;
?>/menu/main.php&sm=translators&service=icanlocalize" class="button secondary"><strong><?php
_e('Get translators','wpml-translation-management') ?></strong></a>
</p>
<?php endif;?>
<?php
// shows only when translation polling is on and there are translations in progress
$ICL_Pro_Translation->get_icl_manually_tranlations_box('icl_cyan_box');
?>
<?php if (count($active_languages = $sitepress->get_active_languages()) > 1): ?>
<div><a href="javascript:void(0)" onclick="jQuery(this).parent().next('.wrapper').slideToggle();"
style="display:block; padding:5px; border: 1px solid #eee; margin-bottom:2px; background-color: #F7F7F7;"><?php
_e('Content translation', 'wpml-translation-management') ?></a>
</div>
<div class="wrapper" style="display:none; padding: 5px 10px; border: 1px solid #eee; border-top: 0px; margin:-11px 0 2px 0;">
<?php
$your_translators = TranslationManagement::get_blog_translators();
$other_service_translators = TranslationManagement::icanlocalize_translators_list();
if (!empty($your_translators) || !empty($other_service_translators)) {
echo '<p><strong>' . __('Your translators', 'wpml-translation-management') . '</strong></p><ul>';
if (!empty($your_translators))
foreach ($your_translators as $your_translator) {
echo '<li>';
if ($current_user->ID == $your_translator->ID) {
$edit_link = 'profile.php';
} else {
$edit_link = esc_url(add_query_arg('wp_http_referer', urlencode(esc_url(stripslashes($_SERVER['REQUEST_URI']))), "user-edit.php?user_id=$your_translator->ID"));
}
echo '<a href="' . $edit_link . '"><strong>' . $your_translator->display_name . '</strong></a> - ';
foreach ($your_translator->language_pairs as $from => $lp) {
$tos = array();
foreach ($lp as $to => $null) {
$tos[] = $active_languages[$to]['display_name'];
}
printf(__('%s to %s', 'wpml-translation-management'), $active_languages[$from]['display_name'], join(', ', $tos));
}
echo '</li>';
}
if (!empty($other_service_translators)){
$langs = $sitepress->get_active_languages();
foreach ($other_service_translators as $rows){
foreach($rows['langs'] as $from => $lp){
$from = isset($langs[$from]['display_name']) ? $langs[$from]['display_name'] : $from;
$tos = array();
foreach($lp as $to){
$tos[] = isset($langs[$to]['display_name']) ? $langs[$to]['display_name'] : $to;
}
}
echo '<li>';
echo '<strong>' . $rows['name'] . '</strong> | ' .
sprintf(__('%s to %s', 'wpml-translation-management'), $from, join(', ', $tos)) . ' | ' . $rows['action'];
echo '</li>';
}
}
echo '</ul><hr />';
}
?>
<?php if(!defined('ICL_DONT_PROMOTE') || !ICL_DONT_PROMOTE):?>
<p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&sm=translators&service=icanlocalize"><strong><?php _e('Add translators from ICanLocalize »', 'wpml-translation-management'); ?></strong></a></p>
<?php endif; ?>
<p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&sm=translators&service=local"><strong><?php _e('Add your own translators »', 'wpml-translation-management'); ?></strong></a></p>
<p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php"><strong><?php _e('Translate contents »', 'wpml-translation-management'); ?></strong></a></p>
</div>
<?php endif; ?> | Java |
<HEAD><TITLE>rle.sp</TITLE></HEAD>
<BODY>
<HR><DIV ALIGN="center"><H1> File : rle.sp </H1></DIV><HR>
<DIV ALIGN="center">
<TABLE CELLSPACING="0" CELLPADDING="3" WIDTH="80%" SUMMARY="">
<TR>
<TD BGCOLOR="black"><SPAN STYLE="color: #00CC00">
<PRE>
$ spar rle
12W1B12W3B24W1B14W
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
</PRE>
</SPAN>
</TD>
</TR>
</TABLE>
</DIV>
<HR>
<PRE>
#!/usr/local/bin/spar
<b>pragma</b> <b>is</b>
annotate( summary, "rle" );
annotate( description, "Given a string containing uppercase characters (A-Z)," );
annotate( description, "compress repeated 'runs' of the same character by" );
annotate( description, "storing the length of that run, and provide a function to" );
annotate( description, "reverse the compression. The output can be anything, as" );
annotate( description, "long as you can recreate the input with it." );
annotate( description, "" );
annotate( description, "Example:" );
annotate( description, "Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" );
annotate( description, "Output: 12W1B12W3B24W1B14W" );
annotate( see_also, "http://rosettacode.org/wiki/Run-length_encoding" );
annotate( author, "Ken O. Burtch" );
license( unrestricted );
restriction( no_external_commands );
<b>end</b> <b>pragma</b>;
<b>procedure</b> rle <b>is</b>
<b>function</b> to_rle( s : string ) <b>return</b> string <b>is</b>
<b>begin</b>
<b>if</b> strings.length( s ) = 0 <b>then</b>
<b>return</b> "";
<b>end</b> <b>if</b>;
<b>declare</b>
result : string;
code : character;
prefix : string;
first : natural := 1;
index : natural := 1;
<b>begin</b>
<b>while</b> index <= strings.length( s ) <b>loop</b>
first := index;
index := @+1;
code := strings.element( s, positive(first) );
<b>while</b> index <= strings.length( s ) <b>loop</b>
<b>exit</b> <b>when</b> code /= strings.element( s, positive(index) );
index := @+1;
<b>exit</b> <b>when</b> index-first = 99;
<b>end</b> <b>loop</b>;
prefix := strings.trim( strings.image( index - first ), trim_end.left );
result := @ & prefix & code;
<b>end</b> <b>loop</b>;
<b>return</b> result;
<b>end</b>;
<b>end</b> to_rle;
<b>function</b> from_rle( s : string ) <b>return</b> string <b>is</b>
<b>begin</b>
<b>if</b> strings.length( s ) = 0 <b>then</b>
<b>return</b> "";
<b>end</b> <b>if</b>;
<b>declare</b>
result : string;
index : positive := 1;
prefix : string;
code : character;
<b>begin</b>
<b>loop</b>
prefix := "" & strings.element( s, index );
index := @+1;
<b>if</b> strings.is_digit( strings.element( s, index ) ) <b>then</b>
prefix := @ & strings.element( s, index );
index := @+1;
<b>end</b> <b>if</b>;
code := strings.element( s, index );
index := @+1;
result := @ & ( numerics.value( prefix ) * code );
<b>exit</b> <b>when</b> natural(index) > strings.length( s );
<b>end</b> <b>loop</b>;
<b>return</b> result;
<b>end</b>;
<b>end</b> from_rle;
<b>begin</b>
? to_rle( "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" );
? from_rle( "12W1B12W3B24W1B14W");
<b>end</b> rle;
<FONT COLOR=green><EM>-- VIM editor formatting instructions</EM></FONT>
<FONT COLOR=green><EM>-- vim: ft=spar</EM></FONT>
</PRE></BODY></HTML>
| Java |
# Install script for directory: /home/parallels/new-pi/utils
# Set the install prefix
IF(NOT DEFINED CMAKE_INSTALL_PREFIX)
SET(CMAKE_INSTALL_PREFIX "/usr/local")
ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX)
STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
# Set the install configuration name.
IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
IF(BUILD_TYPE)
STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
ELSE(BUILD_TYPE)
SET(CMAKE_INSTALL_CONFIG_NAME "DEBUG")
ENDIF(BUILD_TYPE)
MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
# Set the component getting installed.
IF(NOT CMAKE_INSTALL_COMPONENT)
IF(COMPONENT)
MESSAGE(STATUS "Install component: \"${COMPONENT}\"")
SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
ELSE(COMPONENT)
SET(CMAKE_INSTALL_COMPONENT)
ENDIF(COMPONENT)
ENDIF(NOT CMAKE_INSTALL_COMPONENT)
# Install shared libraries without execute permission?
IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
SET(CMAKE_INSTALL_SO_NO_EXE "1")
ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
| Java |
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <cstring>
#include "../../Port.h"
#include "../../NLS.h"
#include "../GBA.h"
#include "../GBAGlobals.h"
#include "../GBAinline.h"
#include "../GBACheats.h"
#include "GBACpu.h"
#include "../GBAGfx.h"
#include "../GBASound.h"
#include "../EEprom.h"
#include "../Flash.h"
#include "../Sram.h"
#include "../bios.h"
#include "../elf.h"
#include "../RTC.h"
#include "../agbprint.h"
#include "../../common/System.h"
#include "../../common/SystemGlobals.h"
#include "../../common/Util.h"
#include "../../common/movie.h"
#include "../../common/vbalua.h"
#ifdef PROFILING
#include "../prof/prof.h"
#endif
#ifdef __GNUC__
#define _stricmp strcasecmp
#endif
static inline void interp_rate()
{ /* empty for now */ }
int32 SWITicks = 0;
int32 IRQTicks = 0;
u32 mastercode = 0;
int32 layerEnableDelay = 0;
bool8 busPrefetch = false;
bool8 busPrefetchEnable = false;
u32 busPrefetchCount = 0;
u32 cpuPrefetch[2];
int32 cpuDmaTicksToUpdate = 0;
int32 cpuDmaCount = 0;
bool8 cpuDmaHack = 0;
u32 cpuDmaLast = 0;
int32 dummyAddress = 0;
int32 gbaSaveType = 0; // used to remember the save type on reset
bool8 intState = false;
bool8 stopState = false;
bool8 holdState = false;
int32 holdType = 0;
bool8 cpuSramEnabled = true;
bool8 cpuFlashEnabled = true;
bool8 cpuEEPROMEnabled = true;
bool8 cpuEEPROMSensorEnabled = false;
#ifdef SDL
bool8 cpuBreakLoop = false;
#endif
// These don't seem to affect determinism
int32 cpuNextEvent = 0;
int32 cpuTotalTicks = 0;
#ifdef PROFILING
int profilingTicks = 0;
int profilingTicksReload = 0;
static profile_segment *profilSegment = NULL;
#endif
#ifdef BKPT_SUPPORT
u8 freezeWorkRAM[0x40000];
u8 freezeInternalRAM[0x8000];
u8 freezeVRAM[0x18000];
u8 freezePRAM[0x400];
u8 freezeOAM[0x400];
bool debugger_last;
#endif
int32 lcdTicks = (useBios && !skipBios) ? 1008 : 208;
u8 timerOnOffDelay = 0;
u16 timer0Value = 0;
bool8 timer0On = false;
int32 timer0Ticks = 0;
int32 timer0Reload = 0;
int32 timer0ClockReload = 0;
u16 timer1Value = 0;
bool8 timer1On = false;
int32 timer1Ticks = 0;
int32 timer1Reload = 0;
int32 timer1ClockReload = 0;
u16 timer2Value = 0;
bool8 timer2On = false;
int32 timer2Ticks = 0;
int32 timer2Reload = 0;
int32 timer2ClockReload = 0;
u16 timer3Value = 0;
bool8 timer3On = false;
int32 timer3Ticks = 0;
int32 timer3Reload = 0;
int32 timer3ClockReload = 0;
u32 dma0Source = 0;
u32 dma0Dest = 0;
u32 dma1Source = 0;
u32 dma1Dest = 0;
u32 dma2Source = 0;
u32 dma2Dest = 0;
u32 dma3Source = 0;
u32 dma3Dest = 0;
void (*cpuSaveGameFunc)(u32, u8) = flashSaveDecide;
void (*renderLine)() = mode0RenderLine;
bool8 fxOn = false;
bool8 windowOn = false;
char buffer[1024];
FILE *out = NULL;
const int32 TIMER_TICKS[4] = { 0, 6, 8, 10 };
extern bool8 cpuIsMultiBoot;
extern const u32 objTilesAddress[3] = { 0x010000, 0x014000, 0x014000 };
const u8 gamepakRamWaitState[4] = { 4, 3, 2, 8 };
const u8 gamepakWaitState[4] = { 4, 3, 2, 8 };
const u8 gamepakWaitState0[2] = { 2, 1 };
const u8 gamepakWaitState1[2] = { 4, 1 };
const u8 gamepakWaitState2[2] = { 8, 1 };
const bool8 isInRom[16] =
{ false, false, false, false, false, false, false, false,
true, true, true, true, true, true, false, false };
u8 memoryWait[16] =
{ 0, 0, 2, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 0 };
u8 memoryWait32[16] =
{ 0, 0, 5, 0, 0, 1, 1, 0, 7, 7, 9, 9, 13, 13, 4, 0 };
u8 memoryWaitSeq[16] =
{ 0, 0, 2, 0, 0, 0, 0, 0, 2, 2, 4, 4, 8, 8, 4, 0 };
u8 memoryWaitSeq32[16] =
{ 0, 0, 5, 0, 0, 1, 1, 0, 5, 5, 9, 9, 17, 17, 4, 0 };
// The videoMemoryWait constants are used to add some waitstates
// if the opcode access video memory data outside of vblank/hblank
// It seems to happen on only one ticks for each pixel.
// Not used for now (too problematic with current code).
//const u8 videoMemoryWait[16] =
// {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
static int32 romSize = 0x2000000;
u8 biosProtected[4];
u8 cpuBitsSet[256];
u8 cpuLowestBitSet[256];
#ifdef WORDS_BIGENDIAN
bool8 cpuBiosSwapped = false;
#endif
u32 myROM[] = {
0xEA000006,
0xEA000093,
0xEA000006,
0x00000000,
0x00000000,
0x00000000,
0xEA000088,
0x00000000,
0xE3A00302,
0xE1A0F000,
0xE92D5800,
0xE55EC002,
0xE28FB03C,
0xE79BC10C,
0xE14FB000,
0xE92D0800,
0xE20BB080,
0xE38BB01F,
0xE129F00B,
0xE92D4004,
0xE1A0E00F,
0xE12FFF1C,
0xE8BD4004,
0xE3A0C0D3,
0xE129F00C,
0xE8BD0800,
0xE169F00B,
0xE8BD5800,
0xE1B0F00E,
0x0000009C,
0x0000009C,
0x0000009C,
0x0000009C,
0x000001F8,
0x000001F0,
0x000000AC,
0x000000A0,
0x000000FC,
0x00000168,
0xE12FFF1E,
0xE1A03000,
0xE1A00001,
0xE1A01003,
0xE2113102,
0x42611000,
0xE033C040,
0x22600000,
0xE1B02001,
0xE15200A0,
0x91A02082,
0x3AFFFFFC,
0xE1500002,
0xE0A33003,
0x20400002,
0xE1320001,
0x11A020A2,
0x1AFFFFF9,
0xE1A01000,
0xE1A00003,
0xE1B0C08C,
0x22600000,
0x42611000,
0xE12FFF1E,
0xE92D0010,
0xE1A0C000,
0xE3A01001,
0xE1500001,
0x81A000A0,
0x81A01081,
0x8AFFFFFB,
0xE1A0000C,
0xE1A04001,
0xE3A03000,
0xE1A02001,
0xE15200A0,
0x91A02082,
0x3AFFFFFC,
0xE1500002,
0xE0A33003,
0x20400002,
0xE1320001,
0x11A020A2,
0x1AFFFFF9,
0xE0811003,
0xE1B010A1,
0xE1510004,
0x3AFFFFEE,
0xE1A00004,
0xE8BD0010,
0xE12FFF1E,
0xE0010090,
0xE1A01741,
0xE2611000,
0xE3A030A9,
0xE0030391,
0xE1A03743,
0xE2833E39,
0xE0030391,
0xE1A03743,
0xE2833C09,
0xE283301C,
0xE0030391,
0xE1A03743,
0xE2833C0F,
0xE28330B6,
0xE0030391,
0xE1A03743,
0xE2833C16,
0xE28330AA,
0xE0030391,
0xE1A03743,
0xE2833A02,
0xE2833081,
0xE0030391,
0xE1A03743,
0xE2833C36,
0xE2833051,
0xE0030391,
0xE1A03743,
0xE2833CA2,
0xE28330F9,
0xE0000093,
0xE1A00840,
0xE12FFF1E,
0xE3A00001,
0xE3A01001,
0xE92D4010,
0xE3A03000,
0xE3A04001,
0xE3500000,
0x1B000004,
0xE5CC3301,
0xEB000002,
0x0AFFFFFC,
0xE8BD4010,
0xE12FFF1E,
0xE3A0C301,
0xE5CC3208,
0xE15C20B8,
0xE0110002,
0x10222000,
0x114C20B8,
0xE5CC4208,
0xE12FFF1E,
0xE92D500F,
0xE3A00301,
0xE1A0E00F,
0xE510F004,
0xE8BD500F,
0xE25EF004,
0xE59FD044,
0xE92D5000,
0xE14FC000,
0xE10FE000,
0xE92D5000,
0xE3A0C302,
0xE5DCE09C,
0xE35E00A5,
0x1A000004,
0x05DCE0B4,
0x021EE080,
0xE28FE004,
0x159FF018,
0x059FF018,
0xE59FD018,
0xE8BD5000,
0xE169F00C,
0xE8BD5000,
0xE25EF004,
0x03007FF0,
0x09FE2000,
0x09FFC000,
0x03007FE0
};
variable_desc saveGameStruct[] = {
{ &DISPCNT, sizeof(u16) },
{ &DISPSTAT, sizeof(u16) },
{ &VCOUNT, sizeof(u16) },
{ &BG0CNT, sizeof(u16) },
{ &BG1CNT, sizeof(u16) },
{ &BG2CNT, sizeof(u16) },
{ &BG3CNT, sizeof(u16) },
{ &BG0HOFS, sizeof(u16) },
{ &BG0VOFS, sizeof(u16) },
{ &BG1HOFS, sizeof(u16) },
{ &BG1VOFS, sizeof(u16) },
{ &BG2HOFS, sizeof(u16) },
{ &BG2VOFS, sizeof(u16) },
{ &BG3HOFS, sizeof(u16) },
{ &BG3VOFS, sizeof(u16) },
{ &BG2PA, sizeof(u16) },
{ &BG2PB, sizeof(u16) },
{ &BG2PC, sizeof(u16) },
{ &BG2PD, sizeof(u16) },
{ &BG2X_L, sizeof(u16) },
{ &BG2X_H, sizeof(u16) },
{ &BG2Y_L, sizeof(u16) },
{ &BG2Y_H, sizeof(u16) },
{ &BG3PA, sizeof(u16) },
{ &BG3PB, sizeof(u16) },
{ &BG3PC, sizeof(u16) },
{ &BG3PD, sizeof(u16) },
{ &BG3X_L, sizeof(u16) },
{ &BG3X_H, sizeof(u16) },
{ &BG3Y_L, sizeof(u16) },
{ &BG3Y_H, sizeof(u16) },
{ &WIN0H, sizeof(u16) },
{ &WIN1H, sizeof(u16) },
{ &WIN0V, sizeof(u16) },
{ &WIN1V, sizeof(u16) },
{ &WININ, sizeof(u16) },
{ &WINOUT, sizeof(u16) },
{ &MOSAIC, sizeof(u16) },
{ &BLDMOD, sizeof(u16) },
{ &COLEV, sizeof(u16) },
{ &COLY, sizeof(u16) },
{ &DM0SAD_L, sizeof(u16) },
{ &DM0SAD_H, sizeof(u16) },
{ &DM0DAD_L, sizeof(u16) },
{ &DM0DAD_H, sizeof(u16) },
{ &DM0CNT_L, sizeof(u16) },
{ &DM0CNT_H, sizeof(u16) },
{ &DM1SAD_L, sizeof(u16) },
{ &DM1SAD_H, sizeof(u16) },
{ &DM1DAD_L, sizeof(u16) },
{ &DM1DAD_H, sizeof(u16) },
{ &DM1CNT_L, sizeof(u16) },
{ &DM1CNT_H, sizeof(u16) },
{ &DM2SAD_L, sizeof(u16) },
{ &DM2SAD_H, sizeof(u16) },
{ &DM2DAD_L, sizeof(u16) },
{ &DM2DAD_H, sizeof(u16) },
{ &DM2CNT_L, sizeof(u16) },
{ &DM2CNT_H, sizeof(u16) },
{ &DM3SAD_L, sizeof(u16) },
{ &DM3SAD_H, sizeof(u16) },
{ &DM3DAD_L, sizeof(u16) },
{ &DM3DAD_H, sizeof(u16) },
{ &DM3CNT_L, sizeof(u16) },
{ &DM3CNT_H, sizeof(u16) },
{ &TM0D, sizeof(u16) },
{ &TM0CNT, sizeof(u16) },
{ &TM1D, sizeof(u16) },
{ &TM1CNT, sizeof(u16) },
{ &TM2D, sizeof(u16) },
{ &TM2CNT, sizeof(u16) },
{ &TM3D, sizeof(u16) },
{ &TM3CNT, sizeof(u16) },
{ &P1, sizeof(u16) },
{ &IE, sizeof(u16) },
{ &IF, sizeof(u16) },
{ &IME, sizeof(u16) },
{ &holdState, sizeof(bool8) },
{ &holdType, sizeof(int32) },
{ &lcdTicks, sizeof(int32) },
{ &timer0On, sizeof(bool8) },
{ &timer0Ticks, sizeof(int32) },
{ &timer0Reload, sizeof(int32) },
{ &timer0ClockReload, sizeof(int32) },
{ &timer1On, sizeof(bool8) },
{ &timer1Ticks, sizeof(int32) },
{ &timer1Reload, sizeof(int32) },
{ &timer1ClockReload, sizeof(int32) },
{ &timer2On, sizeof(bool8) },
{ &timer2Ticks, sizeof(int32) },
{ &timer2Reload, sizeof(int32) },
{ &timer2ClockReload, sizeof(int32) },
{ &timer3On, sizeof(bool8) },
{ &timer3Ticks, sizeof(int32) },
{ &timer3Reload, sizeof(int32) },
{ &timer3ClockReload, sizeof(int32) },
{ &dma0Source, sizeof(u32) },
{ &dma0Dest, sizeof(u32) },
{ &dma1Source, sizeof(u32) },
{ &dma1Dest, sizeof(u32) },
{ &dma2Source, sizeof(u32) },
{ &dma2Dest, sizeof(u32) },
{ &dma3Source, sizeof(u32) },
{ &dma3Dest, sizeof(u32) },
{ &fxOn, sizeof(bool8) },
{ &windowOn, sizeof(bool8) },
{ &N_FLAG, sizeof(bool8) },
{ &C_FLAG, sizeof(bool8) },
{ &Z_FLAG, sizeof(bool8) },
{ &V_FLAG, sizeof(bool8) },
{ &armState, sizeof(bool8) },
{ &armIrqEnable, sizeof(bool8) },
{ &armNextPC, sizeof(u32) },
{ &armMode, sizeof(int32) },
{ &saveType, sizeof(int32) },
{ NULL, 0 }
};
/////////////////////////////////////////////
#ifdef PROFILING
void cpuProfil(profile_segment *seg)
{
profilSegment = seg;
}
void cpuEnableProfiling(int hz)
{
if (hz == 0)
hz = 100;
profilingTicks = profilingTicksReload = 16777216 / hz;
profSetHertz(hz);
}
#endif
inline int CPUUpdateTicks()
{
int cpuLoopTicks = lcdTicks;
if (soundTicks < cpuLoopTicks)
cpuLoopTicks = soundTicks;
if (timer0On && (timer0Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer0Ticks;
}
if (timer1On && !(TM1CNT & 4) && (timer1Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer1Ticks;
}
if (timer2On && !(TM2CNT & 4) && (timer2Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer2Ticks;
}
if (timer3On && !(TM3CNT & 4) && (timer3Ticks < cpuLoopTicks))
{
cpuLoopTicks = timer3Ticks;
}
#ifdef PROFILING
if (profilingTicksReload != 0)
{
if (profilingTicks < cpuLoopTicks)
{
cpuLoopTicks = profilingTicks;
}
}
#endif
if (SWITicks)
{
if (SWITicks < cpuLoopTicks)
cpuLoopTicks = SWITicks;
}
if (IRQTicks)
{
if (IRQTicks < cpuLoopTicks)
cpuLoopTicks = IRQTicks;
}
return cpuLoopTicks;
}
void CPUUpdateWindow0()
{
int x00 = WIN0H >> 8;
int x01 = WIN0H & 255;
if (x00 <= x01)
{
for (int i = 0; i < 240; i++)
{
gfxInWin0[i] = (i >= x00 && i < x01);
}
}
else
{
for (int i = 0; i < 240; i++)
{
gfxInWin0[i] = (i >= x00 || i < x01);
}
}
}
void CPUUpdateWindow1()
{
int x00 = WIN1H >> 8;
int x01 = WIN1H & 255;
if (x00 <= x01)
{
for (int i = 0; i < 240; i++)
{
gfxInWin1[i] = (i >= x00 && i < x01);
}
}
else
{
for (int i = 0; i < 240; i++)
{
gfxInWin1[i] = (i >= x00 || i < x01);
}
}
}
#define CLEAR_ARRAY(a) \
{ \
u32 *array = (a); \
for (int i = 0; i < 240; i++) { \
*array++ = 0x80000000; \
} \
} \
void CPUUpdateRenderBuffers(bool force)
{
if (!(layerEnable & 0x0100) || force)
{
CLEAR_ARRAY(line0);
}
if (!(layerEnable & 0x0200) || force)
{
CLEAR_ARRAY(line1);
}
if (!(layerEnable & 0x0400) || force)
{
CLEAR_ARRAY(line2);
}
if (!(layerEnable & 0x0800) || force)
{
CLEAR_ARRAY(line3);
}
}
#undef CLEAR_ARRAY
bool CPUWriteStateToStream(gzFile gzFile)
{
utilWriteInt(gzFile, SAVE_GAME_VERSION);
utilGzWrite(gzFile, &rom[0xa0], 16);
utilWriteInt(gzFile, useBios);
utilGzWrite(gzFile, ®[0], sizeof(reg));
utilWriteData(gzFile, saveGameStruct);
// new to version 0.7.1
utilWriteInt(gzFile, stopState);
// new to version 0.8
utilWriteInt(gzFile, intState);
utilGzWrite(gzFile, internalRAM, 0x8000);
utilGzWrite(gzFile, paletteRAM, 0x400);
utilGzWrite(gzFile, workRAM, 0x40000);
utilGzWrite(gzFile, vram, 0x20000);
utilGzWrite(gzFile, oam, 0x400);
utilGzWrite(gzFile, pix, 4 * 241 * 162);
utilGzWrite(gzFile, ioMem, 0x400);
eepromSaveGame(gzFile);
flashSaveGame(gzFile);
soundSaveGame(gzFile);
cheatsSaveGame(gzFile);
// version 1.5
rtcSaveGame(gzFile);
// SAVE_GAME_VERSION_9 (new to re-recording version which is based on 1.72)
{
utilGzWrite(gzFile, &sensorX, sizeof(sensorX));
utilGzWrite(gzFile, &sensorY, sizeof(sensorY));
bool8 movieActive = VBAMovieIsActive();
utilGzWrite(gzFile, &movieActive, sizeof(movieActive));
if (movieActive)
{
uint8 *movie_freeze_buf = NULL;
uint32 movie_freeze_size = 0;
int code = VBAMovieFreeze(&movie_freeze_buf, &movie_freeze_size);
if (movie_freeze_buf)
{
utilGzWrite(gzFile, &movie_freeze_size, sizeof(movie_freeze_size));
utilGzWrite(gzFile, movie_freeze_buf, movie_freeze_size);
delete [] movie_freeze_buf;
}
else
{
if (code == MOVIE_UNRECORDED_INPUT)
{
systemMessage(0, N_("Cannot make a movie snapshot as long as there are unrecorded input changes."));
}
else
{
systemMessage(0, N_("Failed to save movie snapshot."));
}
return false;
}
}
utilGzWrite(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount));
}
// SAVE_GAME_VERSION_13
{
utilGzWrite(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount));
utilGzWrite(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged));
utilGzWrite(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast));
}
// SAVE_GAME_VERSION_14
{
utilGzWrite(gzFile, memoryWait, 16 * sizeof(u8));
utilGzWrite(gzFile, memoryWait32, 16 * sizeof(u8));
utilGzWrite(gzFile, memoryWaitSeq, 16 * sizeof(u8));
utilGzWrite(gzFile, memoryWaitSeq32, 16 * sizeof(u8));
utilGzWrite(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used...
}
return true;
}
bool CPUWriteState(const char *file)
{
gzFile gzFile = utilGzOpen(file, "wb");
if (gzFile == NULL)
{
systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"), file);
return false;
}
bool res = CPUWriteStateToStream(gzFile);
utilGzClose(gzFile);
return res;
}
bool CPUWriteMemState(char *memory, int available)
{
gzFile gzFile = utilMemGzOpen(memory, available, "w");
if (gzFile == NULL)
{
return false;
}
bool res = CPUWriteStateToStream(gzFile);
long pos = utilGzTell(gzFile) + 8;
if (pos >= (available))
res = false;
utilGzClose(gzFile);
return res;
}
bool CPUReadStateFromStream(gzFile gzFile)
{
char tempBackupName[128];
if (tempSaveSafe)
{
sprintf(tempBackupName, "gbatempsave%d.sav", tempSaveID++);
CPUWriteState(tempBackupName);
}
int version = utilReadInt(gzFile);
if (version > SAVE_GAME_VERSION || version < SAVE_GAME_VERSION_1)
{
systemMessage(MSG_UNSUPPORTED_VBA_SGM,
N_("Unsupported VisualBoyAdvance save game version %d"),
version);
goto failedLoad;
}
u8 romname[17];
utilGzRead(gzFile, romname, 16);
if (memcmp(&rom[0xa0], romname, 16) != 0)
{
romname[16] = 0;
for (int i = 0; i < 16; i++)
if (romname[i] < 32)
romname[i] = 32;
systemMessage(MSG_CANNOT_LOAD_SGM, N_("Cannot load save game for %s"), romname);
goto failedLoad;
}
bool8 ub = utilReadInt(gzFile) ? true : false;
if (ub != useBios)
{
if (useBios)
systemMessage(MSG_SAVE_GAME_NOT_USING_BIOS,
N_("Save game is not using the BIOS files"));
else
systemMessage(MSG_SAVE_GAME_USING_BIOS,
N_("Save game is using the BIOS file"));
goto failedLoad;
}
utilGzRead(gzFile, ®[0], sizeof(reg));
utilReadData(gzFile, saveGameStruct);
if (version < SAVE_GAME_VERSION_3)
stopState = false;
else
stopState = utilReadInt(gzFile) ? true : false;
if (version < SAVE_GAME_VERSION_4)
intState = false;
else
intState = utilReadInt(gzFile) ? true : false;
utilGzRead(gzFile, internalRAM, 0x8000);
utilGzRead(gzFile, paletteRAM, 0x400);
utilGzRead(gzFile, workRAM, 0x40000);
utilGzRead(gzFile, vram, 0x20000);
utilGzRead(gzFile, oam, 0x400);
if (version < SAVE_GAME_VERSION_6)
utilGzRead(gzFile, pix, 4 * 240 * 160);
else
utilGzRead(gzFile, pix, 4 * 241 * 162);
utilGzRead(gzFile, ioMem, 0x400);
if (skipSaveGameBattery)
{
// skip eeprom data
eepromReadGameSkip(gzFile, version);
// skip flash data
flashReadGameSkip(gzFile, version);
}
else
{
eepromReadGame(gzFile, version);
flashReadGame(gzFile, version);
}
soundReadGame(gzFile, version);
if (version > SAVE_GAME_VERSION_1)
{
if (skipSaveGameCheats)
{
// skip cheats list data
cheatsReadGameSkip(gzFile, version);
}
else
{
cheatsReadGame(gzFile, version);
}
}
if (version > SAVE_GAME_VERSION_6)
{
rtcReadGame(gzFile);
}
if (version <= SAVE_GAME_VERSION_7)
{
u32 temp;
#define SWAP(a, b, c) \
temp = (a); \
(a) = (b) << 16 | (c); \
(b) = (temp) >> 16; \
(c) = (temp) & 0xFFFF;
SWAP(dma0Source, DM0SAD_H, DM0SAD_L);
SWAP(dma0Dest, DM0DAD_H, DM0DAD_L);
SWAP(dma1Source, DM1SAD_H, DM1SAD_L);
SWAP(dma1Dest, DM1DAD_H, DM1DAD_L);
SWAP(dma2Source, DM2SAD_H, DM2SAD_L);
SWAP(dma2Dest, DM2DAD_H, DM2DAD_L);
SWAP(dma3Source, DM3SAD_H, DM3SAD_L);
SWAP(dma3Dest, DM3DAD_H, DM3DAD_L);
}
#undef SWAP
if (version <= SAVE_GAME_VERSION_8)
{
timer0ClockReload = TIMER_TICKS[TM0CNT & 3];
timer1ClockReload = TIMER_TICKS[TM1CNT & 3];
timer2ClockReload = TIMER_TICKS[TM2CNT & 3];
timer3ClockReload = TIMER_TICKS[TM3CNT & 3];
timer0Ticks = ((0x10000 - TM0D) << timer0ClockReload) - timer0Ticks;
timer1Ticks = ((0x10000 - TM1D) << timer1ClockReload) - timer1Ticks;
timer2Ticks = ((0x10000 - TM2D) << timer2ClockReload) - timer2Ticks;
timer3Ticks = ((0x10000 - TM3D) << timer3ClockReload) - timer3Ticks;
interp_rate();
}
// set pointers!
layerEnable = layerSettings & DISPCNT;
CPUUpdateRender();
CPUUpdateRenderBuffers(true);
CPUUpdateWindow0();
CPUUpdateWindow1();
gbaSaveType = 0;
switch (saveType)
{
case 0:
cpuSaveGameFunc = flashSaveDecide;
break;
case 1:
cpuSaveGameFunc = sramWrite;
gbaSaveType = 1;
break;
case 2:
cpuSaveGameFunc = flashWrite;
gbaSaveType = 2;
break;
case 3:
break;
case 5:
gbaSaveType = 5;
break;
default:
systemMessage(MSG_UNSUPPORTED_SAVE_TYPE,
N_("Unsupported save type %d"), saveType);
break;
}
if (eepromInUse)
gbaSaveType = 3;
systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
bool wasPlayingMovie = VBAMovieIsActive() && VBAMovieIsPlaying();
if (version >= SAVE_GAME_VERSION_9) // new to re-recording version:
{
utilGzRead(gzFile, &sensorX, sizeof(sensorX));
utilGzRead(gzFile, &sensorY, sizeof(sensorY));
bool8 movieSnapshot;
utilGzRead(gzFile, &movieSnapshot, sizeof(movieSnapshot));
if (VBAMovieIsActive() && !movieSnapshot)
{
systemMessage(0, N_("Can't load a non-movie snapshot while a movie is active."));
goto failedLoad;
}
if (movieSnapshot) // even if a movie isn't active we still want to parse through this
// because we have already got stuff added in this save format
{
uint32 movieInputDataSize = 0;
utilGzRead(gzFile, &movieInputDataSize, sizeof(movieInputDataSize));
uint8 *local_movie_data = new uint8[movieInputDataSize];
int readBytes = utilGzRead(gzFile, local_movie_data, movieInputDataSize);
if (readBytes != movieInputDataSize)
{
systemMessage(0, N_("Corrupt movie snapshot."));
delete [] local_movie_data;
goto failedLoad;
}
int code = VBAMovieUnfreeze(local_movie_data, movieInputDataSize);
delete [] local_movie_data;
if (code != MOVIE_SUCCESS && VBAMovieIsActive())
{
char errStr [1024];
strcpy(errStr, "Failed to load movie snapshot");
switch (code)
{
case MOVIE_NOT_FROM_THIS_MOVIE:
strcat(errStr, ";\nSnapshot not from this movie"); break;
case MOVIE_NOT_FROM_A_MOVIE:
strcat(errStr, ";\nNot a movie snapshot"); break; // shouldn't get here...
case MOVIE_UNVERIFIABLE_POST_END:
sprintf(errStr, "%s;\nSnapshot unverifiable with movie after End Frame %u", errStr, VBAMovieGetLastErrorInfo()); break;
case MOVIE_TIMELINE_INCONSISTENT_AT:
sprintf(errStr, "%s;\nSnapshot inconsistent with movie at Frame %u", errStr, VBAMovieGetLastErrorInfo()); break;
case MOVIE_WRONG_FORMAT:
strcat(errStr, ";\nWrong format"); break;
}
strcat(errStr, ".");
systemMessage(0, N_(errStr));
goto failedLoad;
}
}
utilGzRead(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount));
}
if (version < SAVE_GAME_VERSION_14)
{
if (version >= SAVE_GAME_VERSION_10)
{
utilGzSeek(gzFile, 16 * sizeof(int32) * 6, SEEK_CUR);
}
if (version >= SAVE_GAME_VERSION_11)
{
utilGzSeek(gzFile, sizeof(bool8) * 3, SEEK_CUR);
}
if (version >= SAVE_GAME_VERSION_12)
{
utilGzSeek(gzFile, sizeof(bool8) * 2, SEEK_CUR);
}
}
if (version >= SAVE_GAME_VERSION_13)
{
utilGzRead(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount));
utilGzRead(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged));
utilGzRead(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast));
}
if (version >= SAVE_GAME_VERSION_14)
{
utilGzRead(gzFile, memoryWait, 16 * sizeof(u8));
utilGzRead(gzFile, memoryWait32, 16 * sizeof(u8));
utilGzRead(gzFile, memoryWaitSeq, 16 * sizeof(u8));
utilGzRead(gzFile, memoryWaitSeq32, 16 * sizeof(u8));
utilGzRead(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used...
}
if (armState)
{
ARM_PREFETCH;
}
else
{
THUMB_PREFETCH;
}
CPUUpdateRegister(0x204, CPUReadHalfWordQuick(0x4000204));
systemSetJoypad(0, ~P1 & 0x3FF);
VBAUpdateButtonPressDisplay();
VBAUpdateFrameCountDisplay();
systemRefreshScreen();
if (tempSaveSafe)
{
remove(tempBackupName);
tempSaveAttempts = 0;
}
return true;
failedLoad:
if (tempSaveSafe)
{
tempSaveAttempts++;
if (tempSaveAttempts < 3) // fail no more than 2 times in a row
CPUReadState(tempBackupName);
remove(tempBackupName);
}
if (wasPlayingMovie && VBAMovieIsRecording())
{
VBAMovieSwitchToPlaying();
}
return false;
}
bool CPUReadMemState(char *memory, int available)
{
gzFile gzFile = utilMemGzOpen(memory, available, "r");
tempSaveSafe = false;
bool res = CPUReadStateFromStream(gzFile);
tempSaveSafe = true;
utilGzClose(gzFile);
return res;
}
bool CPUReadState(const char *file)
{
gzFile gzFile = utilGzOpen(file, "rb");
if (gzFile == NULL)
return false;
bool res = CPUReadStateFromStream(gzFile);
utilGzClose(gzFile);
return res;
}
bool CPUExportEepromFile(const char *fileName)
{
if (eepromInUse)
{
FILE *file = fopen(fileName, "wb");
if (!file)
{
systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"),
fileName);
return false;
}
for (int i = 0; i < eepromSize; )
{
for (int j = 0; j < 8; j++)
{
if (fwrite(&eepromData[i + 7 - j], 1, 1, file) != 1)
{
fclose(file);
return false;
}
}
i += 8;
}
fclose(file);
}
return true;
}
bool CPUWriteBatteryToStream(gzFile gzFile)
{
if (!gzFile)
return false;
utilWriteInt(gzFile, SAVE_GAME_VERSION);
// for simplicity, we put both types of battery files should be in the stream, even if one's empty
eepromSaveGame(gzFile);
flashSaveGame(gzFile);
return true;
}
bool CPUWriteBatteryFile(const char *fileName)
{
if (gbaSaveType == 0)
{
if (eepromInUse)
gbaSaveType = 3;
else
switch (saveType)
{
case 1:
gbaSaveType = 1;
break;
case 2:
gbaSaveType = 2;
break;
}
}
if ((gbaSaveType != 0) && (gbaSaveType != 5))
{
FILE *file = fopen(fileName, "wb");
if (!file)
{
systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"),
fileName);
return false;
}
// only save if Flash/Sram in use or EEprom in use
if (gbaSaveType != 3)
{
if (gbaSaveType == 2)
{
if (fwrite(flashSaveMemory, 1, flashSize, file) != (size_t)flashSize)
{
fclose(file);
return false;
}
}
else
{
if (fwrite(flashSaveMemory, 1, 0x10000, file) != 0x10000)
{
fclose(file);
return false;
}
}
}
else
{
if (fwrite(eepromData, 1, eepromSize, file) != (size_t)eepromSize)
{
fclose(file);
return false;
}
}
fclose(file);
}
return true;
}
bool CPUReadGSASnapshot(const char *fileName)
{
int i;
FILE *file = fopen(fileName, "rb");
if (!file)
{
systemMessage(MSG_CANNOT_OPEN_FILE, N_("Cannot open file %s"), fileName);
return false;
}
// check file size to know what we should read
fseek(file, 0, SEEK_END);
// long size = ftell(file);
fseek(file, 0x0, SEEK_SET);
fread(&i, 1, 4, file);
fseek(file, i, SEEK_CUR); // Skip SharkPortSave
fseek(file, 4, SEEK_CUR); // skip some sort of flag
fread(&i, 1, 4, file); // name length
fseek(file, i, SEEK_CUR); // skip name
fread(&i, 1, 4, file); // desc length
fseek(file, i, SEEK_CUR); // skip desc
fread(&i, 1, 4, file); // notes length
fseek(file, i, SEEK_CUR); // skip notes
int saveSize;
fread(&saveSize, 1, 4, file); // read length
saveSize -= 0x1c; // remove header size
char buffer[17];
char buffer2[17];
fread(buffer, 1, 16, file);
buffer[16] = 0;
for (i = 0; i < 16; i++)
if (buffer[i] < 32)
buffer[i] = 32;
memcpy(buffer2, &rom[0xa0], 16);
buffer2[16] = 0;
for (i = 0; i < 16; i++)
if (buffer2[i] < 32)
buffer2[i] = 32;
if (memcmp(buffer, buffer2, 16))
{
systemMessage(MSG_CANNOT_IMPORT_SNAPSHOT_FOR,
N_("Cannot import snapshot for %s. Current game is %s"),
buffer,
buffer2);
fclose(file);
return false;
}
fseek(file, 12, SEEK_CUR); // skip some flags
if (saveSize >= 65536)
{
if (fread(flashSaveMemory, 1, saveSize, file) != (size_t)saveSize)
{
fclose(file);
return false;
}
}
else
{
systemMessage(MSG_UNSUPPORTED_SNAPSHOT_FILE,
N_("Unsupported snapshot file %s"),
fileName);
fclose(file);
return false;
}
fclose(file);
CPUReset();
return true;
}
bool CPUWriteGSASnapshot(const char *fileName,
const char *title,
const char *desc,
const char *notes)
{
FILE *file = fopen(fileName, "wb");
if (!file)
{
systemMessage(MSG_CANNOT_OPEN_FILE, N_("Cannot open file %s"), fileName);
return false;
}
u8 buffer[17];
utilPutDword(buffer, 0x0d); // SharkPortSave length
fwrite(buffer, 1, 4, file);
fwrite("SharkPortSave", 1, 0x0d, file);
utilPutDword(buffer, 0x000f0000);
fwrite(buffer, 1, 4, file); // save type 0x000f0000 = GBA save
utilPutDword(buffer, (u32)strlen(title));
fwrite(buffer, 1, 4, file); // title length
fwrite(title, 1, strlen(title), file);
utilPutDword(buffer, (u32)strlen(desc));
fwrite(buffer, 1, 4, file); // desc length
fwrite(desc, 1, strlen(desc), file);
utilPutDword(buffer, (u32)strlen(notes));
fwrite(buffer, 1, 4, file); // notes length
fwrite(notes, 1, strlen(notes), file);
int saveSize = 0x10000;
if (gbaSaveType == 2)
saveSize = flashSize;
int totalSize = saveSize + 0x1c;
utilPutDword(buffer, totalSize); // length of remainder of save - CRC
fwrite(buffer, 1, 4, file);
char *temp = new char[0x2001c];
memset(temp, 0, 28);
memcpy(temp, &rom[0xa0], 16); // copy internal name
temp[0x10] = rom[0xbe]; // reserved area (old checksum)
temp[0x11] = rom[0xbf]; // reserved area (old checksum)
temp[0x12] = rom[0xbd]; // complement check
temp[0x13] = rom[0xb0]; // maker
temp[0x14] = 1; // 1 save ?
memcpy(&temp[0x1c], flashSaveMemory, saveSize); // copy save
fwrite(temp, 1, totalSize, file); // write save + header
u32 crc = 0;
for (int i = 0; i < totalSize; i++)
{
crc += ((u32)temp[i] << (crc % 0x18));
}
utilPutDword(buffer, crc);
fwrite(buffer, 1, 4, file); // CRC?
fclose(file);
delete [] temp;
return true;
}
bool CPUImportEepromFile(const char *fileName)
{
FILE *file = fopen(fileName, "rb");
if (!file)
return false;
// check file size to know what we should read
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
if (size == 512 || size == 0x2000)
{
if (fread(eepromData, 1, size, file) != (size_t)size)
{
fclose(file);
return false;
}
for (int i = 0; i < size; )
{
u8 tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
tmp = eepromData[i];
eepromData[i] = eepromData[7 - i];
eepromData[7 - i] = tmp;
i++;
i += 4;
}
}
else
{
fclose(file);
return false;
}
fclose(file);
return true;
}
bool CPUReadBatteryFromStream(gzFile gzFile)
{
if (!gzFile)
return false;
int version = utilReadInt(gzFile);
// for simplicity, we put both types of battery files should be in the stream, even if one's empty
eepromReadGame(gzFile, version);
flashReadGame(gzFile, version);
return true;
}
bool CPUReadBatteryFile(const char *fileName)
{
FILE *file = fopen(fileName, "rb");
if (!file)
return false;
// check file size to know what we should read
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);
systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
if (size == 512 || size == 0x2000)
{
if (fread(eepromData, 1, size, file) != (size_t)size)
{
fclose(file);
return false;
}
}
else
{
if (size == 0x20000)
{
if (fread(flashSaveMemory, 1, 0x20000, file) != 0x20000)
{
fclose(file);
return false;
}
flashSetSize(0x20000);
}
else
{
if (fread(flashSaveMemory, 1, 0x10000, file) != 0x10000)
{
fclose(file);
return false;
}
flashSetSize(0x10000);
}
}
fclose(file);
return true;
}
bool CPUWritePNGFile(const char *fileName)
{
return utilWritePNGFile(fileName, 240, 160, pix);
}
bool CPUWriteBMPFile(const char *fileName)
{
return utilWriteBMPFile(fileName, 240, 160, pix);
}
void CPUCleanUp()
{
#ifdef PROFILING
if (profilingTicksReload)
{
profCleanup();
}
#endif
PIX_FREE(pix);
pix = NULL;
free(bios);
bios = NULL;
free(rom);
rom = NULL;
free(internalRAM);
internalRAM = NULL;
free(workRAM);
workRAM = NULL;
free(paletteRAM);
paletteRAM = NULL;
free(vram);
vram = NULL;
free(oam);
oam = NULL;
free(ioMem);
ioMem = NULL;
#if 0
eepromErase();
flashErase();
#endif
#ifndef NO_DEBUGGER
elfCleanUp();
#endif
systemCleanUp();
systemRefreshScreen();
}
int CPULoadRom(const char *szFile)
{
int size = 0x2000000;
if (rom != NULL)
{
CPUCleanUp();
}
systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
rom = (u8 *)malloc(0x2000000);
if (rom == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"ROM");
return 0;
}
// FIXME: size+4 is so RAM search and watch are safe to read any byte in the allocated region as a 4-byte int
workRAM = (u8 *)RAM_CALLOC(0x40000);
if (workRAM == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"WRAM");
return 0;
}
u8 *whereToLoad = cpuIsMultiBoot ? workRAM : rom;
#ifndef NO_DEBUGGER
if (utilIsELF(szFile))
{
FILE *f = fopen(szFile, "rb");
if (!f)
{
systemMessage(MSG_ERROR_OPENING_IMAGE, N_("Error opening image %s"),
szFile);
CPUCleanUp();
return 0;
}
bool res = elfRead(szFile, size, f);
if (!res || size == 0)
{
CPUCleanUp();
elfCleanUp();
return 0;
}
}
else
#endif //NO_DEBUGGER
if (szFile != NULL)
{
if (!utilLoad(szFile,
utilIsGBAImage,
whereToLoad,
size))
{
CPUCleanUp();
return 0;
}
}
u16 *temp = (u16 *)(rom + ((size + 1) & ~1));
for (int i = (size + 1) & ~1; i < 0x2000000; i += 2)
{
WRITE16LE(temp, (i >> 1) & 0xFFFF);
temp++;
}
pix = (u8 *)PIX_CALLOC(4 * 241 * 162);
if (pix == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"PIX");
CPUCleanUp();
return 0;
}
bios = (u8 *)RAM_CALLOC(0x4000);
if (bios == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"BIOS");
CPUCleanUp();
return 0;
}
internalRAM = (u8 *)RAM_CALLOC(0x8000);
if (internalRAM == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"IRAM");
CPUCleanUp();
return 0;
}
paletteRAM = (u8 *)RAM_CALLOC(0x400);
if (paletteRAM == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"PRAM");
CPUCleanUp();
return 0;
}
vram = (u8 *)RAM_CALLOC(0x20000);
if (vram == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"VRAM");
CPUCleanUp();
return 0;
}
oam = (u8 *)RAM_CALLOC(0x400);
if (oam == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"OAM");
CPUCleanUp();
return 0;
}
ioMem = (u8 *)RAM_CALLOC(0x400);
if (ioMem == NULL)
{
systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"),
"IO");
CPUCleanUp();
return 0;
}
flashInit();
eepromInit();
CPUUpdateRenderBuffers(true);
romSize = size;
return size;
}
void CPUDoMirroring(bool b)
{
u32 mirroredRomSize = (((romSize) >> 20) & 0x3F) << 20;
u32 mirroredRomAddress = romSize;
if ((mirroredRomSize <= 0x800000) && (b))
{
mirroredRomAddress = mirroredRomSize;
if (mirroredRomSize == 0)
mirroredRomSize = 0x100000;
while (mirroredRomAddress < 0x01000000)
{
memcpy((u16 *)(rom + mirroredRomAddress), (u16 *)(rom), mirroredRomSize);
mirroredRomAddress += mirroredRomSize;
}
}
}
// Emulates the Cheat System (m) code
void CPUMasterCodeCheck()
{
if (cheatsEnabled)
{
if ((mastercode) && (mastercode == armNextPC))
{
u32 joy = 0;
if (systemReadJoypads())
joy = systemGetJoypad(0, cpuEEPROMSensorEnabled);
u32 ext = (joy >> 10);
cpuTotalTicks += cheatsCheckKeys(P1 ^ 0x3FF, ext);
}
}
}
void CPUUpdateRender()
{
switch (DISPCNT & 7)
{
case 0:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode0RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode0RenderLineNoWindow;
else
renderLine = mode0RenderLineAll;
break;
case 1:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode1RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode1RenderLineNoWindow;
else
renderLine = mode1RenderLineAll;
break;
case 2:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode2RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode2RenderLineNoWindow;
else
renderLine = mode2RenderLineAll;
break;
case 3:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode3RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode3RenderLineNoWindow;
else
renderLine = mode3RenderLineAll;
break;
case 4:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode4RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode4RenderLineNoWindow;
else
renderLine = mode4RenderLineAll;
break;
case 5:
if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) ||
cpuDisableSfx)
renderLine = mode5RenderLine;
else if (fxOn && !windowOn && !(layerEnable & 0x8000))
renderLine = mode5RenderLineNoWindow;
else
renderLine = mode5RenderLineAll;
default:
break;
}
}
void CPUUpdateCPSR()
{
u32 CPSR = reg[16].I & 0x40;
if (N_FLAG)
CPSR |= 0x80000000;
if (Z_FLAG)
CPSR |= 0x40000000;
if (C_FLAG)
CPSR |= 0x20000000;
if (V_FLAG)
CPSR |= 0x10000000;
if (!armState)
CPSR |= 0x00000020;
if (!armIrqEnable)
CPSR |= 0x80;
CPSR |= (armMode & 0x1F);
reg[16].I = CPSR;
}
void CPUUpdateFlags(bool breakLoop)
{
u32 CPSR = reg[16].I;
N_FLAG = (CPSR & 0x80000000) ? true : false;
Z_FLAG = (CPSR & 0x40000000) ? true : false;
C_FLAG = (CPSR & 0x20000000) ? true : false;
V_FLAG = (CPSR & 0x10000000) ? true : false;
armState = (CPSR & 0x20) ? false : true;
armIrqEnable = (CPSR & 0x80) ? false : true;
if (breakLoop)
{
if (armIrqEnable && (IF & IE) && (IME & 1))
cpuNextEvent = cpuTotalTicks;
}
}
void CPUUpdateFlags()
{
CPUUpdateFlags(true);
}
#ifdef WORDS_BIGENDIAN
static void CPUSwap(volatile u32 *a, volatile u32 *b)
{
volatile u32 c = *b;
*b = *a;
*a = c;
}
#else
static void CPUSwap(u32 *a, u32 *b)
{
u32 c = *b;
*b = *a;
*a = c;
}
#endif
void CPUSwitchMode(int mode, bool saveState, bool breakLoop)
{
// if(armMode == mode)
// return;
CPUUpdateCPSR();
switch (armMode)
{
case 0x10:
case 0x1F:
reg[R13_USR].I = reg[13].I;
reg[R14_USR].I = reg[14].I;
reg[17].I = reg[16].I;
break;
case 0x11:
CPUSwap(®[R8_FIQ].I, ®[8].I);
CPUSwap(®[R9_FIQ].I, ®[9].I);
CPUSwap(®[R10_FIQ].I, ®[10].I);
CPUSwap(®[R11_FIQ].I, ®[11].I);
CPUSwap(®[R12_FIQ].I, ®[12].I);
reg[R13_FIQ].I = reg[13].I;
reg[R14_FIQ].I = reg[14].I;
reg[SPSR_FIQ].I = reg[17].I;
break;
case 0x12:
reg[R13_IRQ].I = reg[13].I;
reg[R14_IRQ].I = reg[14].I;
reg[SPSR_IRQ].I = reg[17].I;
break;
case 0x13:
reg[R13_SVC].I = reg[13].I;
reg[R14_SVC].I = reg[14].I;
reg[SPSR_SVC].I = reg[17].I;
break;
case 0x17:
reg[R13_ABT].I = reg[13].I;
reg[R14_ABT].I = reg[14].I;
reg[SPSR_ABT].I = reg[17].I;
break;
case 0x1b:
reg[R13_UND].I = reg[13].I;
reg[R14_UND].I = reg[14].I;
reg[SPSR_UND].I = reg[17].I;
break;
}
u32 CPSR = reg[16].I;
u32 SPSR = reg[17].I;
switch (mode)
{
case 0x10:
case 0x1F:
reg[13].I = reg[R13_USR].I;
reg[14].I = reg[R14_USR].I;
reg[16].I = SPSR;
break;
case 0x11:
CPUSwap(®[8].I, ®[R8_FIQ].I);
CPUSwap(®[9].I, ®[R9_FIQ].I);
CPUSwap(®[10].I, ®[R10_FIQ].I);
CPUSwap(®[11].I, ®[R11_FIQ].I);
CPUSwap(®[12].I, ®[R12_FIQ].I);
reg[13].I = reg[R13_FIQ].I;
reg[14].I = reg[R14_FIQ].I;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_FIQ].I;
break;
case 0x12:
reg[13].I = reg[R13_IRQ].I;
reg[14].I = reg[R14_IRQ].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_IRQ].I;
break;
case 0x13:
reg[13].I = reg[R13_SVC].I;
reg[14].I = reg[R14_SVC].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_SVC].I;
break;
case 0x17:
reg[13].I = reg[R13_ABT].I;
reg[14].I = reg[R14_ABT].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_ABT].I;
break;
case 0x1b:
reg[13].I = reg[R13_UND].I;
reg[14].I = reg[R14_UND].I;
reg[16].I = SPSR;
if (saveState)
reg[17].I = CPSR;
else
reg[17].I = reg[SPSR_UND].I;
break;
default:
systemMessage(MSG_UNSUPPORTED_ARM_MODE, N_("Unsupported ARM mode %02x"), mode);
break;
}
armMode = mode;
CPUUpdateFlags(breakLoop);
CPUUpdateCPSR();
}
void CPUSwitchMode(int mode, bool saveState)
{
CPUSwitchMode(mode, saveState, true);
}
void CPUUndefinedException()
{
u32 PC = reg[15].I;
bool savedArmState = armState;
CPUSwitchMode(0x1b, true, false);
reg[14].I = PC - (savedArmState ? 4 : 2);
reg[15].I = 0x04;
armState = true;
armIrqEnable = false;
armNextPC = 0x04;
ARM_PREFETCH;
reg[15].I += 4;
}
void CPUSoftwareInterrupt()
{
u32 PC = reg[15].I;
bool savedArmState = armState;
CPUSwitchMode(0x13, true, false);
reg[14].I = PC - (savedArmState ? 4 : 2);
reg[15].I = 0x08;
armState = true;
armIrqEnable = false;
armNextPC = 0x08;
ARM_PREFETCH;
reg[15].I += 4;
}
void CPUSoftwareInterrupt(int comment)
{
static bool disableMessage = false;
if (armState)
comment >>= 16;
#ifdef BKPT_SUPPORT
if (comment == 0xff)
{
dbgOutput(NULL, reg[0].I);
return;
}
#endif
#ifdef PROFILING
if (comment == 0xfe)
{
profStartup(reg[0].I, reg[1].I);
return;
}
if (comment == 0xfd)
{
profControl(reg[0].I);
return;
}
if (comment == 0xfc)
{
profCleanup();
return;
}
if (comment == 0xfb)
{
profCount();
return;
}
#endif
if (comment == 0xfa)
{
agbPrintFlush();
return;
}
#ifdef SDL
if (comment == 0xf9)
{
emulating = 0;
cpuNextEvent = cpuTotalTicks;
cpuBreakLoop = true;
return;
}
#endif
if (useBios)
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment,
armState ? armNextPC - 4 : armNextPC - 2,
reg[0].I,
reg[1].I,
reg[2].I,
VCOUNT);
}
#endif
CPUSoftwareInterrupt();
return;
}
// This would be correct, but it causes problems if uncommented
// else {
// biosProtected = 0xe3a02004;
// }
switch (comment)
{
case 0x00:
BIOS_SoftReset();
ARM_PREFETCH;
break;
case 0x01:
BIOS_RegisterRamReset();
break;
case 0x02:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("Halt: (VCOUNT = %2d)\n",
VCOUNT);
}
#endif
holdState = true;
holdType = -1;
cpuNextEvent = cpuTotalTicks;
break;
case 0x03:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("Stop: (VCOUNT = %2d)\n",
VCOUNT);
}
#endif
holdState = true;
holdType = -1;
stopState = true;
cpuNextEvent = cpuTotalTicks;
break;
case 0x04:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("IntrWait: 0x%08x,0x%08x (VCOUNT = %2d)\n",
reg[0].I,
reg[1].I,
VCOUNT);
}
#endif
CPUSoftwareInterrupt();
break;
case 0x05:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("VBlankIntrWait: (VCOUNT = %2d)\n",
VCOUNT);
}
#endif
CPUSoftwareInterrupt();
break;
case 0x06:
CPUSoftwareInterrupt();
break;
case 0x07:
CPUSoftwareInterrupt();
break;
case 0x08:
BIOS_Sqrt();
break;
case 0x09:
BIOS_ArcTan();
break;
case 0x0A:
BIOS_ArcTan2();
break;
case 0x0B:
{
int len = (reg[2].I & 0x1FFFFF) >> 1;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + len) & 0xe000000) == 0))
{
if ((reg[2].I >> 24) & 1)
{
if ((reg[2].I >> 26) & 1)
SWITicks = (7 + memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1);
else
SWITicks = (8 + memoryWait[(reg[1].I >> 24) & 0xF]) * (len);
}
else
{
if ((reg[2].I >> 26) & 1)
SWITicks = (10 + memoryWait32[(reg[0].I >> 24) & 0xF] +
memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1);
else
SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
}
}
BIOS_CpuSet();
break;
case 0x0C:
{
int len = (reg[2].I & 0x1FFFFF) >> 5;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + len) & 0xe000000) == 0))
{
if ((reg[2].I >> 24) & 1)
SWITicks = (6 + memoryWait32[(reg[1].I >> 24) & 0xF] +
7 * (memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 1)) * len;
else
SWITicks = (9 + memoryWait32[(reg[0].I >> 24) & 0xF] +
memoryWait32[(reg[1].I >> 24) & 0xF] +
7 * (memoryWaitSeq32[(reg[0].I >> 24) & 0xF] +
memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 2)) * len;
}
}
BIOS_CpuFastSet();
break;
case 0x0D:
BIOS_GetBiosChecksum();
break;
case 0x0E:
BIOS_BgAffineSet();
break;
case 0x0F:
BIOS_ObjAffineSet();
break;
case 0x10:
{
int len = CPUReadHalfWord(reg[2].I);
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + len) & 0xe000000) == 0))
SWITicks = (32 + memoryWait[(reg[0].I >> 24) & 0xF]) * len;
}
BIOS_BitUnPack();
break;
case 0x11:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (9 + memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_LZ77UnCompWram();
break;
case 0x12:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (19 + memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_LZ77UnCompVram();
break;
case 0x13:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (29 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1)) * len;
}
BIOS_HuffUnComp();
break;
case 0x14:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_RLUnCompWram();
break;
case 0x15:
{
u32 len = CPUReadMemory(reg[0].I) >> 9;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (34 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_RLUnCompVram();
break;
case 0x16:
{
u32 len = CPUReadMemory(reg[0].I) >> 8;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_Diff8bitUnFilterWram();
break;
case 0x17:
{
u32 len = CPUReadMemory(reg[0].I) >> 9;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (39 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_Diff8bitUnFilterVram();
break;
case 0x18:
{
u32 len = CPUReadMemory(reg[0].I) >> 9;
if (!(((reg[0].I & 0xe000000) == 0) ||
((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0))
SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] +
memoryWait[(reg[1].I >> 24) & 0xF]) * len;
}
BIOS_Diff16bitUnFilter();
break;
case 0x19:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("SoundBiasSet: 0x%08x (VCOUNT = %2d)\n",
reg[0].I,
VCOUNT);
}
#endif
if (reg[0].I)
systemSoundPause();
else
systemSoundResume();
break;
case 0x1F:
BIOS_MidiKey2Freq();
break;
case 0x2A:
BIOS_SndDriverJmpTableCopy();
// let it go, because we don't really emulate this function // FIXME (?)
default:
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_SWI)
{
log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment,
armState ? armNextPC - 4 : armNextPC - 2,
reg[0].I,
reg[1].I,
reg[2].I,
VCOUNT);
}
#endif
if (!disableMessage)
{
systemMessage(MSG_UNSUPPORTED_BIOS_FUNCTION,
N_("Unsupported BIOS function %02x called from %08x. A BIOS file is needed in order to get correct behaviour."),
comment,
armMode ? armNextPC - 4 : armNextPC - 2);
disableMessage = true;
}
break;
}
}
void CPUCompareVCOUNT()
{
if (VCOUNT == (DISPSTAT >> 8))
{
DISPSTAT |= 4;
UPDATE_REG(0x04, DISPSTAT);
if (DISPSTAT & 0x20)
{
IF |= 4;
UPDATE_REG(0x202, IF);
}
}
else
{
DISPSTAT &= 0xFFFB;
UPDATE_REG(0x4, DISPSTAT);
}
if (layerEnableDelay > 0)
{
--layerEnableDelay;
if (layerEnableDelay == 1)
layerEnable = layerSettings & DISPCNT;
}
}
static void doDMA(u32 &s, u32 &d, u32 si, u32 di, u32 c, int transfer32)
{
int sm = s >> 24;
int dm = d >> 24;
int sw = 0;
int dw = 0;
int sc = c;
cpuDmaCount = c;
// This is done to get the correct waitstates.
if (sm > 15)
sm = 15;
if (dm > 15)
dm = 15;
//if ((sm>=0x05) && (sm<=0x07) || (dm>=0x05) && (dm <=0x07))
// blank = (((DISPSTAT | ((DISPSTAT>>1)&1))==1) ? true : false);
if (transfer32)
{
s &= 0xFFFFFFFC;
if (s < 0x02000000 && (reg[15].I >> 24))
{
while (c != 0)
{
CPUWriteMemory(d, 0);
d += di;
c--;
}
}
else
{
while (c != 0)
{
cpuDmaLast = CPUReadMemory(s);
CPUWriteMemory(d, cpuDmaLast);
d += di;
s += si;
c--;
}
}
}
else
{
s &= 0xFFFFFFFE;
si = (int)si >> 1;
di = (int)di >> 1;
if (s < 0x02000000 && (reg[15].I >> 24))
{
while (c != 0)
{
CPUWriteHalfWord(d, 0);
d += di;
c--;
}
}
else
{
while (c != 0)
{
cpuDmaLast = CPUReadHalfWord(s);
CPUWriteHalfWord(d, cpuDmaLast);
cpuDmaLast |= (cpuDmaLast << 16);
d += di;
s += si;
c--;
}
}
}
cpuDmaCount = 0;
int totalTicks = 0;
if (transfer32)
{
sw = 1 + memoryWaitSeq32[sm & 15];
dw = 1 + memoryWaitSeq32[dm & 15];
totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait32[sm & 15] +
memoryWaitSeq32[dm & 15];
}
else
{
sw = 1 + memoryWaitSeq[sm & 15];
dw = 1 + memoryWaitSeq[dm & 15];
totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait[sm & 15] +
memoryWaitSeq[dm & 15];
}
cpuDmaTicksToUpdate += totalTicks;
}
void CPUCheckDMA(int reason, int dmamask)
{
// DMA 0
if ((DM0CNT_H & 0x8000) && (dmamask & 1))
{
if (((DM0CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM0CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM0CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA0)
{
int count = (DM0CNT_L ? DM0CNT_L : 0x4000) << 1;
if (DM0CNT_H & 0x0400)
count <<= 1;
log("DMA0: s=%08x d=%08x c=%04x count=%08x\n", dma0Source, dma0Dest,
DM0CNT_H,
count);
}
#endif
doDMA(dma0Source, dma0Dest, sourceIncrement, destIncrement,
DM0CNT_L ? DM0CNT_L : 0x4000,
DM0CNT_H & 0x0400);
cpuDmaHack = true;
if (DM0CNT_H & 0x4000)
{
IF |= 0x0100;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM0CNT_H >> 5) & 3) == 3)
{
dma0Dest = DM0DAD_L | (DM0DAD_H << 16);
}
if (!(DM0CNT_H & 0x0200) || (reason == 0))
{
DM0CNT_H &= 0x7FFF;
UPDATE_REG(0xBA, DM0CNT_H);
}
}
}
// DMA 1
if ((DM1CNT_H & 0x8000) && (dmamask & 2))
{
if (((DM1CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM1CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM1CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
if (reason == 3)
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA1)
{
log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest,
DM1CNT_H,
16);
}
#endif
doDMA(dma1Source, dma1Dest, sourceIncrement, 0, 4,
0x0400);
}
else
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA1)
{
int count = (DM1CNT_L ? DM1CNT_L : 0x4000) << 1;
if (DM1CNT_H & 0x0400)
count <<= 1;
log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest,
DM1CNT_H,
count);
}
#endif
doDMA(dma1Source, dma1Dest, sourceIncrement, destIncrement,
DM1CNT_L ? DM1CNT_L : 0x4000,
DM1CNT_H & 0x0400);
}
cpuDmaHack = true;
if (DM1CNT_H & 0x4000)
{
IF |= 0x0200;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM1CNT_H >> 5) & 3) == 3)
{
dma1Dest = DM1DAD_L | (DM1DAD_H << 16);
}
if (!(DM1CNT_H & 0x0200) || (reason == 0))
{
DM1CNT_H &= 0x7FFF;
UPDATE_REG(0xC6, DM1CNT_H);
}
}
}
// DMA 2
if ((DM2CNT_H & 0x8000) && (dmamask & 4))
{
if (((DM2CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM2CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM2CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
if (reason == 3)
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA2)
{
int count = (4) << 2;
log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest,
DM2CNT_H,
count);
}
#endif
doDMA(dma2Source, dma2Dest, sourceIncrement, 0, 4,
0x0400);
}
else
{
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA2)
{
int count = (DM2CNT_L ? DM2CNT_L : 0x4000) << 1;
if (DM2CNT_H & 0x0400)
count <<= 1;
log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest,
DM2CNT_H,
count);
}
#endif
doDMA(dma2Source, dma2Dest, sourceIncrement, destIncrement,
DM2CNT_L ? DM2CNT_L : 0x4000,
DM2CNT_H & 0x0400);
}
cpuDmaHack = true;
if (DM2CNT_H & 0x4000)
{
IF |= 0x0400;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM2CNT_H >> 5) & 3) == 3)
{
dma2Dest = DM2DAD_L | (DM2DAD_H << 16);
}
if (!(DM2CNT_H & 0x0200) || (reason == 0))
{
DM2CNT_H &= 0x7FFF;
UPDATE_REG(0xD2, DM2CNT_H);
}
}
}
// DMA 3
if ((DM3CNT_H & 0x8000) && (dmamask & 8))
{
if (((DM3CNT_H >> 12) & 3) == reason)
{
u32 sourceIncrement = 4;
u32 destIncrement = 4;
switch ((DM3CNT_H >> 7) & 3)
{
case 0:
break;
case 1:
sourceIncrement = (u32) - 4;
break;
case 2:
sourceIncrement = 0;
break;
}
switch ((DM3CNT_H >> 5) & 3)
{
case 0:
break;
case 1:
destIncrement = (u32) - 4;
break;
case 2:
destIncrement = 0;
break;
}
#ifdef GBA_LOGGING
if (systemVerbose & VERBOSE_DMA3)
{
int count = (DM3CNT_L ? DM3CNT_L : 0x10000) << 1;
if (DM3CNT_H & 0x0400)
count <<= 1;
log("DMA3: s=%08x d=%08x c=%04x count=%08x\n", dma3Source, dma3Dest,
DM3CNT_H,
count);
}
#endif
doDMA(dma3Source, dma3Dest, sourceIncrement, destIncrement,
DM3CNT_L ? DM3CNT_L : 0x10000,
DM3CNT_H & 0x0400);
if (DM3CNT_H & 0x4000)
{
IF |= 0x0800;
UPDATE_REG(0x202, IF);
cpuNextEvent = cpuTotalTicks;
}
if (((DM3CNT_H >> 5) & 3) == 3)
{
dma3Dest = DM3DAD_L | (DM3DAD_H << 16);
}
if (!(DM3CNT_H & 0x0200) || (reason == 0))
{
DM3CNT_H &= 0x7FFF;
UPDATE_REG(0xDE, DM3CNT_H);
}
}
}
}
void CPUUpdateRegister(u32 address, u16 value)
{
switch (address)
{
case 0x00:
{
if ((value & 7) > 5)
{
// display modes above 0-5 are prohibited
DISPCNT = (value & 7);
}
bool change = (0 != ((DISPCNT ^ value) & 0x80));
bool changeBG = (0 != ((DISPCNT ^ value) & 0x0F00));
u16 changeBGon = ((~DISPCNT) & value) & 0x0F00; // these layers are being activated
DISPCNT = (value & 0xFFF7); // bit 3 can only be accessed by the BIOS to enable GBC mode
UPDATE_REG(0x00, DISPCNT);
if (changeBGon)
{
layerEnableDelay = 4;
layerEnable = layerSettings & value & (~changeBGon);
}
else
{
layerEnable = layerSettings & value;
// CPUUpdateTicks(); // what does this do?
}
windowOn = (layerEnable & 0x6000) ? true : false;
if (change && !((value & 0x80)))
{
if (!(DISPSTAT & 1))
{
lcdTicks = 1008;
// VCOUNT = 0;
// UPDATE_REG(0x06, VCOUNT);
DISPSTAT &= 0xFFFC;
UPDATE_REG(0x04, DISPSTAT);
CPUCompareVCOUNT();
}
// (*renderLine)();
}
CPUUpdateRender();
// we only care about changes in BG0-BG3
if (changeBG)
{
CPUUpdateRenderBuffers(false);
}
break;
}
case 0x04:
DISPSTAT = (value & 0xFF38) | (DISPSTAT & 7);
UPDATE_REG(0x04, DISPSTAT);
break;
case 0x06:
// not writable
break;
case 0x08:
BG0CNT = (value & 0xDFCF);
UPDATE_REG(0x08, BG0CNT);
break;
case 0x0A:
BG1CNT = (value & 0xDFCF);
UPDATE_REG(0x0A, BG1CNT);
break;
case 0x0C:
BG2CNT = (value & 0xFFCF);
UPDATE_REG(0x0C, BG2CNT);
break;
case 0x0E:
BG3CNT = (value & 0xFFCF);
UPDATE_REG(0x0E, BG3CNT);
break;
case 0x10:
BG0HOFS = value & 511;
UPDATE_REG(0x10, BG0HOFS);
break;
case 0x12:
BG0VOFS = value & 511;
UPDATE_REG(0x12, BG0VOFS);
break;
case 0x14:
BG1HOFS = value & 511;
UPDATE_REG(0x14, BG1HOFS);
break;
case 0x16:
BG1VOFS = value & 511;
UPDATE_REG(0x16, BG1VOFS);
break;
case 0x18:
BG2HOFS = value & 511;
UPDATE_REG(0x18, BG2HOFS);
break;
case 0x1A:
BG2VOFS = value & 511;
UPDATE_REG(0x1A, BG2VOFS);
break;
case 0x1C:
BG3HOFS = value & 511;
UPDATE_REG(0x1C, BG3HOFS);
break;
case 0x1E:
BG3VOFS = value & 511;
UPDATE_REG(0x1E, BG3VOFS);
break;
case 0x20:
BG2PA = value;
UPDATE_REG(0x20, BG2PA);
break;
case 0x22:
BG2PB = value;
UPDATE_REG(0x22, BG2PB);
break;
case 0x24:
BG2PC = value;
UPDATE_REG(0x24, BG2PC);
break;
case 0x26:
BG2PD = value;
UPDATE_REG(0x26, BG2PD);
break;
case 0x28:
BG2X_L = value;
UPDATE_REG(0x28, BG2X_L);
gfxBG2Changed |= 1;
break;
case 0x2A:
BG2X_H = (value & 0xFFF);
UPDATE_REG(0x2A, BG2X_H);
gfxBG2Changed |= 1;
break;
case 0x2C:
BG2Y_L = value;
UPDATE_REG(0x2C, BG2Y_L);
gfxBG2Changed |= 2;
break;
case 0x2E:
BG2Y_H = value & 0xFFF;
UPDATE_REG(0x2E, BG2Y_H);
gfxBG2Changed |= 2;
break;
case 0x30:
BG3PA = value;
UPDATE_REG(0x30, BG3PA);
break;
case 0x32:
BG3PB = value;
UPDATE_REG(0x32, BG3PB);
break;
case 0x34:
BG3PC = value;
UPDATE_REG(0x34, BG3PC);
break;
case 0x36:
BG3PD = value;
UPDATE_REG(0x36, BG3PD);
break;
case 0x38:
BG3X_L = value;
UPDATE_REG(0x38, BG3X_L);
gfxBG3Changed |= 1;
break;
case 0x3A:
BG3X_H = value & 0xFFF;
UPDATE_REG(0x3A, BG3X_H);
gfxBG3Changed |= 1;
break;
case 0x3C:
BG3Y_L = value;
UPDATE_REG(0x3C, BG3Y_L);
gfxBG3Changed |= 2;
break;
case 0x3E:
BG3Y_H = value & 0xFFF;
UPDATE_REG(0x3E, BG3Y_H);
gfxBG3Changed |= 2;
break;
case 0x40:
WIN0H = value;
UPDATE_REG(0x40, WIN0H);
CPUUpdateWindow0();
break;
case 0x42:
WIN1H = value;
UPDATE_REG(0x42, WIN1H);
CPUUpdateWindow1();
break;
case 0x44:
WIN0V = value;
UPDATE_REG(0x44, WIN0V);
break;
case 0x46:
WIN1V = value;
UPDATE_REG(0x46, WIN1V);
break;
case 0x48:
WININ = value & 0x3F3F;
UPDATE_REG(0x48, WININ);
break;
case 0x4A:
WINOUT = value & 0x3F3F;
UPDATE_REG(0x4A, WINOUT);
break;
case 0x4C:
MOSAIC = value;
UPDATE_REG(0x4C, MOSAIC);
break;
case 0x50:
BLDMOD = value & 0x3FFF;
UPDATE_REG(0x50, BLDMOD);
fxOn = ((BLDMOD >> 6) & 3) != 0;
CPUUpdateRender();
break;
case 0x52:
COLEV = value & 0x1F1F;
UPDATE_REG(0x52, COLEV);
break;
case 0x54:
COLY = value & 0x1F;
UPDATE_REG(0x54, COLY);
break;
case 0x60:
case 0x62:
case 0x64:
case 0x68:
case 0x6c:
case 0x70:
case 0x72:
case 0x74:
case 0x78:
case 0x7c:
case 0x80:
case 0x84:
soundEvent(address & 0xFF, (u8)(value & 0xFF));
soundEvent((address & 0xFF) + 1, (u8)(value >> 8));
break;
case 0x82:
case 0x88:
case 0xa0:
case 0xa2:
case 0xa4:
case 0xa6:
case 0x90:
case 0x92:
case 0x94:
case 0x96:
case 0x98:
case 0x9a:
case 0x9c:
case 0x9e:
soundEvent(address & 0xFF, value);
break;
case 0xB0:
DM0SAD_L = value;
UPDATE_REG(0xB0, DM0SAD_L);
break;
case 0xB2:
DM0SAD_H = value & 0x07FF;
UPDATE_REG(0xB2, DM0SAD_H);
break;
case 0xB4:
DM0DAD_L = value;
UPDATE_REG(0xB4, DM0DAD_L);
break;
case 0xB6:
DM0DAD_H = value & 0x07FF;
UPDATE_REG(0xB6, DM0DAD_H);
break;
case 0xB8:
DM0CNT_L = value & 0x3FFF;
UPDATE_REG(0xB8, 0);
break;
case 0xBA:
{
bool start = ((DM0CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xF7E0;
DM0CNT_H = value;
UPDATE_REG(0xBA, DM0CNT_H);
if (start && (value & 0x8000))
{
dma0Source = DM0SAD_L | (DM0SAD_H << 16);
dma0Dest = DM0DAD_L | (DM0DAD_H << 16);
CPUCheckDMA(0, 1);
}
break;
}
case 0xBC:
DM1SAD_L = value;
UPDATE_REG(0xBC, DM1SAD_L);
break;
case 0xBE:
DM1SAD_H = value & 0x0FFF;
UPDATE_REG(0xBE, DM1SAD_H);
break;
case 0xC0:
DM1DAD_L = value;
UPDATE_REG(0xC0, DM1DAD_L);
break;
case 0xC2:
DM1DAD_H = value & 0x07FF;
UPDATE_REG(0xC2, DM1DAD_H);
break;
case 0xC4:
DM1CNT_L = value & 0x3FFF;
UPDATE_REG(0xC4, 0);
break;
case 0xC6:
{
bool start = ((DM1CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xF7E0;
DM1CNT_H = value;
UPDATE_REG(0xC6, DM1CNT_H);
if (start && (value & 0x8000))
{
dma1Source = DM1SAD_L | (DM1SAD_H << 16);
dma1Dest = DM1DAD_L | (DM1DAD_H << 16);
CPUCheckDMA(0, 2);
}
break;
}
case 0xC8:
DM2SAD_L = value;
UPDATE_REG(0xC8, DM2SAD_L);
break;
case 0xCA:
DM2SAD_H = value & 0x0FFF;
UPDATE_REG(0xCA, DM2SAD_H);
break;
case 0xCC:
DM2DAD_L = value;
UPDATE_REG(0xCC, DM2DAD_L);
break;
case 0xCE:
DM2DAD_H = value & 0x07FF;
UPDATE_REG(0xCE, DM2DAD_H);
break;
case 0xD0:
DM2CNT_L = value & 0x3FFF;
UPDATE_REG(0xD0, 0);
break;
case 0xD2:
{
bool start = ((DM2CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xF7E0;
DM2CNT_H = value;
UPDATE_REG(0xD2, DM2CNT_H);
if (start && (value & 0x8000))
{
dma2Source = DM2SAD_L | (DM2SAD_H << 16);
dma2Dest = DM2DAD_L | (DM2DAD_H << 16);
CPUCheckDMA(0, 4);
}
break;
}
case 0xD4:
DM3SAD_L = value;
UPDATE_REG(0xD4, DM3SAD_L);
break;
case 0xD6:
DM3SAD_H = value & 0x0FFF;
UPDATE_REG(0xD6, DM3SAD_H);
break;
case 0xD8:
DM3DAD_L = value;
UPDATE_REG(0xD8, DM3DAD_L);
break;
case 0xDA:
DM3DAD_H = value & 0x0FFF;
UPDATE_REG(0xDA, DM3DAD_H);
break;
case 0xDC:
DM3CNT_L = value;
UPDATE_REG(0xDC, 0);
break;
case 0xDE:
{
bool start = ((DM3CNT_H ^ value) & 0x8000) ? true : false;
value &= 0xFFE0;
DM3CNT_H = value;
UPDATE_REG(0xDE, DM3CNT_H);
if (start && (value & 0x8000))
{
dma3Source = DM3SAD_L | (DM3SAD_H << 16);
dma3Dest = DM3DAD_L | (DM3DAD_H << 16);
CPUCheckDMA(0, 8);
}
break;
}
case 0x100:
timer0Reload = value;
interp_rate();
break;
case 0x102:
timer0Value = value;
timerOnOffDelay |= 1;
cpuNextEvent = cpuTotalTicks;
break;
case 0x104:
timer1Reload = value;
interp_rate();
break;
case 0x106:
timer1Value = value;
timerOnOffDelay |= 2;
cpuNextEvent = cpuTotalTicks;
break;
case 0x108:
timer2Reload = value;
break;
case 0x10A:
timer2Value = value;
timerOnOffDelay |= 4;
cpuNextEvent = cpuTotalTicks;
break;
case 0x10C:
timer3Reload = value;
break;
case 0x10E:
timer3Value = value;
timerOnOffDelay |= 8;
cpuNextEvent = cpuTotalTicks;
break;
case 0x128:
if (value & 0x80)
{
value &= 0xff7f;
if (value & 1 && (value & 0x4000))
{
UPDATE_REG(0x12a, 0xFF);
IF |= 0x80;
UPDATE_REG(0x202, IF);
value &= 0x7f7f;
}
}
UPDATE_REG(0x128, value);
break;
case 0x130:
P1 |= (value & 0x3FF);
UPDATE_REG(0x130, P1);
break;
case 0x132:
UPDATE_REG(0x132, value & 0xC3FF);
break;
case 0x200:
IE = value & 0x3FFF;
UPDATE_REG(0x200, IE);
if ((IME & 1) && (IF & IE) && armIrqEnable)
cpuNextEvent = cpuTotalTicks;
break;
case 0x202:
IF ^= (value & IF);
UPDATE_REG(0x202, IF);
break;
case 0x204:
{
memoryWait[0x0e] = memoryWaitSeq[0x0e] = gamepakRamWaitState[value & 3];
if (!speedHack)
{
memoryWait[0x08] = memoryWait[0x09] = gamepakWaitState[(value >> 2) & 3];
memoryWaitSeq[0x08] = memoryWaitSeq[0x09] =
gamepakWaitState0[(value >> 4) & 1];
memoryWait[0x0a] = memoryWait[0x0b] = gamepakWaitState[(value >> 5) & 3];
memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] =
gamepakWaitState1[(value >> 7) & 1];
memoryWait[0x0c] = memoryWait[0x0d] = gamepakWaitState[(value >> 8) & 3];
memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] =
gamepakWaitState2[(value >> 10) & 1];
}
else
{
memoryWait[0x08] = memoryWait[0x09] = 3;
memoryWaitSeq[0x08] = memoryWaitSeq[0x09] = 1;
memoryWait[0x0a] = memoryWait[0x0b] = 3;
memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] = 1;
memoryWait[0x0c] = memoryWait[0x0d] = 3;
memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] = 1;
}
for (int i = 8; i < 15; i++)
{
memoryWait32[i] = memoryWait[i] + memoryWaitSeq[i] + 1;
memoryWaitSeq32[i] = memoryWaitSeq[i] * 2 + 1;
}
if ((value & 0x4000) == 0x4000)
{
busPrefetchEnable = true;
busPrefetch = false;
busPrefetchCount = 0;
}
else
{
busPrefetchEnable = false;
busPrefetch = false;
busPrefetchCount = 0;
}
UPDATE_REG(0x204, value & 0x7FFF);
}
break;
case 0x208:
IME = value & 1;
UPDATE_REG(0x208, IME);
if ((IME & 1) && (IF & IE) && armIrqEnable)
cpuNextEvent = cpuTotalTicks;
break;
case 0x300:
if (value != 0)
value &= 0xFFFE;
UPDATE_REG(0x300, value);
break;
default:
UPDATE_REG(address & 0x3FE, value);
break;
}
}
void applyTimer()
{
if (timerOnOffDelay & 1)
{
timer0ClockReload = TIMER_TICKS[timer0Value & 3];
if (!timer0On && (timer0Value & 0x80))
{
// reload the counter
TM0D = timer0Reload;
timer0Ticks = (0x10000 - TM0D) << timer0ClockReload;
UPDATE_REG(0x100, TM0D);
}
timer0On = timer0Value & 0x80 ? true : false;
TM0CNT = timer0Value & 0xC7;
interp_rate();
UPDATE_REG(0x102, TM0CNT);
// CPUUpdateTicks();
}
if (timerOnOffDelay & 2)
{
timer1ClockReload = TIMER_TICKS[timer1Value & 3];
if (!timer1On && (timer1Value & 0x80))
{
// reload the counter
TM1D = timer1Reload;
timer1Ticks = (0x10000 - TM1D) << timer1ClockReload;
UPDATE_REG(0x104, TM1D);
}
timer1On = timer1Value & 0x80 ? true : false;
TM1CNT = timer1Value & 0xC7;
interp_rate();
UPDATE_REG(0x106, TM1CNT);
}
if (timerOnOffDelay & 4)
{
timer2ClockReload = TIMER_TICKS[timer2Value & 3];
if (!timer2On && (timer2Value & 0x80))
{
// reload the counter
TM2D = timer2Reload;
timer2Ticks = (0x10000 - TM2D) << timer2ClockReload;
UPDATE_REG(0x108, TM2D);
}
timer2On = timer2Value & 0x80 ? true : false;
TM2CNT = timer2Value & 0xC7;
UPDATE_REG(0x10A, TM2CNT);
}
if (timerOnOffDelay & 8)
{
timer3ClockReload = TIMER_TICKS[timer3Value & 3];
if (!timer3On && (timer3Value & 0x80))
{
// reload the counter
TM3D = timer3Reload;
timer3Ticks = (0x10000 - TM3D) << timer3ClockReload;
UPDATE_REG(0x10C, TM3D);
}
timer3On = timer3Value & 0x80 ? true : false;
TM3CNT = timer3Value & 0xC7;
UPDATE_REG(0x10E, TM3CNT);
}
cpuNextEvent = CPUUpdateTicks();
timerOnOffDelay = 0;
}
void CPULoadInternalBios()
{
// load internal BIOS
#ifdef WORDS_BIGENDIAN
for (size_t i = 0; i < sizeof(myROM) / 4; ++i)
{
WRITE32LE(&bios[i], myROM[i]);
}
#else
memcpy(bios, myROM, sizeof(myROM));
#endif
}
void CPUInit()
{
biosProtected[0] = 0x00;
biosProtected[1] = 0xf0;
biosProtected[2] = 0x29;
biosProtected[3] = 0xe1;
int i = 0;
for (i = 0; i < 256; i++)
{
int cpuBitSetCount = 0;
int j;
for (j = 0; j < 8; j++)
if (i & (1 << j))
cpuBitSetCount++;
cpuBitsSet[i] = cpuBitSetCount;
for (j = 0; j < 8; j++)
if (i & (1 << j))
break;
cpuLowestBitSet[i] = j;
}
for (i = 0; i < 0x400; i++)
ioReadable[i] = true;
for (i = 0x10; i < 0x48; i++)
ioReadable[i] = false;
for (i = 0x4c; i < 0x50; i++)
ioReadable[i] = false;
for (i = 0x54; i < 0x60; i++)
ioReadable[i] = false;
for (i = 0x8c; i < 0x90; i++)
ioReadable[i] = false;
for (i = 0xa0; i < 0xb8; i++)
ioReadable[i] = false;
for (i = 0xbc; i < 0xc4; i++)
ioReadable[i] = false;
for (i = 0xc8; i < 0xd0; i++)
ioReadable[i] = false;
for (i = 0xd4; i < 0xdc; i++)
ioReadable[i] = false;
for (i = 0xe0; i < 0x100; i++)
ioReadable[i] = false;
for (i = 0x110; i < 0x120; i++)
ioReadable[i] = false;
for (i = 0x12c; i < 0x130; i++)
ioReadable[i] = false;
for (i = 0x138; i < 0x140; i++)
ioReadable[i] = false;
for (i = 0x144; i < 0x150; i++)
ioReadable[i] = false;
for (i = 0x15c; i < 0x200; i++)
ioReadable[i] = false;
for (i = 0x20c; i < 0x300; i++)
ioReadable[i] = false;
for (i = 0x304; i < 0x400; i++)
ioReadable[i] = false;
if (romSize < 0x1fe2000)
{
*((u16 *)&rom[0x1fe209c]) = 0xdffa; // SWI 0xFA
*((u16 *)&rom[0x1fe209e]) = 0x4770; // BX LR
}
else
{
agbPrintEnable(false);
}
gbaSaveType = 0;
eepromInUse = 0;
saveType = 0;
}
void CPUReset()
{
systemReset();
if (gbaSaveType == 0)
{
if (eepromInUse)
gbaSaveType = 3;
else
switch (saveType)
{
case 1:
gbaSaveType = 1;
break;
case 2:
gbaSaveType = 2;
break;
}
}
// clean picture
memset(pix, 0, 4 * 241 * 162);
// clean registers
memset(®[0], 0, sizeof(reg));
// clean OAM
memset(oam, 0, 0x400);
// clean palette
memset(paletteRAM, 0, 0x400);
// clean vram
memset(vram, 0, 0x20000);
// clean io memory
memset(ioMem, 0, 0x400);
DISPCNT = 0x0080;
DISPSTAT = 0x0000;
VCOUNT = (useBios && !skipBios) ? 0 : 0x007E;
BG0CNT = 0x0000;
BG1CNT = 0x0000;
BG2CNT = 0x0000;
BG3CNT = 0x0000;
BG0HOFS = 0x0000;
BG0VOFS = 0x0000;
BG1HOFS = 0x0000;
BG1VOFS = 0x0000;
BG2HOFS = 0x0000;
BG2VOFS = 0x0000;
BG3HOFS = 0x0000;
BG3VOFS = 0x0000;
BG2PA = 0x0100;
BG2PB = 0x0000;
BG2PC = 0x0000;
BG2PD = 0x0100;
BG2X_L = 0x0000;
BG2X_H = 0x0000;
BG2Y_L = 0x0000;
BG2Y_H = 0x0000;
BG3PA = 0x0100;
BG3PB = 0x0000;
BG3PC = 0x0000;
BG3PD = 0x0100;
BG3X_L = 0x0000;
BG3X_H = 0x0000;
BG3Y_L = 0x0000;
BG3Y_H = 0x0000;
WIN0H = 0x0000;
WIN1H = 0x0000;
WIN0V = 0x0000;
WIN1V = 0x0000;
WININ = 0x0000;
WINOUT = 0x0000;
MOSAIC = 0x0000;
BLDMOD = 0x0000;
COLEV = 0x0000;
COLY = 0x0000;
DM0SAD_L = 0x0000;
DM0SAD_H = 0x0000;
DM0DAD_L = 0x0000;
DM0DAD_H = 0x0000;
DM0CNT_L = 0x0000;
DM0CNT_H = 0x0000;
DM1SAD_L = 0x0000;
DM1SAD_H = 0x0000;
DM1DAD_L = 0x0000;
DM1DAD_H = 0x0000;
DM1CNT_L = 0x0000;
DM1CNT_H = 0x0000;
DM2SAD_L = 0x0000;
DM2SAD_H = 0x0000;
DM2DAD_L = 0x0000;
DM2DAD_H = 0x0000;
DM2CNT_L = 0x0000;
DM2CNT_H = 0x0000;
DM3SAD_L = 0x0000;
DM3SAD_H = 0x0000;
DM3DAD_L = 0x0000;
DM3DAD_H = 0x0000;
DM3CNT_L = 0x0000;
DM3CNT_H = 0x0000;
TM0D = 0x0000;
TM0CNT = 0x0000;
TM1D = 0x0000;
TM1CNT = 0x0000;
TM2D = 0x0000;
TM2CNT = 0x0000;
TM3D = 0x0000;
TM3CNT = 0x0000;
P1 = 0x03FF;
IE = 0x0000;
IF = 0x0000;
IME = 0x0000;
armMode = 0x1F;
armState = true;
if (cpuIsMultiBoot)
{
reg[13].I = 0x03007F00;
reg[15].I = 0x02000000;
reg[16].I = 0x00000000;
reg[R13_IRQ].I = 0x03007FA0;
reg[R13_SVC].I = 0x03007FE0;
armIrqEnable = true;
}
else
{
if (useBios && !skipBios)
{
reg[15].I = 0x00000000;
armMode = 0x13;
armIrqEnable = false;
}
else
{
reg[13].I = 0x03007F00;
reg[15].I = 0x08000000;
reg[16].I = 0x00000000;
reg[R13_IRQ].I = 0x03007FA0;
reg[R13_SVC].I = 0x03007FE0;
armIrqEnable = true;
}
}
C_FLAG = V_FLAG = N_FLAG = Z_FLAG = false;
UPDATE_REG(0x00, DISPCNT);
UPDATE_REG(0x06, VCOUNT);
UPDATE_REG(0x20, BG2PA);
UPDATE_REG(0x26, BG2PD);
UPDATE_REG(0x30, BG3PA);
UPDATE_REG(0x36, BG3PD);
UPDATE_REG(0x130, P1);
UPDATE_REG(0x88, 0x200);
// disable FIQ
reg[16].I |= 0x40;
CPUUpdateCPSR();
armNextPC = reg[15].I;
reg[15].I += 4;
// reset internal state
intState = false;
stopState = false;
holdState = false;
holdType = 0;
biosProtected[0] = 0x00;
biosProtected[1] = 0xf0;
biosProtected[2] = 0x29;
biosProtected[3] = 0xe1;
lcdTicks = (useBios && !skipBios) ? 1008 : 208;
timer0On = false;
timer0Ticks = 0;
timer0Reload = 0;
timer0ClockReload = 0;
timer1On = false;
timer1Ticks = 0;
timer1Reload = 0;
timer1ClockReload = 0;
timer2On = false;
timer2Ticks = 0;
timer2Reload = 0;
timer2ClockReload = 0;
timer3On = false;
timer3Ticks = 0;
timer3Reload = 0;
timer3ClockReload = 0;
dma0Source = 0;
dma0Dest = 0;
dma1Source = 0;
dma1Dest = 0;
dma2Source = 0;
dma2Dest = 0;
dma3Source = 0;
dma3Dest = 0;
cpuSaveGameFunc = flashSaveDecide;
renderLine = mode0RenderLine;
fxOn = false;
windowOn = false;
saveType = 0;
layerEnable = DISPCNT & layerSettings;
CPUUpdateRenderBuffers(true);
for (int i = 0; i < 256; i++)
{
memoryMap[i].address = (u8 *)&dummyAddress;
memoryMap[i].mask = 0;
}
memoryMap[0].address = bios;
memoryMap[0].mask = 0x3FFF;
memoryMap[2].address = workRAM;
memoryMap[2].mask = 0x3FFFF;
memoryMap[3].address = internalRAM;
memoryMap[3].mask = 0x7FFF;
memoryMap[4].address = ioMem;
memoryMap[4].mask = 0x3FF;
memoryMap[5].address = paletteRAM;
memoryMap[5].mask = 0x3FF;
memoryMap[6].address = vram;
memoryMap[6].mask = 0x1FFFF;
memoryMap[7].address = oam;
memoryMap[7].mask = 0x3FF;
memoryMap[8].address = rom;
memoryMap[8].mask = 0x1FFFFFF;
memoryMap[9].address = rom;
memoryMap[9].mask = 0x1FFFFFF;
memoryMap[10].address = rom;
memoryMap[10].mask = 0x1FFFFFF;
memoryMap[12].address = rom;
memoryMap[12].mask = 0x1FFFFFF;
memoryMap[14].address = flashSaveMemory;
memoryMap[14].mask = 0xFFFF;
eepromReset();
flashReset();
rtcReset();
CPUUpdateWindow0();
CPUUpdateWindow1();
// make sure registers are correctly initialized if not using BIOS
if (!useBios)
{
if (cpuIsMultiBoot)
BIOS_RegisterRamReset(0xfe);
else
BIOS_RegisterRamReset(0xff);
}
else
{
if (cpuIsMultiBoot)
BIOS_RegisterRamReset(0xfe);
}
switch (cpuSaveType)
{
case 0: // automatic
cpuSramEnabled = true;
cpuFlashEnabled = true;
cpuEEPROMEnabled = true;
cpuEEPROMSensorEnabled = false;
saveType = gbaSaveType = 0;
break;
case 1: // EEPROM
cpuSramEnabled = false;
cpuFlashEnabled = false;
cpuEEPROMEnabled = true;
cpuEEPROMSensorEnabled = false;
saveType = gbaSaveType = 3;
// EEPROM usage is automatically detected
break;
case 2: // SRAM
cpuSramEnabled = true;
cpuFlashEnabled = false;
cpuEEPROMEnabled = false;
cpuEEPROMSensorEnabled = false;
cpuSaveGameFunc = sramDelayedWrite; // to insure we detect the write
saveType = gbaSaveType = 1;
break;
case 3: // FLASH
cpuSramEnabled = false;
cpuFlashEnabled = true;
cpuEEPROMEnabled = false;
cpuEEPROMSensorEnabled = false;
cpuSaveGameFunc = flashDelayedWrite; // to insure we detect the write
saveType = gbaSaveType = 2;
break;
case 4: // EEPROM+Sensor
cpuSramEnabled = false;
cpuFlashEnabled = false;
cpuEEPROMEnabled = true;
cpuEEPROMSensorEnabled = true;
// EEPROM usage is automatically detected
saveType = gbaSaveType = 3;
break;
case 5: // NONE
cpuSramEnabled = false;
cpuFlashEnabled = false;
cpuEEPROMEnabled = false;
cpuEEPROMSensorEnabled = false;
// no save at all
saveType = gbaSaveType = 5;
break;
}
ARM_PREFETCH;
cpuDmaHack = false;
SWITicks = 0;
IRQTicks = 0;
soundReset();
systemRefreshScreen();
}
void CPUInterrupt()
{
u32 PC = reg[15].I;
bool savedState = armState;
CPUSwitchMode(0x12, true, false);
reg[14].I = PC;
if (!savedState)
reg[14].I += 2;
reg[15].I = 0x18;
armState = true;
armIrqEnable = false;
armNextPC = reg[15].I;
reg[15].I += 4;
ARM_PREFETCH;
// if(!holdState)
biosProtected[0] = 0x02;
biosProtected[1] = 0xc0;
biosProtected[2] = 0x5e;
biosProtected[3] = 0xe5;
}
static inline void CPUDrawPixLine()
{
switch (systemColorDepth)
{
case 16:
{
u16 *dest = (u16 *)pix + 241 * (VCOUNT + 1);
for (int x = 0; x < 240; )
{
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap16[lineMix[x++] & 0xFFFF];
}
// for filters that read past the screen
*dest++ = 0;
break;
}
case 24:
{
u8 *dest = (u8 *)pix + 240 * VCOUNT * 3;
for (int x = 0; x < 240; )
{
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
*((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF];
dest += 3;
}
break;
}
case 32:
{
u32 *dest = (u32 *)pix + 241 * (VCOUNT + 1);
for (int x = 0; x < 240; )
{
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
*dest++ = systemColorMap32[lineMix[x++] & 0xFFFF];
}
break;
}
}
}
static inline u32 CPUGetUserInput()
{
// update joystick information
systemReadJoypads();
u32 joy = systemGetJoypad(0, cpuEEPROMSensorEnabled);
P1 = 0x03FF ^ (joy & 0x3FF);
UPDATE_REG(0x130, P1);
// HACK: some special "buttons"
extButtons = (joy >> 18);
speedup = (extButtons & 1) != 0;
return joy;
}
static inline void CPUBeforeEmulation()
{
if (newFrame)
{
CallRegisteredLuaFunctions(LUACALL_BEFOREEMULATION);
u32 joy = CPUGetUserInput();
// this seems wrong, but there are cases where the game
// can enter the stop state without requesting an IRQ from
// the joypad.
// FIXME: where is the right place???
u16 P1CNT = READ16LE(((u16 *)&ioMem[0x132]));
if ((P1CNT & 0x4000) || stopState)
{
u16 p1 = (0x3FF ^ P1) & 0x3FF;
if (P1CNT & 0x8000)
{
if (p1 == (P1CNT & 0x3FF))
{
IF |= 0x1000;
UPDATE_REG(0x202, IF);
}
}
else
{
if (p1 & P1CNT)
{
IF |= 0x1000;
UPDATE_REG(0x202, IF);
}
}
}
//if (cpuEEPROMSensorEnabled)
//systemUpdateMotionSensor(0);
VBAMovieResetIfRequested();
newFrame = false;
}
}
static inline void CPUFrameBoundaryWork()
{
// HACK: some special "buttons"
if (cheatsEnabled)
cheatsCheckKeys(P1 ^ 0x3FF, extButtons);
systemFrameBoundaryWork();
}
void CPULoop(int _ticks)
{
CPUBeforeEmulation();
int32 ticks = _ticks;
int32 clockTicks;
int32 timerOverflow = 0;
bool newVideoFrame = false;
// variable used by the CPU core
cpuTotalTicks = 0;
cpuNextEvent = CPUUpdateTicks();
if (cpuNextEvent > ticks)
cpuNextEvent = ticks;
#ifdef SDL
cpuBreakLoop = false;
#endif
for (;;)
{
#ifndef FINAL_VERSION
if (systemDebug)
{
if (systemDebug >= 10 && !holdState)
{
CPUUpdateCPSR();
#ifdef BKPT_SUPPORT
if (debugger_last)
{
sprintf(
buffer,
"R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n",
oldreg[0],
oldreg[1],
oldreg[2],
oldreg[3],
oldreg[4],
oldreg[5],
oldreg[6],
oldreg[7],
oldreg[8],
oldreg[9],
oldreg[10],
oldreg[11],
oldreg[12],
oldreg[13],
oldreg[14],
oldreg[15],
oldreg[16],
oldreg[17]);
}
#endif
sprintf(
buffer,
"R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x"
"R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n",
reg[0].I,
reg[1].I,
reg[2].I,
reg[3].I,
reg[4].I,
reg[5].I,
reg[6].I,
reg[7].I,
reg[8].I,
reg[9].I,
reg[10].I,
reg[11].I,
reg[12].I,
reg[13].I,
reg[14].I,
reg[15].I,
reg[16].I,
reg[17].I);
log(buffer);
}
else if (!holdState)
{
log("PC=%08x\n", armNextPC);
}
}
#endif /* FINAL_VERSION */
if (!holdState && !SWITicks)
{
if (armState)
{
if (!armExecute())
return;
}
else
{
if (!thumbExecute())
return;
}
clockTicks = 0;
}
else
clockTicks = CPUUpdateTicks();
cpuTotalTicks += clockTicks;
if (cpuTotalTicks >= cpuNextEvent)
{
int32 remainingTicks = cpuTotalTicks - cpuNextEvent;
if (SWITicks)
{
SWITicks -= clockTicks;
if (SWITicks < 0)
SWITicks = 0;
}
clockTicks = cpuNextEvent;
cpuTotalTicks = 0;
cpuDmaHack = false;
updateLoop:
if (IRQTicks)
{
IRQTicks -= clockTicks;
if (IRQTicks < 0)
IRQTicks = 0;
}
lcdTicks -= clockTicks;
if (lcdTicks <= 0)
{
if (DISPSTAT & 1) // V-BLANK
{ // if in V-Blank mode, keep computing...
if (DISPSTAT & 2)
{
lcdTicks += 1008;
VCOUNT++;
UPDATE_REG(0x06, VCOUNT);
DISPSTAT &= 0xFFFD;
UPDATE_REG(0x04, DISPSTAT);
CPUCompareVCOUNT();
}
else
{
lcdTicks += 224;
DISPSTAT |= 2;
UPDATE_REG(0x04, DISPSTAT);
if (DISPSTAT & 16)
{
IF |= 2;
UPDATE_REG(0x202, IF);
}
}
if (VCOUNT >= 228) //Reaching last line
{
DISPSTAT &= 0xFFFC;
UPDATE_REG(0x04, DISPSTAT);
VCOUNT = 0;
UPDATE_REG(0x06, VCOUNT);
CPUCompareVCOUNT();
}
}
else
{
if (DISPSTAT & 2)
{
// if in H-Blank, leave it and move to drawing mode
VCOUNT++;
UPDATE_REG(0x06, VCOUNT);
lcdTicks += 1008;
DISPSTAT &= 0xFFFD;
if (VCOUNT == 160)
{
DISPSTAT |= 1;
DISPSTAT &= 0xFFFD;
UPDATE_REG(0x04, DISPSTAT);
if (DISPSTAT & 0x0008)
{
IF |= 1;
UPDATE_REG(0x202, IF);
}
CPUCheckDMA(1, 0x0f);
newVideoFrame = true;
}
UPDATE_REG(0x04, DISPSTAT);
CPUCompareVCOUNT();
}
else
{
if (systemFrameDrawingRequired())
{
(*renderLine)();
CPUDrawPixLine();
}
// entering H-Blank
DISPSTAT |= 2;
UPDATE_REG(0x04, DISPSTAT);
lcdTicks += 224;
CPUCheckDMA(2, 0x0f);
if (DISPSTAT & 16)
{
IF |= 2;
UPDATE_REG(0x202, IF);
}
}
}
}
// we shouldn't be doing sound in stop state, but we lose synchronization
// if sound is disabled, so in stop state, soundTick will just produce
// mute sound
soundTicks -= clockTicks;
if (soundTicks <= 0)
{
soundTick();
soundTicks += soundTickStep;
}
if (!stopState)
{
if (timer0On)
{
timer0Ticks -= clockTicks;
if (timer0Ticks <= 0)
{
timer0Ticks += (0x10000 - timer0Reload) << timer0ClockReload;
timerOverflow |= 1;
soundTimerOverflow(0);
if (TM0CNT & 0x40)
{
IF |= 0x08;
UPDATE_REG(0x202, IF);
}
}
TM0D = 0xFFFF - (timer0Ticks >> timer0ClockReload) & 0xFFFF;
UPDATE_REG(0x100, TM0D);
}
if (timer1On)
{
if (TM1CNT & 4)
{
if (timerOverflow & 1)
{
TM1D++;
if (TM1D == 0)
{
TM1D += timer1Reload;
timerOverflow |= 2;
soundTimerOverflow(1);
if (TM1CNT & 0x40)
{
IF |= 0x10;
UPDATE_REG(0x202, IF);
}
}
UPDATE_REG(0x104, TM1D);
}
}
else
{
timer1Ticks -= clockTicks;
if (timer1Ticks <= 0)
{
timer1Ticks += (0x10000 - timer1Reload) << timer1ClockReload;
timerOverflow |= 2;
soundTimerOverflow(1);
if (TM1CNT & 0x40)
{
IF |= 0x10;
UPDATE_REG(0x202, IF);
}
}
TM1D = 0xFFFF - (timer1Ticks >> timer1ClockReload) & 0xFFFF;
UPDATE_REG(0x104, TM1D);
}
}
if (timer2On)
{
if (TM2CNT & 4)
{
if (timerOverflow & 2)
{
TM2D++;
if (TM2D == 0)
{
TM2D += timer2Reload;
timerOverflow |= 4;
if (TM2CNT & 0x40)
{
IF |= 0x20;
UPDATE_REG(0x202, IF);
}
}
UPDATE_REG(0x108, TM2D);
}
}
else
{
timer2Ticks -= clockTicks;
if (timer2Ticks <= 0)
{
timer2Ticks += (0x10000 - timer2Reload) << timer2ClockReload;
timerOverflow |= 4;
if (TM2CNT & 0x40)
{
IF |= 0x20;
UPDATE_REG(0x202, IF);
}
}
TM2D = 0xFFFF - (timer2Ticks >> timer2ClockReload) & 0xFFFF;
UPDATE_REG(0x108, TM2D);
}
}
if (timer3On)
{
if (TM3CNT & 4)
{
if (timerOverflow & 4)
{
TM3D++;
if (TM3D == 0)
{
TM3D += timer3Reload;
if (TM3CNT & 0x40)
{
IF |= 0x40;
UPDATE_REG(0x202, IF);
}
}
UPDATE_REG(0x10C, TM3D);
}
}
else
{
timer3Ticks -= clockTicks;
if (timer3Ticks <= 0)
{
timer3Ticks += (0x10000 - timer3Reload) << timer3ClockReload;
if (TM3CNT & 0x40)
{
IF |= 0x40;
UPDATE_REG(0x202, IF);
}
}
TM3D = 0xFFFF - (timer3Ticks >> timer3ClockReload) & 0xFFFF;
UPDATE_REG(0x10C, TM3D);
}
}
}
timerOverflow = 0;
#ifdef PROFILING
profilingTicks -= clockTicks;
if (profilingTicks <= 0)
{
profilingTicks += profilingTicksReload;
if (profilSegment)
{
profile_segment *seg = profilSegment;
do
{
u16 *b = (u16 *)seg->sbuf;
int pc = ((reg[15].I - seg->s_lowpc) * seg->s_scale) / 0x10000;
if (pc >= 0 && pc < seg->ssiz)
{
b[pc]++;
break;
}
seg = seg->next;
}
while (seg);
}
}
#endif
if (newVideoFrame)
{
newVideoFrame = false;
CPUFrameBoundaryWork();
}
ticks -= clockTicks;
cpuNextEvent = CPUUpdateTicks();
if (cpuDmaTicksToUpdate > 0)
{
if (cpuDmaTicksToUpdate > cpuNextEvent)
clockTicks = cpuNextEvent;
else
clockTicks = cpuDmaTicksToUpdate;
cpuDmaTicksToUpdate -= clockTicks;
cpuDmaHack = true;
goto updateLoop; // this is evil
}
if (IF && (IME & 1) && armIrqEnable)
{
int res = IF & IE;
if (stopState)
res &= 0x3080;
if (res)
{
if (intState)
{
if (!IRQTicks)
{
CPUInterrupt();
intState = false;
holdState = false;
stopState = false;
holdType = 0;
}
}
else
{
if (!holdState)
{
intState = true;
IRQTicks = 7;
if (cpuNextEvent > IRQTicks)
cpuNextEvent = IRQTicks;
}
else
{
CPUInterrupt();
holdState = false;
stopState = false;
holdType = 0;
}
}
// Stops the SWI Ticks emulation if an IRQ is executed
//(to avoid problems with nested IRQ/SWI)
if (SWITicks)
SWITicks = 0;
}
}
if (remainingTicks > 0)
{
if (remainingTicks > cpuNextEvent)
clockTicks = cpuNextEvent;
else
clockTicks = remainingTicks;
remainingTicks -= clockTicks;
goto updateLoop; // this is evil, too
}
if (timerOnOffDelay)
applyTimer();
//if (cpuNextEvent > ticks) // FIXME: can be negative and slow down
// cpuNextEvent = ticks;
#ifdef SDL
if (newFrame || useOldFrameTiming && ticks <= 0 || cpuBreakLoop)
#else
if (newFrame || useOldFrameTiming && ticks <= 0)
#endif
{
break;
}
}
}
}
struct EmulatedSystem GBASystem =
{
// emuMain
CPULoop,
// emuReset
CPUReset,
// emuCleanUp
CPUCleanUp,
// emuReadBattery
CPUReadBatteryFile,
// emuWriteBattery
CPUWriteBatteryFile,
// emuReadBatteryFromStream
CPUReadBatteryFromStream,
// emuWriteBatteryToStream
CPUWriteBatteryToStream,
// emuReadState
CPUReadState,
// emuWriteState
CPUWriteState,
// emuReadStateFromStream
CPUReadStateFromStream,
// emuWriteStateToStream
CPUWriteStateToStream,
// emuReadMemState
CPUReadMemState,
// emuWriteMemState
CPUWriteMemState,
// emuWritePNG
CPUWritePNGFile,
// emuWriteBMP
CPUWriteBMPFile,
// emuUpdateCPSR
CPUUpdateCPSR,
// emuHasDebugger
true,
// emuCount
#ifdef FINAL_VERSION
250000,
#else
5000,
#endif
};
| Java |
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(SpriteRenderer))]
public class SpriteRandomiser : MonoBehaviour {
[System.Serializable]
public class PossibleState
{
public Sprite texture = null;
public Color color = Color.white;
};
public PossibleState[] possibleStates = new PossibleState[0];
public void RandomiseSprite()
{
Random.seed = (int)Time.time;
if(possibleStates.Length > 0)
{
PossibleState state = possibleStates[Random.Range(0,possibleStates.Length)];
SpriteRenderer spriteRenderer = GetComponent<Renderer>() as SpriteRenderer;
spriteRenderer.sprite = state.texture;
spriteRenderer.color = state.color;
}
}
// Use this for initialization
void Start ()
{
RandomiseSprite();
}
}
| Java |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AppTestDeployment")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AppTestDeployment")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Java |
<!doctype html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]-->
<!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]-->
<head>
{% include head.html %}
</head>
<body id="post">
{% include navigation.html %}
<div id="main" role="main">
<article class="hentry">
{% if page.image.feature %}<img src="{{ site.url }}/images/{{ page.image.feature }}" class="entry-feature-image" alt="{{ page.title }}">{% if page.image.credit %}<p class="image-credit">Photo Credit: <a href="{{ page.image.creditlink }}">{{ page.image.credit }}</a>{% endif %}{% endif %}
<div class="entry-wrapper">
<header class="entry-header">
<span class="entry-tags">{% for tag in page.tags %}<a href="{{ site.url }}/tags.html#{{ tag | cgi_encode }}" title="Pages tagged {{ tag }}">{{ tag }}</a>{% unless forloop.last %} • {% endunless %}{% endfor %}</span>
{% if page.link %}
<h1 class="entry-title"><a href="{{ page.link }}">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %} <span class="link-arrow">→</span></a></h1>
{% else %}
<h1 class="entry-title">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %}</h1>
{% endif %}
</header>
<footer class="entry-meta">
<img src="{{ site.url }}/images/{{ site.owner.avatar }}" alt="{{ site.owner.name }} photo" class="author-photo">
<span class="author vcard">By <span class="fn"><a href="{{ site.url }}/about/" title="About {{ site.owner.name }}">{{ site.owner.name }}</a></span></span>
<span class="entry-date date published"><time datetime="{{ page.date | date_to_xmlschema }}"><i class="icon-calendar-empty"></i> {{ page.date | date: "%B %d, %Y" }}</time></span>
{% if page.modified %}<span class="entry-date date modified"><time datetime="{{ page.modified }}"><i class="icon-pencil"></i> {{ page.modified | date: "%B %d, %Y" }}</time></span>{% endif %}
{% if site.disqus_shortname and page.comments %}<span class="entry-comments"><i class="icon-comment-alt"></i> <a href="#disqus_thread">Comment</a></span>{% endif %}
<span><a href="{{ site.url }}{{ page.url }}" rel="bookmark" title="{{ page.title }}"><i class="icon-link"></i> Permalink</a></span>
{% if page.share %}
<span class="social-share-facebook">
<a href="https://www.facebook.com/sharer/sharer.php?u={{ site.url }}{{ page.url }}" title="Share on Facebook" itemprop="Facebook"><i class="icon-facebook-sign"></i> Like</a></span>
<span class="social-share-twitter">
<a href="https://twitter.com/intent/tweet?text={{ site.url }}{{ page.url }}" title="Share on Twitter" itemprop="Twitter"><i class="icon-twitter-sign"></i> Tweet</a></span>
<span class="social-share-googleplus">
<a href="https://plus.google.com/share?url={{ site.url }}{{ page.url }}" title="Share on Google Plus" itemprop="GooglePlus"><i class="icon-google-plus-sign"></i> +1</a></span>
<!-- /.social-share -->{% endif %}
</footer>
<div class="entry-content">
{{ content }}
{% if site.disqus_shortname and page.comments %}<div id="disqus_thread"></div><!-- /#disqus_thread -->{% endif %}
</div><!-- /.entry-content -->
</div><!-- /.entry-wrapper -->
<nav class="pagination" role="navigation">
{% if page.previous %}
<a href="{{ site.url }}{{ page.previous.url }}" class="btn" title="{{ page.previous.title }}">Previous article</a>
{% endif %}
{% if page.next %}
<a href="{{ site.url }}{{ page.next.url }}" class="btn" title="{{ page.next.title }}">Next article</a>
{% endif %}
</nav><!-- /.pagination -->
</article>
</div><!-- /#main -->
<div class="footer-wrapper">
<footer role="contentinfo">
{% include footer.html %}
</footer>
</div><!-- /.footer-wrapper -->
{% include scripts.html %}
</body>
</html>
| Java |
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Session;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;
namespace MediaBrowser.Controller.Net
{
public interface ISessionContext
{
Task<SessionInfo> GetSession(object requestContext);
Task<User> GetUser(object requestContext);
Task<SessionInfo> GetSession(IRequest requestContext);
Task<User> GetUser(IRequest requestContext);
}
}
| Java |
/* About Css */
body {
-webkit-touch-callout: none; /* prevent callout to copy image, etc when tap to hold */
-webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */
-webkit-user-select: none; /* prevent copy paste, to allow, change 'none' to 'text' */
background: #333333;
background-attachment:fixed;
font-family:'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif;
font-size:12px;
height:100%;
margin:0px;
padding:0px;
width:100%;
}
/* Portrait layout (default) */
.app {
height:250px;
width:300px;
margin:30px;
}
/* Landscape layout (with min-width) */
@media screen and (min-aspect-ratio: 1/1) and (min-width:400px) {
.app {
margin-left:160px;
}
}
h1{
font-size:30px;
font-weight:normal;
margin:0px;
overflow:visible;
padding:0px;
text-align:center;
color:#FEFEFE;
}
.button{
background:#9f9f9f;
border-radius:10px;
margin:auto;
text-align:center;
text-decoration:none;
border:#8f8f8f solid 1px;
}
.button p{
color:#fefefe;
text-align:center;
text-decoration:none;
font-size:24px;
padding:15px 0;
margin:0;
}
.button:hover,.button:active{
background:#6f6f6f;
color:#efefef;
}
.back{
margin-left:-25px;
margin-right:15px;
color:#fefefe;
font-size:20px;
padding:10px;
background-color: #428bca;
border-color: #357ebd;
}
.back:hover,.back:active{
background-color: #3071a9;
border-color: #285e8e;
} | Java |
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define MAX_SIZE 1010
int getarray(int a[])
{
int i=0,count;
scanf("%d",&count);
for(; i<count ; i++)
scanf("%d",&a[i]);
return count;
}
int find(int a[], int n, int val)
{
int i,true=0;
for(i=0; i<n; i++)
{
if(a[i]==val)
{
true=1;
return i;
}
}
if(true==0)
return -1;
}
int main()
{
int cases, i;
int arr[MAX_SIZE], size;
int val, found = 0;
scanf("%d", &cases);
for(i = 1; i <= cases; i++)
{
size = getarray(arr);
scanf("%d", &val);
found = find(arr, size, val);
if(found == -1)
{
printf("NOT FOUND\n");
continue;
}
printf("%d\n", found);
}
return 0;
}
| Java |
<section id="options">
<?php
$terms = array();
$vid = NULL;
$vid_machine_name = 'portfolio_categories';
$vocabulary = taxonomy_vocabulary_machine_name_load($vid_machine_name);
if (!empty($vocabulary->vid)) {
$vid = $vocabulary->vid;
}
if (!empty($vid)) {
$terms = taxonomy_get_tree($vid);
}
?>
<ul id="filters" class="option-set right" data-option-key="filter">
<li><a href="#filter" data-option-value="*" class="button small selected"><?php print t('Show All'); ?></a></li>
<?php if (!empty($terms)): ?>
<?php foreach ($terms as $term): ?>
<li><a href="#filter" data-option-value=".tid-<?php print $term->tid; ?>" class="button small"><?php print $term->name; ?></a></li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</section> | Java |
/**
* jBorZoi - An Elliptic Curve Cryptography Library
*
* Copyright (C) 2003 Dragongate Technologies Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.dragongate_technologies.borZoi;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
* Elliptic Curve Private Keys consisting of two member variables: dp,
* the EC domain parameters and s, the private key which must
* be kept secret.
* @author <a href="http://www.dragongate-technologies.com">Dragongate Technologies Ltd.</a>
* @version 0.90
*/
public class ECPrivKey {
/**
* The EC Domain Parameters
*/
public ECDomainParameters dp;
/**
* The Private Key
*/
public BigInteger s;
/**
* Generate a random private key with ECDomainParameters dp
*/
public ECPrivKey(ECDomainParameters dp) {
this.dp = (ECDomainParameters) dp.clone();
SecureRandom rnd = new SecureRandom();
s = new BigInteger(dp.m, rnd);
s = s.mod(dp.r);
}
/**
* Generate a private key with ECDomainParameters dp
* and private key s
*/
public ECPrivKey(ECDomainParameters dp, BigInteger s) {
this.dp = dp;
this.s = s;
}
public String toString() {
String str = new String("dp: ").concat(dp.toString()).concat("\n");
str = str.concat("s: ").concat(s.toString()).concat("\n");
return str;
}
protected Object clone() {
return new ECPrivKey(dp, s);
}
}
| Java |
<!DOCTYPE html>
<html xml:lang="en-US" lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-US">
<title>My Family Tree - Sanchez, John</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.2 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
<link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">My Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="IndividualDetail">
<h3>Sanchez, John<sup><small> <a href="#sref1">1</a></small></sup></h3>
<div id="summaryarea">
<table class="infolist">
<tr>
<td class="ColumnAttribute">Birth Name</td>
<td class="ColumnValue">
Sanchez, John
</td>
</tr>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">I0685</td>
</tr>
<tr>
<td class="ColumnAttribute">Gender</td>
<td class="ColumnValue">male</td>
</tr>
<tr>
<td class="ColumnAttribute">Age at Death</td>
<td class="ColumnValue">about 65 years</td>
</tr>
</table>
</div>
<div class="subsection" id="events">
<h4>Events</h4>
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
Birth
</td>
<td class="ColumnDate">about 1480</td>
<td class="ColumnPlace">
<a href="../../../plc/l/v/II6KQCD2F8F42WXMVL.html" title="Phoenix, Maricopa, AZ, USA">
Phoenix, Maricopa, AZ, USA
</a>
</td>
<td class="ColumnDescription">
Birth of Sanchez, John
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
<tr>
<td class="ColumnEvent">
Death
</td>
<td class="ColumnDate">1545</td>
<td class="ColumnPlace">
<a href="../../../plc/l/v/II6KQCD2F8F42WXMVL.html" title="Phoenix, Maricopa, AZ, USA">
Phoenix, Maricopa, AZ, USA
</a>
</td>
<td class="ColumnDescription">
Death of Sanchez, John
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="parents">
<h4>Parents</h4>
<table class="infolist">
<thead>
<tr>
<th class="ColumnAttribute">Relation to main person</th>
<th class="ColumnValue">Name</th>
<th class="ColumnValue">Relation within this family (if not by birth)</th>
</tr>
</thead>
<tbody>
</tbody>
<tr>
<td class="ColumnAttribute">Father</td>
<td class="ColumnValue">
<a href="../../../ppl/b/c/4GGKQCM55ID425VACB.html">Molina, Robert<span class="grampsid"> [I1154]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"> <a href="../../../ppl/e/0/9I6KQCF5N90G0VRI0E.html">Sanchez, John<span class="grampsid"> [I0685]</span></a></td>
<td class="ColumnValue"></td>
</tr>
</table>
</div>
<div class="subsection" id="families">
<h4>Families</h4>
<table class="infolist">
<tr class="BeginFamily">
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"><a href="" title="Family of Sanchez, John and Curtis, Margaret">Family of Sanchez, John and Curtis, Margaret<span class="grampsid"> [F0382]</span></a></td>
</tr>
<tr class="BeginFamily">
<td class="ColumnType">Married</td>
<td class="ColumnAttribute">Wife</td>
<td class="ColumnValue">
<a href="../../../ppl/j/h/4EGKQC200RACB7Y6HJ.html">Curtis, Margaret<span class="grampsid"> [I1150]</span></a>
</td>
</tr>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue">
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
Marriage
</td>
<td class="ColumnDate"> </td>
<td class="ColumnPlace">
<a href="../../../plc/l/8/OFGKQC9VTT55S65K8L.html" title="Deming, NM, USA">
Deming, NM, USA
</a>
</td>
<td class="ColumnDescription">
Marriage of Sanchez, John and Curtis, Margaret
</td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
</tbody>
</table>
</td>
<tr>
<td class="ColumnType"> </td>
<td class="ColumnAttribute">Children</td>
<td class="ColumnValue">
<ol>
<li>
<a href="../../../ppl/z/7/2J6KQC39AHC9O4YD7Z.html">Lefebvre, Robert<span class="grampsid"> [I0686]</span></a>
</li>
</ol>
</td>
</tr>
</tr>
</table>
</div>
<div class="subsection" id="pedigree">
<h4>Pedigree</h4>
<ol class="pedigreegen">
<li>
<a href="../../../ppl/b/c/4GGKQCM55ID425VACB.html">Molina, Robert<span class="grampsid"> [I1154]</span></a>
<ol>
<li class="thisperson">
Sanchez, John
<ol class="spouselist">
<li class="spouse">
<a href="../../../ppl/j/h/4EGKQC200RACB7Y6HJ.html">Curtis, Margaret<span class="grampsid"> [I1150]</span></a>
<ol>
<li>
<a href="../../../ppl/z/7/2J6KQC39AHC9O4YD7Z.html">Lefebvre, Robert<span class="grampsid"> [I0686]</span></a>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
</ol>
</div>
<div class="subsection" id="tree">
<h4>Ancestors</h4>
<div id="treeContainer" style="width:735px; height:602px;">
<div class="boxbg male AncCol0" style="top: 269px; left: 6px;">
<a class="noThumb" href="../../../ppl/e/0/9I6KQCF5N90G0VRI0E.html">
Sanchez, John
</a>
</div>
<div class="shadow" style="top: 274px; left: 10px;"></div>
<div class="bvline" style="top: 301px; left: 165px; width: 15px"></div>
<div class="gvline" style="top: 306px; left: 165px; width: 20px"></div>
<div class="boxbg male AncCol1" style="top: 119px; left: 196px;">
<a class="noThumb" href="../../../ppl/b/c/4GGKQCM55ID425VACB.html">
Molina, Robert
</a>
</div>
<div class="shadow" style="top: 124px; left: 200px;"></div>
<div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div>
<div class="bvline" style="top: 151px; left: 355px; width: 15px"></div>
<div class="gvline" style="top: 156px; left: 355px; width: 20px"></div>
<div class="boxbg male AncCol2" style="top: 44px; left: 386px;">
<a class="noThumb" href="../../../ppl/b/m/VGGKQC6Z87K666ENMB.html">
Guerrero, Robert
</a>
</div>
<div class="shadow" style="top: 49px; left: 390px;"></div>
<div class="bvline" style="top: 76px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 81px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 76px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 81px; left: 375px; height: 75px;"></div>
<div class="bvline" style="top: 76px; left: 545px; width: 15px"></div>
<div class="gvline" style="top: 81px; left: 545px; width: 20px"></div>
<div class="boxbg male AncCol3" style="top: 7px; left: 576px;">
<a class="noThumb" href="../../../ppl/g/r/GHGKQCAPWR3J6XMRG.html">
Guerrero, Robert
</a>
</div>
<div class="shadow" style="top: 12px; left: 580px;"></div>
<div class="bvline" style="top: 39px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 44px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 39px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 44px; left: 565px; height: 37px;"></div>
</div>
</div>
<div class="subsection" id="sourcerefs">
<h4>Source References</h4>
<ol>
<li>
<a href="../../../src/x/a/X5TJQC9JXU4RKT6VAX.html" title="Import from test2.ged" name ="sref1">
Import from test2.ged
<span class="grampsid"> [S0003]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.2 on 2015-12-25<br />Last change was the 2007-07-26 08:34:25
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
| Java |
/*
The GTKWorkbook Project <http://gtkworkbook.sourceforge.net/>
Copyright (C) 2008, 2009 John Bellone, Jr. <jvb4@njit.edu>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PRACTICAL PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301 USA
*/
#include <sstream>
#include <gdk/gdkkeysyms.h>
#include <libgtkworkbook/workbook.h>
#include <proactor/Proactor.hpp>
#include <proactor/Event.hpp>
#include <network/Tcp.hpp>
#include "Realtime.hpp"
using namespace realtime;
/* @description: This method creates a filename with the prefix supplied and
uses the pid of the process as its suffix.
@pre: The prefix (should be a file path, obviously). */
static std::string
AppendProcessId (const gchar * pre) {
std::stringstream s;
s << pre << getppid();
return s.str();
}
static void
StreamOpenDialogCallback (GtkWidget * w, gpointer data) {
Realtime * rt = (Realtime *)data;
OpenStreamDialog * dialog = rt->streamdialog();
if (dialog->widget == NULL) {
dialog->rt = rt;
dialog->widget = gtk_dialog_new_with_buttons ("Open stream ", GTK_WINDOW (rt->app()->gtkwindow()),
(GtkDialogFlags) (GTK_DIALOG_MODAL|GTK_DIALOG_NO_SEPARATOR),
GTK_STOCK_OK,
GTK_RESPONSE_OK,
GTK_STOCK_CANCEL,
GTK_RESPONSE_CANCEL,
NULL);
GtkWidget * gtk_frame = gtk_frame_new ("Connection Options");
GtkWidget * hbox = gtk_hbox_new(FALSE, 0);
GtkWidget * box = GTK_DIALOG (dialog->widget)->vbox;
dialog->host_entry = gtk_entry_new();
dialog->port_entry = gtk_entry_new();
gtk_entry_set_max_length (GTK_ENTRY (dialog->host_entry), 15);
gtk_entry_set_max_length (GTK_ENTRY (dialog->port_entry), 5);
gtk_entry_set_width_chars (GTK_ENTRY (dialog->host_entry), 15);
gtk_entry_set_width_chars (GTK_ENTRY (dialog->port_entry), 5);
gtk_box_pack_start (GTK_BOX (hbox), dialog->host_entry, FALSE, FALSE, 0);
gtk_box_pack_end (GTK_BOX (hbox), dialog->port_entry, FALSE, FALSE, 0);
gtk_container_add (GTK_CONTAINER (gtk_frame), hbox);
gtk_box_pack_start (GTK_BOX (box), gtk_frame, FALSE, FALSE, 0);
g_signal_connect (G_OBJECT (dialog->widget), "delete-event",
G_CALLBACK (gtk_widget_hide_on_delete), NULL);
}
gtk_widget_show_all ( dialog->widget );
if (gtk_dialog_run (GTK_DIALOG (dialog->widget)) == GTK_RESPONSE_OK) {
const char * host_value = gtk_entry_get_text (GTK_ENTRY (dialog->host_entry));
const char * port_value = gtk_entry_get_text (GTK_ENTRY (dialog->port_entry));
Sheet * sheet = rt->workbook()->add_new_sheet (rt->workbook(), host_value, 100, 20);
if (IS_NULLSTR (host_value) || IS_NULLSTR (port_value)) {
g_warning ("One of requird values are empty");
}
else if (sheet == NULL) {
g_warning ("Cannot open connection to %s:%s because of failure to add sheet",
host_value, port_value);
}
else if (rt->OpenTcpClient (sheet, host_value, atoi (port_value)) == false) {
// STUB: Popup an alertbox about failing to connect?
}
else {
// STUB: Success. Do we want to do anything else here?
g_message ("Client connection opened on %s:%s on sheet %s", host_value, port_value, sheet->name);
}
}
gtk_widget_hide_all ( dialog->widget );
}
Realtime::Realtime (Application * appstate, Handle * platform)
: Plugin (appstate, platform) {
ConfigPair * logpath =
appstate->config()->get_pair (appstate->config(), "realtime", "log", "path");
if (IS_NULL (logpath)) {
g_critical ("Failed loading log->path from configuration file. Exiting application.");
exit(1);
}
std::string logname = std::string (logpath->value).append("/");
logname.append (AppendProcessId("realtime.").append(".log"));
if ((pktlog = fopen (logname.c_str(), "w")) == NULL) {
g_critical ("Failed opening file '%s' for packet logging", logname.c_str());
}
this->wb = workbook_open (appstate->gtkwindow(), "realtime");
this->packet_parser = NULL;
this->tcp_server = NULL;
}
Realtime::~Realtime (void) {
// Iterate through the list of active connections, and begin closing them. This should also
// include deleting the pointers to all of the accepting threads. Eventually there should be
// a boost::shared_ptr here so that we don't have to do the dirty work.
ActiveThreads::iterator it = this->threads.begin();
while (it != this->threads.end()) {
network::TcpSocket * socket = ((*it).first);
concurrent::Thread * thread = ((*it).second);
it = this->threads.erase (it);
if (socket) delete socket;
if (thread) {
thread->stop();
delete thread;
}
}
if (this->packet_parser) {
this->packet_parser->stop();
delete this->packet_parser;
}
if (this->tcp_server) {
this->tcp_server->stop();
delete this->tcp_server;
}
FCLOSE (this->pktlog);
}
bool
Realtime::CreateNewServerConnection (network::TcpServerSocket * socket, AcceptThread * accept_thread) {
this->threads.push_back ( ActiveThread (socket, accept_thread) );
if (this->tcp_server->addWorker (accept_thread) == false) {
g_critical ("Failed starting accepting thread on socket %d", socket->getPort() );
return false;
}
return true;
}
bool
Realtime::CreateNewClientConnection (network::TcpClientSocket * socket, CsvParser * csv, NetworkDispatcher * nd) {
this->threads.push_back ( ActiveThread (socket, csv) );
this->threads.push_back ( ActiveThread (NULL, nd) ); // this is a hack
ConnectionThread * reader = new ConnectionThread (socket);
if (nd->addWorker (reader) == false) {
g_critical ("Failed starting the client reader");
delete reader;
return false;
}
this->threads.push_back ( ActiveThread (NULL, reader) ); // this is a hack
return true;
}
bool
Realtime::OpenTcpServer (int port) {
// Has to be above the service ports.
if (port < 1000) {
g_warning ("Failed starting Tcp server: port (%d) must be above 1000", port);
return false;
}
// The first time we attempt to create a port to receive input on we need to create a dispatcher, and
// specify an event identifier so that we can communicate with it from workers. At this point the
// Packet Parser is created as well.
if (this->tcp_server == NULL) {
int eventId = proactor::Event::uniqueEventId();
NetworkDispatcher * nd = new NetworkDispatcher (eventId);
PacketParser * pp = new PacketParser (this->workbook(), this->pktlog, 0);
if (nd->start() == false) {
g_critical ("Failed starting network dispatcher for tcp server");
return false;
}
if (this->app()->proactor()->addWorker (eventId, pp) == false) {
g_critical ("Failed starting packet parser for tcp server");
return false;
}
this->tcp_server = nd;
this->packet_parser = pp;
}
network::TcpServerSocket * socket = new network::TcpServerSocket (port);
if (socket->start(5) == false) {
g_critical ("Failed starting network socket for tcp server on port %d", port);
return false;
}
AcceptThread * accept_thread = new AcceptThread (socket->newAcceptor());
return this->CreateNewServerConnection (socket, accept_thread);
}
bool
Realtime::OpenTcpClient (Sheet * sheet, const std::string & address, int port) {
// Has to be above the service ports.
if (port < 1000) {
g_warning ("Failed starting Tcp client: port (%d) must be above 1000", port);
return false;
}
// We need to create a network dispatcher for each one of these connections because of
// the current limitation of the Proactor design. It really needs to be rewritten, but
// that is a separate project in and of itself. For now a list of dispatchers must be
// kept so that we do not lose track.
int eventId = proactor::Event::uniqueEventId();
NetworkDispatcher * dispatcher = new NetworkDispatcher (eventId);
if (dispatcher->start() == false) {
g_critical ("Failed starting network dispatcher for %s:%d", address.c_str(), port);
delete dispatcher;
return false;
}
// Keeping this simple is the reason why we need multiple dispatchers. If I could come
// up with a simple way to strap on the ability to have multiple sheets without the need
// for an additioanl dispatcher/csv combo I would. It totally destroys the principle of
// the proactor design.
CsvParser * csv = new CsvParser (sheet, this->pktlog, 0);
if (this->app()->proactor()->addWorker (eventId, csv) == false) {
g_critical ("Failed starting csv parser and adding to proactor for %s:%d",
address.c_str(), port);
delete csv;
delete dispatcher;
return false;
}
network::TcpClientSocket * socket = new network::TcpClientSocket;
if (socket->connect (address.c_str(), port) == false) {
g_critical ("Failed making Tcp connection to %s:%d", address.c_str(), port);
delete socket;
delete csv;
delete dispatcher;
return false;
}
return this->CreateNewClientConnection (socket, csv, dispatcher);
}
void
Realtime::Start(void) {
Config * cfg = this->app()->config();
ConfigPair * servport = cfg->get_pair (cfg, "realtime", "tcp", "port");
int port = atoi (servport->value);
if (this->OpenTcpServer (port) == true) {
g_message ("Opened Tcp server on port %d", port);
}
}
GtkWidget *
Realtime::CreateMainMenu (void) {
GtkWidget * rtmenu = gtk_menu_new();
GtkWidget * rtmenu_item = gtk_menu_item_new_with_label ("Realtime");
GtkWidget * rtmenu_open = gtk_menu_item_new_with_label ("Open Csv stream...");
gtk_menu_shell_append (GTK_MENU_SHELL (rtmenu), rtmenu_open);
g_signal_connect (G_OBJECT (rtmenu_open), "activate",
G_CALLBACK (StreamOpenDialogCallback), this);
gtk_menu_item_set_submenu (GTK_MENU_ITEM (rtmenu_item), rtmenu);
return rtmenu_item;
}
GtkWidget *
Realtime::BuildLayout (void) {
GtkWidget * gtk_menu = this->app()->gtkmenu();
GtkWidget * box = gtk_vbox_new (FALSE, 0);
GtkWidget * realtime_menu = this->CreateMainMenu();
// Append to the existing menu structure from the application.
gtk_menu_shell_prepend (GTK_MENU_SHELL (gtk_menu), realtime_menu);
// Setup the workbook.
wb->signals[SIG_WORKBOOK_CHANGED] = this->app()->signals[Application::SHEET_CHANGED];
wb->gtk_box = box;
// Pack all of the objects into a vertical box, and then pack that box into the application.
gtk_box_pack_start (GTK_BOX (box), wb->gtk_notebook, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (this->app()->gtkvbox()), box, TRUE, TRUE, 0);
return box;
}
| Java |
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xml:base="http://machines.plannedobsolescence.net/149-2007" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>postmodernism - apathy</title>
<link>http://machines.plannedobsolescence.net/149-2007/taxonomy/term/72/0</link>
<description></description>
<language>en</language>
<item>
<title>Postmodern Political Apathy</title>
<link>http://machines.plannedobsolescence.net/149-2007/node/27</link>
<description><p>I identified with the some of Jameson's views on postmodern feelings, or lack thereof.</p>
<p><a href="http://machines.plannedobsolescence.net/149-2007/node/27">read more</a></p></description>
<comments>http://machines.plannedobsolescence.net/149-2007/node/27#comments</comments>
<category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/72">apathy</category>
<category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/73">feeling</category>
<category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/55">Jameson</category>
<category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/71">politics</category>
<pubDate>Mon, 24 Sep 2007 02:42:00 +0000</pubDate>
<dc:creator>blankman</dc:creator>
<guid isPermaLink="false">27 at http://machines.plannedobsolescence.net/149-2007</guid>
</item>
</channel>
</rss>
| Java |
/***************************************************************************
qgscalloutwidget.cpp
---------------------
begin : July 2019
copyright : (C) 2019 by Nyall Dawson
email : nyall dot dawson at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgscalloutwidget.h"
#include "qgsvectorlayer.h"
#include "qgsexpressioncontextutils.h"
#include "qgsunitselectionwidget.h"
#include "qgscallout.h"
#include "qgsnewauxiliaryfielddialog.h"
#include "qgsnewauxiliarylayerdialog.h"
#include "qgsauxiliarystorage.h"
QgsExpressionContext QgsCalloutWidget::createExpressionContext() const
{
if ( auto *lExpressionContext = mContext.expressionContext() )
return *lExpressionContext;
QgsExpressionContext expContext( mContext.globalProjectAtlasMapLayerScopes( vectorLayer() ) );
QgsExpressionContextScope *symbolScope = QgsExpressionContextUtils::updateSymbolScope( nullptr, new QgsExpressionContextScope() );
symbolScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_SYMBOL_COLOR, QColor(), true ) );
expContext << symbolScope;
// additional scopes
const auto constAdditionalExpressionContextScopes = mContext.additionalExpressionContextScopes();
for ( const QgsExpressionContextScope &scope : constAdditionalExpressionContextScopes )
{
expContext.appendScope( new QgsExpressionContextScope( scope ) );
}
//TODO - show actual value
expContext.setOriginalValueVariable( QVariant() );
expContext.setHighlightedVariables( QStringList() << QgsExpressionContext::EXPR_ORIGINAL_VALUE << QgsExpressionContext::EXPR_SYMBOL_COLOR );
return expContext;
}
void QgsCalloutWidget::setContext( const QgsSymbolWidgetContext &context )
{
mContext = context;
const auto unitSelectionWidgets = findChildren<QgsUnitSelectionWidget *>();
for ( QgsUnitSelectionWidget *unitWidget : unitSelectionWidgets )
{
unitWidget->setMapCanvas( mContext.mapCanvas() );
}
const auto symbolButtonWidgets = findChildren<QgsSymbolButton *>();
for ( QgsSymbolButton *symbolWidget : symbolButtonWidgets )
{
symbolWidget->setMapCanvas( mContext.mapCanvas() );
symbolWidget->setMessageBar( mContext.messageBar() );
}
}
QgsSymbolWidgetContext QgsCalloutWidget::context() const
{
return mContext;
}
void QgsCalloutWidget::registerDataDefinedButton( QgsPropertyOverrideButton *button, QgsCallout::Property key )
{
button->init( key, callout()->dataDefinedProperties(), QgsCallout::propertyDefinitions(), mVectorLayer, true );
connect( button, &QgsPropertyOverrideButton::changed, this, &QgsCalloutWidget::updateDataDefinedProperty );
connect( button, &QgsPropertyOverrideButton::createAuxiliaryField, this, &QgsCalloutWidget::createAuxiliaryField );
button->registerExpressionContextGenerator( this );
}
void QgsCalloutWidget::createAuxiliaryField()
{
// try to create an auxiliary layer if not yet created
if ( !mVectorLayer->auxiliaryLayer() )
{
QgsNewAuxiliaryLayerDialog dlg( mVectorLayer, this );
dlg.exec();
}
// return if still not exists
if ( !mVectorLayer->auxiliaryLayer() )
return;
QgsPropertyOverrideButton *button = qobject_cast<QgsPropertyOverrideButton *>( sender() );
QgsCallout::Property key = static_cast< QgsCallout::Property >( button->propertyKey() );
QgsPropertyDefinition def = QgsCallout::propertyDefinitions()[key];
// create property in auxiliary storage if necessary
if ( !mVectorLayer->auxiliaryLayer()->exists( def ) )
{
QgsNewAuxiliaryFieldDialog dlg( def, mVectorLayer, true, this );
if ( dlg.exec() == QDialog::Accepted )
def = dlg.propertyDefinition();
}
// return if still not exist
if ( !mVectorLayer->auxiliaryLayer()->exists( def ) )
return;
// update property with join field name from auxiliary storage
QgsProperty property = button->toProperty();
property.setField( QgsAuxiliaryLayer::nameFromProperty( def, true ) );
property.setActive( true );
button->updateFieldLists();
button->setToProperty( property );
callout()->dataDefinedProperties().setProperty( key, button->toProperty() );
emit changed();
}
void QgsCalloutWidget::updateDataDefinedProperty()
{
QgsPropertyOverrideButton *button = qobject_cast<QgsPropertyOverrideButton *>( sender() );
QgsCallout::Property key = static_cast< QgsCallout::Property >( button->propertyKey() );
callout()->dataDefinedProperties().setProperty( key, button->toProperty() );
emit changed();
}
/// @cond PRIVATE
//
// QgsSimpleLineCalloutWidget
//
QgsSimpleLineCalloutWidget::QgsSimpleLineCalloutWidget( QgsVectorLayer *vl, QWidget *parent )
: QgsCalloutWidget( parent, vl )
{
setupUi( this );
// Callout options - to move to custom widgets when multiple callout styles exist
mCalloutLineStyleButton->setSymbolType( QgsSymbol::Line );
mCalloutLineStyleButton->setDialogTitle( tr( "Callout Symbol" ) );
mCalloutLineStyleButton->registerExpressionContextGenerator( this );
mCalloutLineStyleButton->setLayer( vl );
mMinCalloutWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
mOffsetFromAnchorUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
mOffsetFromLabelUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels
<< QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches );
connect( mMinCalloutWidthUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsSimpleLineCalloutWidget::minimumLengthUnitWidgetChanged );
connect( mMinCalloutLengthSpin, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsSimpleLineCalloutWidget::minimumLengthChanged );
connect( mOffsetFromAnchorUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsSimpleLineCalloutWidget::offsetFromAnchorUnitWidgetChanged );
connect( mOffsetFromAnchorSpin, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsSimpleLineCalloutWidget::offsetFromAnchorChanged );
connect( mOffsetFromLabelUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsSimpleLineCalloutWidget::offsetFromLabelUnitWidgetChanged );
connect( mOffsetFromLabelSpin, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsSimpleLineCalloutWidget::offsetFromLabelChanged );
connect( mDrawToAllPartsCheck, &QCheckBox::toggled, this, &QgsSimpleLineCalloutWidget::drawToAllPartsToggled );
// Anchor point options
mAnchorPointComboBox->addItem( tr( "Pole of Inaccessibility" ), static_cast< int >( QgsCallout::PoleOfInaccessibility ) );
mAnchorPointComboBox->addItem( tr( "Point on Exterior" ), static_cast< int >( QgsCallout::PointOnExterior ) );
mAnchorPointComboBox->addItem( tr( "Point on Surface" ), static_cast< int >( QgsCallout::PointOnSurface ) );
mAnchorPointComboBox->addItem( tr( "Centroid" ), static_cast< int >( QgsCallout::Centroid ) );
connect( mAnchorPointComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsSimpleLineCalloutWidget::mAnchorPointComboBox_currentIndexChanged );
mLabelAnchorPointComboBox->addItem( tr( "Closest Point" ), static_cast< int >( QgsCallout::LabelPointOnExterior ) );
mLabelAnchorPointComboBox->addItem( tr( "Centroid" ), static_cast< int >( QgsCallout::LabelCentroid ) );
mLabelAnchorPointComboBox->addItem( tr( "Top Left" ), static_cast< int >( QgsCallout::LabelTopLeft ) );
mLabelAnchorPointComboBox->addItem( tr( "Top Center" ), static_cast< int >( QgsCallout::LabelTopMiddle ) );
mLabelAnchorPointComboBox->addItem( tr( "Top Right" ), static_cast< int >( QgsCallout::LabelTopRight ) );
mLabelAnchorPointComboBox->addItem( tr( "Left Middle" ), static_cast< int >( QgsCallout::LabelMiddleLeft ) );
mLabelAnchorPointComboBox->addItem( tr( "Right Middle" ), static_cast< int >( QgsCallout::LabelMiddleRight ) );
mLabelAnchorPointComboBox->addItem( tr( "Bottom Left" ), static_cast< int >( QgsCallout::LabelBottomLeft ) );
mLabelAnchorPointComboBox->addItem( tr( "Bottom Center" ), static_cast< int >( QgsCallout::LabelBottomMiddle ) );
mLabelAnchorPointComboBox->addItem( tr( "Bottom Right" ), static_cast< int >( QgsCallout::LabelBottomRight ) );
connect( mLabelAnchorPointComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsSimpleLineCalloutWidget::mLabelAnchorPointComboBox_currentIndexChanged );
connect( mCalloutLineStyleButton, &QgsSymbolButton::changed, this, &QgsSimpleLineCalloutWidget::lineSymbolChanged );
}
void QgsSimpleLineCalloutWidget::setCallout( QgsCallout *callout )
{
if ( !callout )
return;
mCallout.reset( dynamic_cast<QgsSimpleLineCallout *>( callout->clone() ) );
if ( !mCallout )
return;
mMinCalloutWidthUnitWidget->blockSignals( true );
mMinCalloutWidthUnitWidget->setUnit( mCallout->minimumLengthUnit() );
mMinCalloutWidthUnitWidget->setMapUnitScale( mCallout->minimumLengthMapUnitScale() );
mMinCalloutWidthUnitWidget->blockSignals( false );
whileBlocking( mMinCalloutLengthSpin )->setValue( mCallout->minimumLength() );
mOffsetFromAnchorUnitWidget->blockSignals( true );
mOffsetFromAnchorUnitWidget->setUnit( mCallout->offsetFromAnchorUnit() );
mOffsetFromAnchorUnitWidget->setMapUnitScale( mCallout->offsetFromAnchorMapUnitScale() );
mOffsetFromAnchorUnitWidget->blockSignals( false );
mOffsetFromLabelUnitWidget->blockSignals( true );
mOffsetFromLabelUnitWidget->setUnit( mCallout->offsetFromLabelUnit() );
mOffsetFromLabelUnitWidget->setMapUnitScale( mCallout->offsetFromLabelMapUnitScale() );
mOffsetFromLabelUnitWidget->blockSignals( false );
whileBlocking( mOffsetFromAnchorSpin )->setValue( mCallout->offsetFromAnchor() );
whileBlocking( mOffsetFromLabelSpin )->setValue( mCallout->offsetFromLabel() );
whileBlocking( mCalloutLineStyleButton )->setSymbol( mCallout->lineSymbol()->clone() );
whileBlocking( mDrawToAllPartsCheck )->setChecked( mCallout->drawCalloutToAllParts() );
whileBlocking( mAnchorPointComboBox )->setCurrentIndex( mAnchorPointComboBox->findData( static_cast< int >( callout->anchorPoint() ) ) );
whileBlocking( mLabelAnchorPointComboBox )->setCurrentIndex( mLabelAnchorPointComboBox->findData( static_cast< int >( callout->labelAnchorPoint() ) ) );
registerDataDefinedButton( mMinCalloutLengthDDBtn, QgsCallout::MinimumCalloutLength );
registerDataDefinedButton( mOffsetFromAnchorDDBtn, QgsCallout::OffsetFromAnchor );
registerDataDefinedButton( mOffsetFromLabelDDBtn, QgsCallout::OffsetFromLabel );
registerDataDefinedButton( mDrawToAllPartsDDBtn, QgsCallout::DrawCalloutToAllParts );
registerDataDefinedButton( mAnchorPointDDBtn, QgsCallout::AnchorPointPosition );
registerDataDefinedButton( mLabelAnchorPointDDBtn, QgsCallout::LabelAnchorPointPosition );
registerDataDefinedButton( mOriginXDDBtn, QgsCallout::OriginX );
registerDataDefinedButton( mOriginYDDBtn, QgsCallout::OriginY );
registerDataDefinedButton( mDestXDDBtn, QgsCallout::DestinationX );
registerDataDefinedButton( mDestYDDBtn, QgsCallout::DestinationY );
}
void QgsSimpleLineCalloutWidget::setGeometryType( QgsWkbTypes::GeometryType type )
{
bool isPolygon = type == QgsWkbTypes::PolygonGeometry;
mAnchorPointLbl->setEnabled( isPolygon );
mAnchorPointLbl->setVisible( isPolygon );
mAnchorPointComboBox->setEnabled( isPolygon );
mAnchorPointComboBox->setVisible( isPolygon );
mAnchorPointDDBtn->setEnabled( isPolygon );
mAnchorPointDDBtn->setVisible( isPolygon );
}
QgsCallout *QgsSimpleLineCalloutWidget::callout()
{
return mCallout.get();
}
void QgsSimpleLineCalloutWidget::minimumLengthChanged()
{
mCallout->setMinimumLength( mMinCalloutLengthSpin->value() );
emit changed();
}
void QgsSimpleLineCalloutWidget::minimumLengthUnitWidgetChanged()
{
mCallout->setMinimumLengthUnit( mMinCalloutWidthUnitWidget->unit() );
mCallout->setMinimumLengthMapUnitScale( mMinCalloutWidthUnitWidget->getMapUnitScale() );
emit changed();
}
void QgsSimpleLineCalloutWidget::offsetFromAnchorUnitWidgetChanged()
{
mCallout->setOffsetFromAnchorUnit( mOffsetFromAnchorUnitWidget->unit() );
mCallout->setOffsetFromAnchorMapUnitScale( mOffsetFromAnchorUnitWidget->getMapUnitScale() );
emit changed();
}
void QgsSimpleLineCalloutWidget::offsetFromAnchorChanged()
{
mCallout->setOffsetFromAnchor( mOffsetFromAnchorSpin->value() );
emit changed();
}
void QgsSimpleLineCalloutWidget::offsetFromLabelUnitWidgetChanged()
{
mCallout->setOffsetFromLabelUnit( mOffsetFromLabelUnitWidget->unit() );
mCallout->setOffsetFromLabelMapUnitScale( mOffsetFromLabelUnitWidget->getMapUnitScale() );
emit changed();
}
void QgsSimpleLineCalloutWidget::offsetFromLabelChanged()
{
mCallout->setOffsetFromLabel( mOffsetFromLabelSpin->value() );
emit changed();
}
void QgsSimpleLineCalloutWidget::lineSymbolChanged()
{
mCallout->setLineSymbol( mCalloutLineStyleButton->clonedSymbol< QgsLineSymbol >() );
emit changed();
}
void QgsSimpleLineCalloutWidget::mAnchorPointComboBox_currentIndexChanged( int index )
{
mCallout->setAnchorPoint( static_cast<QgsCallout::AnchorPoint>( mAnchorPointComboBox->itemData( index ).toInt() ) );
emit changed();
}
void QgsSimpleLineCalloutWidget::mLabelAnchorPointComboBox_currentIndexChanged( int index )
{
mCallout->setLabelAnchorPoint( static_cast<QgsCallout::LabelAnchorPoint>( mLabelAnchorPointComboBox->itemData( index ).toInt() ) );
emit changed();
}
void QgsSimpleLineCalloutWidget::drawToAllPartsToggled( bool active )
{
mCallout->setDrawCalloutToAllParts( active );
emit changed();
}
//
// QgsManhattanLineCalloutWidget
//
QgsManhattanLineCalloutWidget::QgsManhattanLineCalloutWidget( QgsVectorLayer *vl, QWidget *parent )
: QgsSimpleLineCalloutWidget( vl, parent )
{
}
///@endcond
| Java |
/*
* ws2san.h
*
* WinSock Direct (SAN) support
*
* This file is part of the w32api package.
*
* Contributors:
* Created by Casper S. Hornstrup <chorns@users.sourceforge.net>
*
* THIS SOFTWARE IS NOT COPYRIGHTED
*
* This source code is offered for use in the public domain. You may
* use, modify or distribute it freely.
*
* This code is distributed in the hope that it will be useful but
* WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
* DISCLAIMED. This includes but is not limited to warranties of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#ifndef __WS2SAN_H
#define __WS2SAN_H
#if __GNUC__ >=3
#pragma GCC system_header
#endif
#ifdef __cplusplus
extern "C" {
#endif
#pragma pack(push,4)
#include <winsock2.h>
#include "ntddk.h"
#define WSPAPI STDCALL
/* FIXME: Unknown definitions */
typedef PVOID LPWSPDATA;
typedef PDWORD LPWSATHREADID;
typedef PVOID LPWSPPROC_TABLE;
typedef struct _WSPUPCALLTABLEEX WSPUPCALLTABLEEX;
typedef WSPUPCALLTABLEEX *LPWSPUPCALLTABLEEX;
#define SO_MAX_RDMA_SIZE 0x700D
#define SO_RDMA_THRESHOLD_SIZE 0x700E
#define WSAID_REGISTERMEMORY \
{0xC0B422F5, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}}
#define WSAID_DEREGISTERMEMORY \
{0xC0B422F6, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}}
#define WSAID_REGISTERRDMAMEMORY \
{0xC0B422F7, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}}
#define WSAID_DEREGISTERRDMAMEMORY \
{0xC0B422F8, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}}
#define WSAID_RDMAWRITE \
{0xC0B422F9, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}}
#define WSAID_RDMAREAD \
{0xC0B422FA, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}}
#define WSAID_MEMORYREGISTRATIONCACHECALLBACK \
{0xE5DA4AF8, 0xD824, 0x48CD, {0xA7, 0x99, 0x63, 0x37, 0xA9, 0x8E, 0xD2, 0xAF}}
typedef struct _WSABUFEX {
u_long len;
char FAR *buf;
HANDLE handle;
} WSABUFEX, FAR * LPWSABUFEX;
#if 0
typedef struct _WSPUPCALLTABLEEX {
LPWPUCLOSEEVENT lpWPUCloseEvent;
LPWPUCLOSESOCKETHANDLE lpWPUCloseSocketHandle;
LPWPUCREATEEVENT lpWPUCreateEvent;
LPWPUCREATESOCKETHANDLE lpWPUCreateSocketHandle;
LPWPUFDISSET lpWPUFDIsSet;
LPWPUGETPROVIDERPATH lpWPUGetProviderPath;
LPWPUMODIFYIFSHANDLE lpWPUModifyIFSHandle;
LPWPUPOSTMESSAGE lpWPUPostMessage;
LPWPUQUERYBLOCKINGCALLBACK lpWPUQueryBlockingCallback;
LPWPUQUERYSOCKETHANDLECONTEXT lpWPUQuerySocketHandleContext;
LPWPUQUEUEAPC lpWPUQueueApc;
LPWPURESETEVENT lpWPUResetEvent;
LPWPUSETEVENT lpWPUSetEvent;
LPWPUOPENCURRENTTHREAD lpWPUOpenCurrentThread;
LPWPUCLOSETHREAD lpWPUCloseThread;
LPWPUCOMPLETEOVERLAPPEDREQUEST lpWPUCompleteOverlappedRequest;
} WSPUPCALLTABLEEX, FAR * LPWSPUPCALLTABLEEX;
#endif
int WSPAPI
WSPStartupEx(
IN WORD wVersionRequested,
OUT LPWSPDATA lpWSPData,
IN LPWSAPROTOCOL_INFOW lpProtocolInfo,
IN LPWSPUPCALLTABLEEX lpUpcallTable,
OUT LPWSPPROC_TABLE lpProcTable);
typedef int WSPAPI
(*LPWSPSTARTUPEX)(
IN WORD wVersionRequested,
OUT LPWSPDATA lpWSPData,
IN LPWSAPROTOCOL_INFOW lpProtocolInfo,
IN LPWSPUPCALLTABLEEX lpUpcallTable,
OUT LPWSPPROC_TABLE lpProcTable);
#define MEM_READ 1
#define MEM_WRITE 2
#define MEM_READWRITE 3
int WSPAPI
WSPDeregisterMemory(
IN SOCKET s,
IN HANDLE Handle,
OUT LPINT lpErrno);
typedef int WSPAPI
(*LPFN_WSPDEREGISTERMEMORY)(
IN SOCKET s,
IN HANDLE Handle,
OUT LPINT lpErrno);
int WSPAPI
WSPDeregisterRdmaMemory(
IN SOCKET s,
IN LPVOID lpRdmaBufferDescriptor,
IN DWORD dwDescriptorLength,
OUT LPINT lpErrno);
typedef int WSPAPI
(*LPFN_WSPDEREGISTERRDMAMEMORY)(
IN SOCKET s,
IN LPVOID lpRdmaBufferDescriptor,
IN DWORD dwDescriptorLength,
OUT LPINT lpErrno);
int WSPAPI
WSPMemoryRegistrationCacheCallback(
IN PVOID lpvAddress,
IN SIZE_T Size,
OUT LPINT lpErrno);
typedef int WSPAPI
(*LPFN_WSPMEMORYREGISTRATIONCACHECALLBACK)(
IN PVOID lpvAddress,
IN SIZE_T Size,
OUT LPINT lpErrno);
int WSPAPI
WSPRdmaRead(
IN SOCKET s,
IN LPWSABUFEX lpBuffers,
IN DWORD dwBufferCount,
IN LPVOID lpTargetBufferDescriptor,
IN DWORD dwTargetDescriptorLength,
IN DWORD dwTargetBufferOffset,
OUT LPDWORD lpdwNumberOfBytesRead,
IN DWORD dwFlags,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
IN LPWSATHREADID lpThreadId,
OUT LPINT lpErrno);
typedef int WSPAPI
(*LPFN_WSPRDMAREAD)(
IN SOCKET s,
IN LPWSABUFEX lpBuffers,
IN DWORD dwBufferCount,
IN LPVOID lpTargetBufferDescriptor,
IN DWORD dwTargetDescriptorLength,
IN DWORD dwTargetBufferOffset,
OUT LPDWORD lpdwNumberOfBytesRead,
IN DWORD dwFlags,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
IN LPWSATHREADID lpThreadId,
OUT LPINT lpErrno);
int WSPAPI
WSPRdmaWrite(
IN SOCKET s,
IN LPWSABUFEX lpBuffers,
IN DWORD dwBufferCount,
IN LPVOID lpTargetBufferDescriptor,
IN DWORD dwTargetDescriptorLength,
IN DWORD dwTargetBufferOffset,
OUT LPDWORD lpdwNumberOfBytesWritten,
IN DWORD dwFlags,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
IN LPWSATHREADID lpThreadId,
OUT LPINT lpErrno);
typedef int WSPAPI
(*LPFN_WSPRDMAWRITE)(
IN SOCKET s,
IN LPWSABUFEX lpBuffers,
IN DWORD dwBufferCount,
IN LPVOID lpTargetBufferDescriptor,
IN DWORD dwTargetDescriptorLength,
IN DWORD dwTargetBufferOffset,
OUT LPDWORD lpdwNumberOfBytesWritten,
IN DWORD dwFlags,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
IN LPWSATHREADID lpThreadId,
OUT LPINT lpErrno);
HANDLE WSPAPI
WSPRegisterMemory(
IN SOCKET s,
IN PVOID lpBuffer,
IN DWORD dwBufferLength,
IN DWORD dwFlags,
OUT LPINT lpErrno);
int WSPAPI
WSPRegisterRdmaMemory(
IN SOCKET s,
IN PVOID lpBuffer,
IN DWORD dwBufferLength,
IN DWORD dwFlags,
OUT LPVOID lpRdmaBufferDescriptor,
IN OUT LPDWORD lpdwDescriptorLength,
OUT LPINT lpErrno);
typedef int WSPAPI
(*LPFN_WSPREGISTERRDMAMEMORY)(
IN SOCKET s,
IN PVOID lpBuffer,
IN DWORD dwBufferLength,
IN DWORD dwFlags,
OUT LPVOID lpRdmaBufferDescriptor,
IN OUT LPDWORD lpdwDescriptorLength,
OUT LPINT lpErrno);
#pragma pack(pop)
#ifdef __cplusplus
}
#endif
#endif /* __WS2SAN_H */
| Java |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent.atomic;
/**
* An {@code AtomicMarkableReference} maintains an object reference
* along with a mark bit, that can be updated atomically.
*
* <p>Implementation note: This implementation maintains markable
* references by creating internal objects representing "boxed"
* [reference, boolean] pairs.
*
* @since 1.5
* @author Doug Lea
* @param <V> The type of object referred to by this reference
*/
public class AtomicMarkableReference<V> {
private static class Pair<T> {
final T reference;
final boolean mark;
private Pair(T reference, boolean mark) {
this.reference = reference;
this.mark = mark;
}
static <T> Pair<T> of(T reference, boolean mark) {
return new Pair<T>(reference, mark);
}
}
private volatile Pair<V> pair;
/**
* Creates a new {@code AtomicMarkableReference} with the given
* initial values.
*
* @param initialRef the initial reference
* @param initialMark the initial mark
*/
public AtomicMarkableReference(V initialRef, boolean initialMark) {
pair = Pair.of(initialRef, initialMark);
}
/**
* Returns the current value of the reference.
*
* @return the current value of the reference
*/
public V getReference() {
return pair.reference;
}
/**
* Returns the current value of the mark.
*
* @return the current value of the mark
*/
public boolean isMarked() {
return pair.mark;
}
/**
* Returns the current values of both the reference and the mark.
* Typical usage is {@code boolean[1] holder; ref = v.get(holder); }.
*
* @param markHolder an array of size of at least one. On return,
* {@code markholder[0]} will hold the value of the mark.
* @return the current value of the reference
*/
public V get(boolean[] markHolder) {
Pair<V> pair = this.pair;
markHolder[0] = pair.mark;
return pair.reference;
}
/**
* Atomically sets the value of both the reference and mark
* to the given update values if the
* current reference is {@code ==} to the expected reference
* and the current mark is equal to the expected mark.
*
* <p><a href="package-summary.html#weakCompareAndSet">May fail
* spuriously and does not provide ordering guarantees</a>, so is
* only rarely an appropriate alternative to {@code compareAndSet}.
*
* @param expectedReference the expected value of the reference
* @param newReference the new value for the reference
* @param expectedMark the expected value of the mark
* @param newMark the new value for the mark
* @return {@code true} if successful
*/
public boolean weakCompareAndSet(V expectedReference,
V newReference,
boolean expectedMark,
boolean newMark) {
return compareAndSet(expectedReference, newReference,
expectedMark, newMark);
}
/**
* Atomically sets the value of both the reference and mark
* to the given update values if the
* current reference is {@code ==} to the expected reference
* and the current mark is equal to the expected mark.
*
* @param expectedReference the expected value of the reference
* @param newReference the new value for the reference
* @param expectedMark the expected value of the mark
* @param newMark the new value for the mark
* @return {@code true} if successful
*/
public boolean compareAndSet(V expectedReference,
V newReference,
boolean expectedMark,
boolean newMark) {
Pair<V> current = pair;
return
expectedReference == current.reference &&
expectedMark == current.mark &&
((newReference == current.reference &&
newMark == current.mark) ||
casPair(current, Pair.of(newReference, newMark)));
}
/**
* Unconditionally sets the value of both the reference and mark.
*
* @param newReference the new value for the reference
* @param newMark the new value for the mark
*/
public void set(V newReference, boolean newMark) {
Pair<V> current = pair;
if (newReference != current.reference || newMark != current.mark)
this.pair = Pair.of(newReference, newMark);
}
/**
* Atomically sets the value of the mark to the given update value
* if the current reference is {@code ==} to the expected
* reference. Any given invocation of this operation may fail
* (return {@code false}) spuriously, but repeated invocation
* when the current value holds the expected value and no other
* thread is also attempting to set the value will eventually
* succeed.
*
* @param expectedReference the expected value of the reference
* @param newMark the new value for the mark
* @return {@code true} if successful
*/
public boolean attemptMark(V expectedReference, boolean newMark) {
Pair<V> current = pair;
return
expectedReference == current.reference &&
(newMark == current.mark ||
casPair(current, Pair.of(expectedReference, newMark)));
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
// private static final long pairOffset =
// objectFieldOffset(UNSAFE, "pair", AtomicMarkableReference.class);
private boolean casPair(Pair<V> cmp, Pair<V> val) {
return UNSAFE.compareAndSwapObject(this, pairOffset, cmp, val);
}
public static volatile long pairOffset;
static {
try {
pairOffset = 0;
UNSAFE.registerStaticFieldOffset(
AtomicMarkableReference.class.getDeclaredField("pairOffset"),
AtomicMarkableReference.class.getDeclaredField("pair"));
} catch (Exception ex) { throw new Error(ex); }
}
}
| Java |
(function ($) {
$(document).ready(function(){
$("#edit-title-0-value").change(update);
$("#edit-field-carac1-0-value").click(update);
$("#edit-field-carac1-0-value").change(update);
$("#edit-field-carac2-0-value").change(update);
$("#edit-field-carac3-0-value").change(update);
$("#edit-field-carac4-0-value").change(update);
$("#edit-field-skill-0-value").change(update);
$("#edit-field-question-0-value").change(update);
$("#edit-field-answer-0-value").change(update);
$("#edit-field-img-game-card-0-upload").change(update);
$("#edit-field-upload_image_verso").change(update);
var bgimagerecto = undefined;
var bgimageverso = undefined;
if($('span.file--image > a').length == 1) {
if($('#edit-field-img-game-card-0-remove-button')) {
console.log("length11");
bgimagerecto = $("span.file--image > a:eq(0)").attr('href');
}
else {
console.log("length12");
bgimageverso = $("span.file--image > a:eq(0)").attr('href');
}
}
if($('span.file--image > a').length == 2) {
console.log("length2");
bgimagerecto = $("span.file--image > a:eq(0)").attr('href');
bgimageverso = $("span.file--image > a:eq(1)").attr('href');
}
if (bgimagerecto !== undefined) {
console.log("imagerecto");
$('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')');
$('.field--name-field-img-game-card .ajax-new-content').addClass('processed');
}
if (bgimageverso !== undefined) {
console.log("imageverso");
$('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')');
$('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed');
}
$(document).ajaxComplete(function(event, xhr, settings) {
//RECTO
console.log(event.target);
console.log("azer " + bgimagerecto);
console.log("qsdf " + bgimageverso);
if(~settings.url.indexOf("field_img_game_card")) {
console.log('entering recto');
if ($('.field--name-field-img-game-card .ajax-new-content').hasClass('processed')) {
console.log("remove recto");
//$('.ajax-new-content').remove();
$('#gamecardrectolayout').removeAttr('style');
$('.field--name-field-img-game-card .ajax-new-content').removeClass('processed');
return;
}
if(!$('#edit-field-img-game-card-0-remove-button')) {
console.log("remoooooove");
$('#gamecardrectolayout').removeAttr('style');
$('.field--name-field-img-game-card .ajax-new-content').removeClass('processed');
return;
}
console.log("addingrecto");
$('.field--name-field-img-game-card .ajax-new-content').addClass('processed');
bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); //Manage here when single or double
if (bgimagerecto !== undefined) {
console.log("gorecto");
$('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')');
}
return;
}
//VERSO
if(~settings.url.indexOf("field_upload_image_verso")) {
if ($('.field--name-field-upload-image-verso .ajax-new-content').hasClass('processed') || !$('#edit-field-upload-image-verso-0-remove-button')) {
console.log("remove verso");
//$('.ajax-new-content').remove();
$('#gamecardversolayout').removeAttr('style');
$('.field--name-field-upload-image-verso .ajax-new-content').removeClass('processed');
return;
}
console.log("adding verso");
$('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed');
if($('span.file--image > a').length == 1) bgimageverso = $("span.file--image > a:eq(0)").attr('href');
if($('span.file--image > a').length == 2) bgimageverso = $("span.file--image > a:eq(1)").attr('href');
if (bgimageverso !== undefined) {
console.log("Verso added");
$('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')');
}
}
});
});
function update(){
var cardname = (($("#edit-title-0-value").val() != "") ? $("#edit-title-0-value").val() : "");
var carac1 = (($("#edit-field-carac1-0-value").val() != "") ? $("#edit-field-carac1-0-value").val() : "");
var carac2 = (($("#edit-field-carac2-0-value").val() != "") ? $("#edit-field-carac2-0-value").val() : "");
var carac3 = (($("#edit-field-carac3-0-value").val() != "") ? $("#edit-field-carac3-0-value").val() : "");
var carac4 = (($("#edit-field-carac4-0-value").val() != "") ? $("#edit-field-carac4-0-value").val() : "");
var skill = (($("#edit-field-skill-0-value").val() != "") ? $("#edit-field-skill-0-value").val() : "") ;
var question = (($("#edit-field-question-0-value").val() != "") ? $("#edit-field-question-0-value").val() : "");
var answer = (($("#edit-field-answer-0-value").val() != "") ? $("#edit-field-answer-0-value").val() : "") ;
var rectoImg = (($("#edit-field-img-game-card-0-upload").val() != "") ? $("#edit-field-img-game-card-0-upload").val() : "");
var versoImg = (($("#edit-field-upload_image_verso").val() != "") ? $("#edit-field-upload_image_verso").val() : "");
if(rectoImg !== undefined) {
if (rectoImg != null) {
$('#gamecardrectolayout').css('background-image', 'url("' + rectoImg + '")');
}
else {
rectoImg = $("span.file--image > a:eq(0)").attr('href');
$('#gamecardrectolayout').css('background-image', 'url( ' + rectoImg + ')');
}
}
if(versoImg !== undefined) {
if (versoImg != null) {
$('#gamecardrectolayout').css('background-image', 'url("' + versoImg + '")');
}
else {
versoImg = $("span.file--image > a:eq(1)").attr('href');
$('#gamecardrectolayout').css('background-image', 'url( ' + versoImg + ')');
}
}
$('#displayCardname').html(cardname);
$('#displayCarac1').html(carac1);
$('#displayCarac2').html(carac2);
$('#displayCarac3').html(carac3);
$('#displayCarac4').html(carac4);
$('#displaySkill').html(skill);
$('#displayQuestion').html(question);
$('#displayAnswer').html(answer);
}
})(jQuery);
| Java |
<?php
/**
* @package WordPress
* @subpackage HTML5-Reset-WordPress-Theme
* @since HTML5 Reset 2.0
Template Name: Groups
*/
get_header(); ?>
<div class="content-background">
<div id="content-wrap">
<div class="grid">
<div class="col col-1-4">
<?php wp_nav_menu( array('menu' => 'Groups Menu', 'container_class' => 'side-menu-container', 'menu_class' => 'side-menu' )); ?>
<div class="fb-like-box" data-href="https://www.facebook.com/skisnowstar" data-width="200" data-height="300" data-colorscheme="light" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"></div>
<a href="https://twitter.com/SkiSnowstar" class="twitter-follow-button" data-width="90%" data-align="right" data-show-count="false" data-lang="en" data-size="large">Follow @twitter</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</div><!-- END COL-1-4 -->
<div class="col col-3-4">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article class="post" id="post-<?php the_ID(); ?>">
<!-- <h2><?php the_title(); ?></h2> -->
<!-- <?php posted_on(); ?> -->
<?php if ( has_post_thumbnail() ) {the_post_thumbnail('full', array('class' => 'content-img'));} ?>
<div class="entry">
<?php the_content(); ?>
<?php wp_link_pages(array('before' => __('Pages: '), 'next_or_number' => 'number')); ?>
</div>
<?php edit_post_link(__('Edit this entry.'), '<p>', '</p>'); ?>
</article>
<?php endwhile; endif; ?>
</div><!-- END COL-3-4 -->
</div><!-- END GRID -->
</div> <!-- End Content Wrap -->
<?php get_footer(); ?>
| Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Caixa.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Caixa.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| Java |
/*
* Copyright (C) 2019 Paul Davis <paul@linuxaudiosystems.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _ardour_transport_api_h_
#define _ardour_transport_api_h_
#include "ardour/types.h"
#include "ardour/libardour_visibility.h"
namespace ARDOUR
{
class LIBARDOUR_API TransportAPI
{
public:
TransportAPI() {}
virtual ~TransportAPI() {}
private:
friend struct TransportFSM;
virtual void locate (samplepos_t, bool with_roll, bool with_flush, bool with_loop=false, bool force=false, bool with_mmc=true) = 0;
virtual void stop_transport (bool abort = false, bool clear_state = false) = 0;
virtual void start_transport () = 0;
virtual void butler_completed_transport_work () = 0;
virtual void schedule_butler_for_transport_work () = 0;
virtual bool should_roll_after_locate () const = 0;
virtual double speed() const = 0;
virtual void set_transport_speed (double speed, bool abort_capture, bool clear_state, bool as_default) = 0;
virtual samplepos_t position() const = 0;
virtual bool need_declick_before_locate () const = 0;
};
} /* end namespace ARDOUR */
#endif
| Java |
/*
* Copyright (C) 2015-2016 FixCore <FixCore Develops>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_GAMEOBJECTAI_H
#define TRINITY_GAMEOBJECTAI_H
#include "Define.h"
#include <list>
#include "Object.h"
#include "GameObject.h"
#include "CreatureAI.h"
class GameObjectAI
{
protected:
GameObject* const go;
public:
explicit GameObjectAI(GameObject* g) : go(g) {}
virtual ~GameObjectAI() {}
virtual void UpdateAI(uint32 /*diff*/) {}
virtual void InitializeAI() { Reset(); }
virtual void Reset() { }
// Pass parameters between AI
virtual void DoAction(const int32 /*param = 0 */) {}
virtual void SetGUID(uint64 /*guid*/, int32 /*id = 0 */) {}
virtual uint64 GetGUID(int32 /*id = 0 */) const { return 0; }
static int Permissible(GameObject const* go);
virtual bool GossipHello(Player* /*player*/) { return false; }
virtual bool GossipSelect(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/) { return false; }
virtual bool GossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, char const* /*code*/) { return false; }
virtual bool QuestAccept(Player* /*player*/, Quest const* /*quest*/) { return false; }
virtual bool QuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; }
virtual uint32 GetDialogStatus(Player* /*player*/) { return 100; }
virtual void Destroyed(Player* /*player*/, uint32 /*eventId*/) {}
virtual uint32 GetData(uint32 /*id*/) const { return 0; }
virtual void SetData64(uint32 /*id*/, uint64 /*value*/) {}
virtual uint64 GetData64(uint32 /*id*/) const { return 0; }
virtual void SetData(uint32 /*id*/, uint32 /*value*/) {}
virtual void OnGameEvent(bool /*start*/, uint16 /*eventId*/) {}
virtual void OnStateChanged(uint32 /*state*/, Unit* /*unit*/) {}
virtual void EventInform(uint32 /*eventId*/) {}
};
class NullGameObjectAI : public GameObjectAI
{
public:
explicit NullGameObjectAI(GameObject* g);
void UpdateAI(uint32 /*diff*/) {}
static int Permissible(GameObject const* /*go*/) { return PERMIT_BASE_IDLE; }
};
#endif
| Java |
/****************************************************************************
**
** This file is part of the Qtopia Opensource Edition Package.
**
** Copyright (C) 2008 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** versions 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#ifndef BROWSER_H
#define BROWSER_H
#include <QList>
#include <QMailAddress>
#include <QMap>
#include <QString>
#include <QTextBrowser>
#include <QUrl>
#include <QVariant>
class QWidget;
class QMailMessage;
class QMailMessagePart;
class Browser: public QTextBrowser
{
Q_OBJECT
public:
Browser(QWidget *parent = 0);
virtual ~Browser();
void setResource( const QUrl& name, QVariant var );
void clearResources();
void setMessage( const QMailMessage& mail, bool plainTextMode );
void scrollBy(int dx, int dy);
virtual QVariant loadResource(int type, const QUrl& name);
QList<QString> embeddedNumbers() const;
signals:
void finished();
public slots:
virtual void setSource(const QUrl &name);
protected:
void keyPressEvent(QKeyEvent* event);
private:
void displayPlainText(const QMailMessage* mail);
void displayHtml(const QMailMessage* mail);
void setTextResource(const QUrl& name, const QString& textData);
void setImageResource(const QUrl& name, const QByteArray& imageData);
void setPartResource(const QMailMessagePart& part);
QString renderPart(const QMailMessagePart& part);
QString renderAttachment(const QMailMessagePart& part);
QString describeMailSize(uint bytes) const;
QString formatText(const QString& txt) const;
QString smsBreakReplies(const QString& txt) const;
QString noBreakReplies(const QString& txt) const;
QString handleReplies(const QString& txt) const;
QString buildParagraph(const QString& txt, const QString& prepend, bool preserveWs = false) const;
QString encodeUrlAndMail(const QString& txt) const;
QString listRefMailTo(const QList<QMailAddress>& list) const;
QString refMailTo(const QMailAddress& address) const;
QString refNumber(const QString& number) const;
QMap<QUrl, QVariant> resourceMap;
QString (Browser::*replySplitter)(const QString&) const;
mutable QList<QString> numbers;
};
#endif // BROWSER_H
| Java |
/*
* Turbo Sliders++
* Copyright (C) 2013-2014 Martin Newhouse
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
#ifndef TRACK_METADATA_HPP
#define TRACK_METADATA_HPP
#include "track_identifier.hpp"
namespace ts
{
namespace resources
{
class Track_handle;
struct Track_metadata
{
Track_identifier identifier;
utf8_string gamemode;
};
Track_metadata load_track_metadata(const resources::Track_handle& track_handle);
}
}
#endif | Java |
package edu.stanford.nlp.time;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Map;
import java.util.regex.Pattern;
import edu.stanford.nlp.util.Pair;
import org.w3c.dom.Element;
/**
* Stores one TIMEX3 expression. This class is used for both TimeAnnotator and
* GUTimeAnnotator for storing information for TIMEX3 tags.
*
* <p>
* Example text with TIMEX3 annotation:<br>
* <code>In Washington <TIMEX3 tid="t1" TYPE="DATE" VAL="PRESENT_REF"
* temporalFunction="true" valueFromFunction="tf1"
* anchorTimeID="t0">today</TIMEX3>, the Federal Aviation Administration
* released air traffic control tapes from the night the TWA Flight eight
* hundred went down.
* </code>
* <p>
* <br>
* TIMEX3 specification:
* <br>
* <pre><code>
* attributes ::= tid type [functionInDocument] [beginPoint] [endPoint]
* [quant] [freq] [temporalFunction] (value | valueFromFunction)
* [mod] [anchorTimeID] [comment]
*
* tid ::= ID
* {tid ::= TimeID
* TimeID ::= t<integer>}
* type ::= 'DATE' | 'TIME' | 'DURATION' | 'SET'
* beginPoint ::= IDREF
* {beginPoint ::= TimeID}
* endPoint ::= IDREF
* {endPoint ::= TimeID}
* quant ::= CDATA
* freq ::= Duration
* functionInDocument ::= 'CREATION_TIME' | 'EXPIRATION_TIME' | 'MODIFICATION_TIME' |
* 'PUBLICATION_TIME' | 'RELEASE_TIME'| 'RECEPTION_TIME' |
* 'NONE' {default, if absent, is 'NONE'}
* temporalFunction ::= 'true' | 'false' {default, if absent, is 'false'}
* {temporalFunction ::= boolean}
* value ::= Duration | Date | Time | WeekDate | WeekTime | Season | PartOfYear | PaPrFu
* valueFromFunction ::= IDREF
* {valueFromFunction ::= TemporalFunctionID
* TemporalFunctionID ::= tf<integer>}
* mod ::= 'BEFORE' | 'AFTER' | 'ON_OR_BEFORE' | 'ON_OR_AFTER' |'LESS_THAN' | 'MORE_THAN' |
* 'EQUAL_OR_LESS' | 'EQUAL_OR_MORE' | 'START' | 'MID' | 'END' | 'APPROX'
* anchorTimeID ::= IDREF
* {anchorTimeID ::= TimeID}
* comment ::= CDATA
* </code></pre>
*
* <p>
* References
* <br>
* Guidelines: <a href="http://www.timeml.org/tempeval2/tempeval2-trial/guidelines/timex3guidelines-072009.pdf">
* http://www.timeml.org/tempeval2/tempeval2-trial/guidelines/timex3guidelines-072009.pdf</a>
* <br>
* Specifications: <a href="http://www.timeml.org/site/publications/timeMLdocs/timeml_1.2.1.html#timex3">
* http://www.timeml.org/site/publications/timeMLdocs/timeml_1.2.1.html#timex3</a>
* <br>
* XSD: <a href="http://www.timeml.org/timeMLdocs/TimeML.xsd">http://www.timeml.org/timeMLdocs/TimeML.xsd</a>
**/
public class Timex implements Serializable {
private static final long serialVersionUID = 385847729549981302L;
/**
* XML representation of the TIMEX tag
*/
private String xml;
/**
* TIMEX3 value attribute - Time value (given in extended ISO 8601 format).
*/
private String val;
/**
* Alternate representation for time value (not part of TIMEX3 standard).
* used when value of the time expression cannot be expressed as a standard TIMEX3 value.
*/
private String altVal;
/**
* Actual text that make up the time expression
*/
private String text;
/**
* TIMEX3 type attribute - Type of the time expression (DATE, TIME, DURATION, or SET)
*/
private String type;
/**
* TIMEX3 tid attribute - TimeID. ID to identify this time expression.
* Should have the format of {@code t<integer>}
*/
private String tid;
// TODO: maybe its easier if these are just strings...
/**
* TIMEX3 beginPoint attribute - integer indicating the TimeID of the begin time
* that anchors this duration/range (-1 is not present).
*/
private int beginPoint;
/**
* TIMEX3 beginPoint attribute - integer indicating the TimeID of the end time
* that anchors this duration/range (-1 is not present).
*/
private int endPoint;
/**
* Range begin/end/duration
* (this is not part of the timex standard and is typically null, available if sutime.includeRange is true)
*/
private Range range;
public static class Range implements Serializable {
private static final long serialVersionUID = 1L;
public String begin;
public String end;
public String duration;
public Range(String begin, String end, String duration) {
this.begin = begin;
this.end = end;
this.duration = duration;
}
}
public String value() {
return val;
}
public String altVal() {
return altVal;
}
public String text() {
return text;
}
public String timexType() {
return type;
}
public String tid() {
return tid;
}
public Range range() {
return range;
}
public Timex() {
}
public Timex(Element element) {
this.val = null;
this.beginPoint = -1;
this.endPoint = -1;
/*
* ByteArrayOutputStream os = new ByteArrayOutputStream(); Serializer ser =
* new Serializer(os, "UTF-8"); ser.setIndent(2); // this is the default in
* JDOM so let's keep the same ser.setMaxLength(0); // no line wrapping for
* content ser.write(new Document(element));
*/
init(element);
}
public Timex(String val) {
this(null, val);
}
public Timex(String type, String val) {
this.val = val;
this.type = type;
this.beginPoint = -1;
this.endPoint = -1;
this.xml = (val == null ? "<TIMEX3/>" : String.format("<TIMEX3 VAL=\"%s\" TYPE=\"%s\"/>", this.val, this.type));
}
public Timex(String type, String val, String altVal, String tid, String text, int beginPoint, int endPoint) {
this.type = type;
this.val = val;
this.altVal = altVal;
this.tid = tid;
this.text = text;
this.beginPoint = beginPoint;
this.endPoint = endPoint;
}
private void init(Element element) {
init(XMLUtils.nodeToString(element, false), element);
}
private void init(String xml, Element element) {
this.xml = xml;
this.text = element.getTextContent();
// Mandatory attributes
this.tid = XMLUtils.getAttribute(element, "tid");
this.val = XMLUtils.getAttribute(element, "VAL");
if (this.val == null) {
this.val = XMLUtils.getAttribute(element, "value");
}
this.altVal = XMLUtils.getAttribute(element, "alt_value");
this.type = XMLUtils.getAttribute(element, "type");
if (type == null) {
this.type = XMLUtils.getAttribute(element, "TYPE");
}
// if (this.type != null) {
// this.type = this.type.intern();
// }
// Optional attributes
String beginPoint = XMLUtils.getAttribute(element, "beginPoint");
this.beginPoint = (beginPoint == null || beginPoint.length() == 0)? -1 : Integer.parseInt(beginPoint.substring(1));
String endPoint = XMLUtils.getAttribute(element, "endPoint");
this.endPoint = (endPoint == null || endPoint.length() == 0)? -1 : Integer.parseInt(endPoint.substring(1));
// Optional range
String rangeStr = XMLUtils.getAttribute(element, "range");
if (rangeStr != null) {
if (rangeStr.startsWith("(") && rangeStr.endsWith(")")) {
rangeStr = rangeStr.substring(1, rangeStr.length()-1);
}
String[] parts = rangeStr.split(",");
this.range = new Range(parts.length > 0? parts[0]:"", parts.length > 1? parts[1]:"", parts.length > 2? parts[2]:"");
}
}
public int beginPoint() { return beginPoint; }
public int endPoint() { return endPoint; }
public String toString() {
return (this.xml != null) ? this.xml : this.val;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Timex timex = (Timex) o;
if (beginPoint != timex.beginPoint) {
return false;
}
if (endPoint != timex.endPoint) {
return false;
}
if (type != null ? !type.equals(timex.type) : timex.type != null) {
return false;
}
if (val != null ? !val.equals(timex.val) : timex.val != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = val != null ? val.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + beginPoint;
result = 31 * result + endPoint;
return result;
}
public Element toXmlElement() {
Element element = XMLUtils.createElement("TIMEX3");
if (tid != null) {
element.setAttribute("tid", tid);
}
if (value() != null) {
element.setAttribute("value", val);
}
if (altVal != null) {
element.setAttribute("altVal", altVal);
}
if (type != null) {
element.setAttribute("type", type);
}
if (beginPoint != -1) {
element.setAttribute("beginPoint", "t" + String.valueOf(beginPoint));
}
if (endPoint != -1) {
element.setAttribute("endPoint", "t" + String.valueOf(endPoint));
}
if (text != null) {
element.setTextContent(text);
}
return element;
}
// Used to create timex from XML (mainly for testing)
public static Timex fromXml(String xml) {
Element element = XMLUtils.parseElement(xml);
if ("TIMEX3".equals(element.getNodeName())) {
Timex t = new Timex();
// t.init(xml, element);
// Doesn't preserve original input xml
// Will reorder attributes of xml so can match xml of test timex and actual timex
// (for which we can't control the order of the attributes now we don't use nu.xom...)
t.init(element);
return t;
} else {
throw new IllegalArgumentException("Invalid timex xml: " + xml);
}
}
public static Timex fromMap(String text, Map<String, String> map) {
try {
Element element = XMLUtils.createElement("TIMEX3");
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue() != null) {
element.setAttribute(entry.getKey(), entry.getValue());
}
}
element.setTextContent(text);
return new Timex(element);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Gets the Calendar matching the year, month and day of this Timex.
*
* @return The matching Calendar.
*/
public Calendar getDate() {
if (Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(5, 7));
int day = Integer.parseInt(this.val.substring(8, 10));
return makeCalendar(year, month, day);
} else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
int day = Integer.parseInt(this.val.substring(6, 8));
return makeCalendar(year, month, day);
}
throw new UnsupportedOperationException(String.format("%s is not a fully specified date", this));
}
/**
* Gets two Calendars, marking the beginning and ending of this Timex's range.
*
* @return The begin point and end point Calendars.
*/
public Pair<Calendar, Calendar> getRange() {
return this.getRange(null);
}
/**
* Gets two Calendars, marking the beginning and ending of this Timex's range.
*
* @param documentTime
* The time the document containing this Timex was written. (Not
* necessary for resolving all Timex expressions. This may be
* {@code null}, but then relative time expressions cannot be
* resolved.)
* @return The begin point and end point Calendars.
*/
public Pair<Calendar, Calendar> getRange(Timex documentTime) {
if (this.val == null) {
throw new UnsupportedOperationException("no value specified for " + this);
}
// YYYYMMDD or YYYYMMDDT... where the time is concatenated directly with the
// date
else if (val.length() >= 8 && Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val.substring(0, 8))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
int day = Integer.parseInt(this.val.substring(6, 8));
return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day));
}
// YYYY-MM-DD or YYYY-MM-DDT...
else if (val.length() >= 10 && Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val.substring(0, 10))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(5, 7));
int day = Integer.parseInt(this.val.substring(8, 10));
return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day));
}
// YYYYMMDDL+
else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d[A-Z]+", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
int day = Integer.parseInt(this.val.substring(6, 8));
return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day));
}
// YYYYMM or YYYYMMT...
else if (val.length() >= 6 && Pattern.matches("\\d\\d\\d\\d\\d\\d", this.val.substring(0, 6))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(4, 6));
Calendar begin = makeCalendar(year, month, 1);
int lastDay = begin.getActualMaximum(Calendar.DATE);
Calendar end = makeCalendar(year, month, lastDay);
return new Pair<>(begin, end);
}
// YYYY-MM or YYYY-MMT...
else if (val.length() >= 7 && Pattern.matches("\\d\\d\\d\\d-\\d\\d", this.val.substring(0, 7))) {
int year = Integer.parseInt(this.val.substring(0, 4));
int month = Integer.parseInt(this.val.substring(5, 7));
Calendar begin = makeCalendar(year, month, 1);
int lastDay = begin.getActualMaximum(Calendar.DATE);
Calendar end = makeCalendar(year, month, lastDay);
return new Pair<>(begin, end);
}
// YYYY or YYYYT...
else if (val.length() >= 4 && Pattern.matches("\\d\\d\\d\\d", this.val.substring(0, 4))) {
int year = Integer.parseInt(this.val.substring(0, 4));
return new Pair<>(makeCalendar(year, 1, 1), makeCalendar(year, 12, 31));
}
// PDDY
if (Pattern.matches("P\\d+Y", this.val) && documentTime != null) {
Calendar rc = documentTime.getDate();
int yearRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1));
// in the future
if (this.beginPoint < this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
end.add(Calendar.YEAR, yearRange);
return new Pair<>(start, end);
}
// in the past
else if (this.beginPoint > this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
start.add(Calendar.YEAR, 0 - yearRange);
return new Pair<>(start, end);
}
throw new RuntimeException("begin and end are equal " + this);
}
// PDDM
if (Pattern.matches("P\\d+M", this.val) && documentTime != null) {
Calendar rc = documentTime.getDate();
int monthRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1));
// in the future
if (this.beginPoint < this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
end.add(Calendar.MONTH, monthRange);
return new Pair<>(start, end);
}
// in the past
if (this.beginPoint > this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
start.add(Calendar.MONTH, 0 - monthRange);
return new Pair<>(start, end);
}
throw new RuntimeException("begin and end are equal " + this);
}
// PDDD
if (Pattern.matches("P\\d+D", this.val) && documentTime != null) {
Calendar rc = documentTime.getDate();
int dayRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1));
// in the future
if (this.beginPoint < this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
end.add(Calendar.DAY_OF_MONTH, dayRange);
return new Pair<>(start, end);
}
// in the past
if (this.beginPoint > this.endPoint) {
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
start.add(Calendar.DAY_OF_MONTH, 0 - dayRange);
return new Pair<>(start, end);
}
throw new RuntimeException("begin and end are equal " + this);
}
// YYYYSP
if (Pattern.matches("\\d+SP", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 2, 1);
Calendar end = makeCalendar(year, 4, 31);
return new Pair<>(start, end);
}
// YYYYSU
if (Pattern.matches("\\d+SU", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 5, 1);
Calendar end = makeCalendar(year, 7, 31);
return new Pair<>(start, end);
}
// YYYYFA
if (Pattern.matches("\\d+FA", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 8, 1);
Calendar end = makeCalendar(year, 10, 31);
return new Pair<>(start, end);
}
// YYYYWI
if (Pattern.matches("\\d+WI", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
Calendar start = makeCalendar(year, 11, 1);
Calendar end = makeCalendar(year + 1, 1, 29);
return new Pair<>(start, end);
}
// YYYYWDD
if (Pattern.matches("\\d\\d\\d\\dW\\d+", this.val)) {
int year = Integer.parseInt(this.val.substring(0, 4));
int week = Integer.parseInt(this.val.substring(5));
int startDay = (week - 1) * 7;
int endDay = startDay + 6;
Calendar start = makeCalendar(year, startDay);
Calendar end = makeCalendar(year, endDay);
return new Pair<>(start, end);
}
// PRESENT_REF
if (this.val.equals("PRESENT_REF")) {
Calendar rc = documentTime.getDate(); // todo: This case doesn't check for documentTime being null and will NPE
Calendar start = copyCalendar(rc);
Calendar end = copyCalendar(rc);
return new Pair<>(start, end);
}
throw new RuntimeException(String.format("unknown value \"%s\" in %s", this.val, this));
}
private static Calendar makeCalendar(int year, int month, int day) {
Calendar date = Calendar.getInstance();
date.clear();
date.set(year, month - 1, day, 0, 0, 0);
return date;
}
private static Calendar makeCalendar(int year, int dayOfYear) {
Calendar date = Calendar.getInstance();
date.clear();
date.set(Calendar.YEAR, year);
date.set(Calendar.DAY_OF_YEAR, dayOfYear);
return date;
}
private static Calendar copyCalendar(Calendar c) {
Calendar date = Calendar.getInstance();
date.clear();
date.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c
.get(Calendar.MINUTE), c.get(Calendar.SECOND));
return date;
}
}
| Java |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* This file is part of guh. *
* *
* Guh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, version 2 of the License. *
* *
* Guh is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with guh. If not, see <http://www.gnu.org/licenses/>. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*!
\page openweathermap.html
\title Open Weather Map
\ingroup plugins
\ingroup services
This plugin alows you to get the current weather data from \l{http://www.openweathermap.org}.
The plugin offers two different search methods: if the user searches for a empty string,
the plugin makes an autodetction with the WAN ip and offers the user the found autodetectresult.
Otherwise the plugin return the list with the found searchresults.
\section1 Examples
\section2 Autodetect location
If you want to autodetect your location dend a discovery request with an empty string.
\code
{
"id":1,
"method":"Devices.GetDiscoveredDevices",
"params":{
"deviceClassId":"985195aa-17ad-4530-88a4-cdd753d747d7",
"discoveryParams": {
"location":""
}
}
}
\endcode
response from autodetection...
\code
{
"id": 1,
"params": {
"deviceDescriptors": [
{
"description": "AT",
"id": "{75607672-5354-428f-a752-910140c22b18}",
"title": "Vienna"
}
],
"errorMessage": "",
"success": true
},
"status": "success"
}
\endcode
\section2 Searching city
If you want to search a string send following discovery message:
\code
{
"id":1,
"method":"Devices.GetDiscoveredDevices",
"params":{
"deviceClassId":"985195aa-17ad-4530-88a4-cdd753d747d7",
"discoveryParams": {
"location":"Vie"
}
}
}
\endcode
response...
\code
{
"id": 1,
"params": {
"deviceDescriptors": [
{
"description": "DE",
"id": "{6dc6be43-5bdc-4dbd-bcbf-6f8e1f90000b}",
"title": "Viersen"
},
{
"description": "VN",
"id": "{af275298-77f1-40b4-843a-d0f3c7aef6bb}",
"title": "Viet Tri"
},
{
"description": "DE",
"id": "{86a4ab63-41b4-4348-9830-4bf6c87474bf}",
"title": "Viernheim"
},
{
"description": "AR",
"id": "{3b5f8eea-6159-4375-bd01-1f07de9c3a9d}",
"title": "Viedma"
},
{
"description": "FR",
"id": "{f3b91f26-3275-4bb4-a594-924202a2124e}",
"title": "Vierzon"
},
{
"description": "AT",
"id": "{b59d15f7-f52b-43a0-a9c5-a3fa80cbc2bd}",
"title": "Vienna"
}
],
"errorMessage": "",
"success": true
},
"status": "success"
}
\endcode
\section2 Adding a discovered city
If you want to add a dicovered city send the add "AddConfiguredDevice" message
with the deviceDescriptorId from the searchresult list. In this example the id for Vienna.
\code
{
"id":1,
"method":"Devices.AddConfiguredDevice",
"params":{
"deviceClassId":"985195aa-17ad-4530-88a4-cdd753d747d7",
"deviceDescriptorId": "b59d15f7-f52b-43a0-a9c5-a3fa80cbc2bd"
}
}
\endcode
response...
\code
{
"id": 1,
"params": {
"deviceId": "{af0f1958-b901-48da-ad97-d4d64af88cf8}",
"errorMessage": "",
"success": true
},
"status": "success"
}
\endcode
\section1 Plugin propertys:
\section2 Plugin parameters
Each configured plugin has following paramters:
\table
\header
\li Name
\li Description
\li Data Type
\row
\li location
\li This parameter holds the name of the city
\li string
\row
\li country
\li This parameter holds the country of the city
\li string
\row
\li id
\li This parameter holds the city id from \l{http://www.openweathermap.org}
\li string
\endtable
\section2 Actions
Following list contains all plugin \l{Action}s:
\table
\header
\li Name
\li Description
\li UUID
\row
\li refresh
\li This action refreshes all states.
\li cfbc6504-d86f-4856-8dfa-97b6fbb385e4
\endtable
\section2 States
Following list contains all plugin \l{State}s:
\table
\header
\li Name
\li Description
\li UUID
\li Data Type
\row
\li city name
\li The name of the city
\li fd9e7b7f-cf1f-4093-8f6d-fff5b223471f
\li string
\row
\li city id
\li The city ID for openweathermap.org
\li c6ef1c07-e817-4251-b83d-115bbf6f0ae9
\li string
\row
\li country name
\li The country name
\li 0e607a5f-1938-4e77-a146-15e9ad15bfad
\li string
\row
\li last update
\li The timestamp of the weather data from the weatherstation in unixtime
format
\li 98e48095-87da-47a4-b812-28c6c17a3e76
\li unsignend int
\row
\li temperature
\li Current temperature [Celsius]
\li 2f949fa3-ff21-4721-87ec-0a5c9d0a5b8a
\li double
\row
\li temperature minimum
\li Today temperature minimum [Clesius]
\li 701338b3-80de-4c95-8abf-26f44529d620
\li double
\row
\li temperature maximum
\li Today temperature maximum [Clesius]
\li f69bedd2-c997-4a7d-9242-76bf2aab3d3d
\li double
\row
\li humidity
\li Current relative humidity [%]
\li 3f01c9f0-206b-4477-afa2-80d6e5e54fbb
\li int
\row
\li pressure
\li Current pressure [hPa]
\li 6a57b6e9-7010-4a89-982c-ce0bc2a71f11
\li double
\row
\li wind speed
\li Current wind speed [m/s]
\li 12dc85a9-825d-4375-bef4-abd66e9e301b
\li double
\row
\li wind direction
\li The wind direction rellative to the north pole [degree]
\li a8b0383c-d615-41fe-82b8-9b797f045cc9
\li int
\row
\li cloudiness
\li This value represents how much of the sky is clowdy [%]
\li 0c1dc881-560e-40ac-a4a1-9ab69138cfe3
\li int
\row
\li weather description
\li This string describes the current weather condition in clear words
\li e71d98e3-ebd8-4abf-ad25-9ecc2d05276a
\li string
\row
\li sunset
\li The time of todays sunset in unixtime format
\li 5dd6f5a3-25d6-4e60-82ca-e934ad76a4b6
\li unsigned int
\row
\li sunrise
\li The time of todays sunrise in unixtime format
\li 413b3fc6-bd1c-46fb-8c86-03096254f94f
\li unsigned int
\endtable
*/
#include "devicepluginopenweathermap.h"
#include "plugin/device.h"
#include "devicemanager.h"
#include <QDebug>
#include <QJsonDocument>
#include <QVariantMap>
#include <QDateTime>
DeviceClassId openweathermapDeviceClassId = DeviceClassId("985195aa-17ad-4530-88a4-cdd753d747d7");
ActionTypeId updateWeatherActionTypeId = ActionTypeId("cfbc6504-d86f-4856-8dfa-97b6fbb385e4");
StateTypeId updateTimeStateTypeId = StateTypeId("36b2f09b-7d77-4fbc-a68f-23d735dda0b1");
StateTypeId temperatureStateTypeId = StateTypeId("6013402f-b5b1-46b3-8490-f0c20d62fe61");
StateTypeId temperatureMinStateTypeId = StateTypeId("14ec2781-cb04-4bbf-b097-7d01ef982630");
StateTypeId temperatureMaxStateTypeId = StateTypeId("fefe5563-452f-4833-b5cf-49c3cc67c772");
StateTypeId humidityStateTypeId = StateTypeId("6f32ec73-3240-4630-ada9-1c10b8e98123");
StateTypeId pressureStateTypeId = StateTypeId("4a42eea9-00eb-440b-915e-dbe42180f83b");
StateTypeId windSpeedStateTypeId = StateTypeId("2bf63430-e9e2-4fbf-88e6-6f1b4770f287");
StateTypeId windDirectionStateTypeId = StateTypeId("589e2ea5-65b2-4afd-9b72-e3708a589a12");
StateTypeId cloudinessStateTypeId = StateTypeId("798553bc-45c7-42eb-9105-430bddb5d9b7");
StateTypeId weatherDescriptionStateTypeId = StateTypeId("f9539108-0e0e-4736-a306-6408f8e20a26");
StateTypeId sunriseStateTypeId = StateTypeId("af155e94-9492-44e1-8608-7d0ee8b5d50d");
StateTypeId sunsetStateTypeId = StateTypeId("a1dddc3d-549f-4f20-b78b-be850548f286");
DevicePluginOpenweathermap::DevicePluginOpenweathermap()
{
m_openweaher = new OpenWeatherMap(this);
connect(m_openweaher, &OpenWeatherMap::searchResultReady, this, &DevicePluginOpenweathermap::searchResultsReady);
connect(m_openweaher, &OpenWeatherMap::weatherDataReady, this, &DevicePluginOpenweathermap::weatherDataReady);
}
DeviceManager::DeviceError DevicePluginOpenweathermap::discoverDevices(const DeviceClassId &deviceClassId, const ParamList ¶ms)
{
if(deviceClassId != openweathermapDeviceClassId){
return DeviceManager::DeviceErrorDeviceClassNotFound;
}
QString location;
foreach (const Param ¶m, params) {
if (param.name() == "location") {
location = param.value().toString();
}
}
// if we have an empty search string, perform an autodetection of the location with the WAN ip...
if (location.isEmpty()){
m_openweaher->searchAutodetect();
} else {
m_openweaher->search(location);
}
// otherwise search the given string
m_openweaher->search(location);
return DeviceManager::DeviceErrorAsync;
}
DeviceManager::DeviceSetupStatus DevicePluginOpenweathermap::setupDevice(Device *device)
{
foreach (Device *deviceListDevice, deviceManager()->findConfiguredDevices(openweathermapDeviceClassId)) {
if(deviceListDevice->paramValue("id").toString() == device->paramValue("id").toString()){
qWarning() << QString("Location " + device->paramValue("location").toString() + " already added.");
return DeviceManager::DeviceSetupStatusFailure;
}
}
device->setName("Weather from OpenWeatherMap (" + device->paramValue("location").toString() + ")");
m_openweaher->update(device->paramValue("id").toString(), device->id());
return DeviceManager::DeviceSetupStatusSuccess;
}
DeviceManager::HardwareResources DevicePluginOpenweathermap::requiredHardware() const
{
return DeviceManager::HardwareResourceTimer;
}
DeviceManager::DeviceError DevicePluginOpenweathermap::executeAction(Device *device, const Action &action)
{
if(action.actionTypeId() == updateWeatherActionTypeId){
m_openweaher->update(device->paramValue("id").toString(), device->id());
}
return DeviceManager::DeviceErrorNoError;
}
void DevicePluginOpenweathermap::guhTimer()
{
foreach (Device *device, deviceManager()->findConfiguredDevices(openweathermapDeviceClassId)) {
m_openweaher->update(device->paramValue("id").toString(), device->id());
}
}
void DevicePluginOpenweathermap::searchResultsReady(const QList<QVariantMap> &cityList)
{
QList<DeviceDescriptor> retList;
foreach (QVariantMap elemant, cityList) {
DeviceDescriptor descriptor(openweathermapDeviceClassId, elemant.value("name").toString(),elemant.value("country").toString());
ParamList params;
Param locationParam("location", elemant.value("name"));
params.append(locationParam);
Param countryParam("country", elemant.value("country"));
params.append(countryParam);
Param idParam("id", elemant.value("id"));
params.append(idParam);
descriptor.setParams(params);
retList.append(descriptor);
}
emit devicesDiscovered(openweathermapDeviceClassId,retList);
}
void DevicePluginOpenweathermap::weatherDataReady(const QByteArray &data, const DeviceId &deviceId)
{
QJsonParseError error;
QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
if(error.error != QJsonParseError::NoError) {
qWarning() << "failed to parse data" << data << ":" << error.errorString();
return;
}
QVariantMap dataMap = jsonDoc.toVariant().toMap();
foreach (Device *device, deviceManager()->findConfiguredDevices(openweathermapDeviceClassId)) {
if(device->id() == deviceId){
if(dataMap.contains("clouds")){
int cloudiness = dataMap.value("clouds").toMap().value("all").toInt();
device->setStateValue(cloudinessStateTypeId,cloudiness);
}
if(dataMap.contains("dt")){
uint lastUpdate = dataMap.value("dt").toUInt();
device->setStateValue(updateTimeStateTypeId,lastUpdate);
}
if(dataMap.contains("main")){
double temperatur = dataMap.value("main").toMap().value("temp").toDouble();
double temperaturMax = dataMap.value("main").toMap().value("temp_max").toDouble();
double temperaturMin = dataMap.value("main").toMap().value("temp_min").toDouble();
double pressure = dataMap.value("main").toMap().value("pressure").toDouble();
int humidity = dataMap.value("main").toMap().value("humidity").toInt();
device->setStateValue(temperatureStateTypeId,temperatur);
device->setStateValue(temperatureMinStateTypeId,temperaturMin);
device->setStateValue(temperatureMaxStateTypeId,temperaturMax);
device->setStateValue(pressureStateTypeId,pressure);
device->setStateValue(humidityStateTypeId,humidity);
}
if(dataMap.contains("sys")){
uint sunrise = dataMap.value("sys").toMap().value("sunrise").toUInt();
uint sunset = dataMap.value("sys").toMap().value("sunset").toUInt();
device->setStateValue(sunriseStateTypeId,sunrise);
device->setStateValue(sunsetStateTypeId,sunset);
}
if(dataMap.contains("weather")){
QString description = dataMap.value("weather").toMap().value("description").toString();
device->setStateValue(weatherDescriptionStateTypeId,description);
}
if(dataMap.contains("wind")){
int windDirection = dataMap.value("wind").toMap().value("deg").toInt();
double windSpeed = dataMap.value("wind").toMap().value("speed").toDouble();
device->setStateValue(windDirectionStateTypeId,windDirection);
device->setStateValue(windSpeedStateTypeId,windSpeed);
}
}
}
}
| Java |
/*************************************************************************/ /*!
@File
@Title Services definitions required by external drivers
@Copyright Copyright (c) Imagination Technologies Ltd. All Rights Reserved
@Description Provides services data structures, defines and prototypes
required by external drivers
@License Dual MIT/GPLv2
The contents of this file are subject to the MIT license as set out below.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 ("GPL") in which case the provisions
of GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms of
GPL, and not to allow others to use your version of this file under the terms
of the MIT license, indicate your decision by deleting the provisions above
and replace them with the notice and other provisions required by GPL as set
out in the file called "GPL-COPYING" included in this distribution. If you do
not delete the provisions above, a recipient may use your version of this file
under the terms of either the MIT license or GPL.
This License is also included in this distribution in the file called
"MIT-COPYING".
EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ /**************************************************************************/
#if !defined (__SERVICESEXT_H__)
#define __SERVICESEXT_H__
/* include/ */
#include "pvrsrv_error.h"
#include "img_types.h"
#include "pvrsrv_device_types.h"
/*
* Lock buffer read/write flags
*/
#define PVRSRV_LOCKFLG_READONLY (1) /*!< The locking process will only read the locked surface */
/*!
*****************************************************************************
* Services State
*****************************************************************************/
typedef enum _PVRSRV_SERVICES_STATE_
{
PVRSRV_SERVICES_STATE_OK = 0,
PVRSRV_SERVICES_STATE_BAD,
} PVRSRV_SERVICES_STATE;
/*!
*****************************************************************************
* States for power management
*****************************************************************************/
/*!
System Power State Enum
*/
typedef enum _PVRSRV_SYS_POWER_STATE_
{
PVRSRV_SYS_POWER_STATE_Unspecified = -1, /*!< Unspecified : Uninitialised */
PVRSRV_SYS_POWER_STATE_OFF = 0, /*!< Off */
PVRSRV_SYS_POWER_STATE_ON = 1, /*!< On */
PVRSRV_SYS_POWER_STATE_FORCE_I32 = 0x7fffffff /*!< Force enum to be at least 32-bits wide */
} PVRSRV_SYS_POWER_STATE, *PPVRSRV_SYS_POWER_STATE; /*!< Typedef for ptr to PVRSRV_SYS_POWER_STATE */
/*!
Device Power State Enum
*/
typedef enum _PVRSRV_DEV_POWER_STATE_
{
PVRSRV_DEV_POWER_STATE_DEFAULT = -1, /*!< Default state for the device */
PVRSRV_DEV_POWER_STATE_OFF = 0, /*!< Unpowered */
PVRSRV_DEV_POWER_STATE_ON = 1, /*!< Running */
PVRSRV_DEV_POWER_STATE_FORCE_I32 = 0x7fffffff /*!< Force enum to be at least 32-bits wide */
} PVRSRV_DEV_POWER_STATE, *PPVRSRV_DEV_POWER_STATE; /*!< Typedef for ptr to PVRSRV_DEV_POWER_STATE */ /* PRQA S 3205 */
/* Power transition handler prototypes */
/*!
Typedef for a pointer to a Function that will be called before a transition
from one power state to another. See also PFN_POST_POWER.
*/
typedef PVRSRV_ERROR (*PFN_PRE_POWER) (IMG_HANDLE hDevHandle,
PVRSRV_DEV_POWER_STATE eNewPowerState,
PVRSRV_DEV_POWER_STATE eCurrentPowerState,
IMG_BOOL bForced);
/*!
Typedef for a pointer to a Function that will be called after a transition
from one power state to another. See also PFN_PRE_POWER.
*/
typedef PVRSRV_ERROR (*PFN_POST_POWER) (IMG_HANDLE hDevHandle,
PVRSRV_DEV_POWER_STATE eNewPowerState,
PVRSRV_DEV_POWER_STATE eCurrentPowerState,
IMG_BOOL bForced);
/* Clock speed handler prototypes */
/*!
Typedef for a pointer to a Function that will be caled before a transition
from one clockspeed to another. See also PFN_POST_CLOCKSPEED_CHANGE.
*/
typedef PVRSRV_ERROR (*PFN_PRE_CLOCKSPEED_CHANGE) (IMG_HANDLE hDevHandle,
IMG_BOOL bIdleDevice,
PVRSRV_DEV_POWER_STATE eCurrentPowerState);
/*!
Typedef for a pointer to a Function that will be caled after a transition
from one clockspeed to another. See also PFN_PRE_CLOCKSPEED_CHANGE.
*/
typedef PVRSRV_ERROR (*PFN_POST_CLOCKSPEED_CHANGE) (IMG_HANDLE hDevHandle,
IMG_BOOL bIdleDevice,
PVRSRV_DEV_POWER_STATE eCurrentPowerState);
/*!
*****************************************************************************
* Enumeration of possible alpha types.
*****************************************************************************/
typedef enum _PVRSRV_ALPHA_FORMAT_ {
PVRSRV_ALPHA_FORMAT_UNKNOWN = 0x00000000, /*!< Alpha Format: Unknown */
PVRSRV_ALPHA_FORMAT_PRE = 0x00000001, /*!< Alpha Format: Pre-Alpha */
PVRSRV_ALPHA_FORMAT_NONPRE = 0x00000002, /*!< Alpha Format: Non-Pre-Alpha */
PVRSRV_ALPHA_FORMAT_MASK = 0x0000000F, /*!< Alpha Format Mask */
} PVRSRV_ALPHA_FORMAT;
/*!
*****************************************************************************
* Enumeration of possible alpha types.
*****************************************************************************/
typedef enum _PVRSRV_COLOURSPACE_FORMAT_ {
PVRSRV_COLOURSPACE_FORMAT_UNKNOWN = 0x00000000, /*!< Colourspace Format: Unknown */
PVRSRV_COLOURSPACE_FORMAT_LINEAR = 0x00010000, /*!< Colourspace Format: Linear */
PVRSRV_COLOURSPACE_FORMAT_NONLINEAR = 0x00020000, /*!< Colourspace Format: Non-Linear */
PVRSRV_COLOURSPACE_FORMAT_MASK = 0x000F0000, /*!< Colourspace Format Mask */
} PVRSRV_COLOURSPACE_FORMAT;
/*!
* Drawable orientation (in degrees clockwise).
*/
typedef enum _PVRSRV_ROTATION_ {
PVRSRV_ROTATE_0 = 0, /*!< Rotate by 0 degres */
PVRSRV_ROTATE_90 = 1, /*!< Rotate by 90 degrees */
PVRSRV_ROTATE_180 = 2, /*!< Rotate by 180 degrees */
PVRSRV_ROTATE_270 = 3, /*!< Rotate by 270 degrees */
PVRSRV_FLIP_Y = 4, /*!< Flip in Y axis */
} PVRSRV_ROTATION;
/*!
*****************************************************************************
* This structure is used for OS independent registry (profile) access
*****************************************************************************/
typedef struct _PVRSRV_REGISTRY_INFO
{
IMG_UINT32 ui32DevCookie;
IMG_PCHAR pszKey;
IMG_PCHAR pszValue;
IMG_PCHAR pszBuf;
IMG_UINT32 ui32BufSize;
} PVRSRV_REGISTRY_INFO, *PPVRSRV_REGISTRY_INFO;
#endif /* __SERVICESEXT_H__ */
/*****************************************************************************
End of file (servicesext.h)
*****************************************************************************/
| Java |
<!DOCTYPE html>
<html>
<!-- Mirrored from www.w3schools.com/jquery/tryjquery_sel_lastoftypediff.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:35:39 GMT -->
<head>
<script src="../../ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var btn = $(this).text();
$("p").css("background-color","white");
$("p" + btn).css("background-color","yellow");
});
});
</script>
</head>
<body>
<button>:last</button>
<button>:last-child</button>
<button>:last-of-type</button><br>
<p>The first paragraph in body, and the first child in div.</p>
<div style="border:1px solid;">
<p>The first paragraph in div, and the first child in div.</p>
<p>The last paragraph in div, and the last child in div.</p>
</div><br>
<div style="border:1px solid;">
<span>This is a span element, and the first child in this div.</span>
<p>The first paragraph in another div, and the second child in this div.</p>
<p>The last paragraph in another div, and the third child in this div.</p>
<span>This is a span element, and the last child in this div.</span>
</div><br>
<div style="border:1px solid">
<p>The first paragraph in another div, and the first child in this div.</p>
<p>The last paragraph in the another div, and the last child in this div.</p>
</div>
<p>The last paragraph in body, and the last child in div.</p>
</body>
<!-- Mirrored from www.w3schools.com/jquery/tryjquery_sel_lastoftypediff.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:35:39 GMT -->
</html> | Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta name="desCRipTion" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®»¶Ó´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨" />
<title>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®_±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®-dld158ÓéÀÖ{°Ù¶ÈÐÂÎÅ}°Ù¶ÈÈÏÖ¤</title>
<!--ÈÈÁ¦Í¼¿ªÊ¼-->
<meta name="uctk" content="enabled">
<!--ÈÈÁ¦Í¼½áÊø-->
<meta name="keywords" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®"/>
<meta name="desCRipTion" content="»¶Ó´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨"/>
<meta name="sitename" content="Ê×¶¼Ö®´°-±±¾©ÊÐÕþÎñÃÅ»§ÍøÕ¾">
<meta name="siteurl" content="http://www.beijing.gov.cn">
<meta name="district" content="±±¾©" >
<meta name="filetype" content="0">
<meta name="publishedtype" content="1">
<meta name="pagetype" content="2">
<meta name="subject" content="28428;1">
<!-- Le styles -->
<link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap150609.css" rel="stylesheet">
<link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap-responsive150609.css" rel="stylesheet">
<style>
body {
background:#E8E8E8; /* 60px to make the container go all the way to the bottom of the topbar */
}
.navbar .btn-navbar { position:absolute; right:0; margin-top:50px;}
#othermessage p {width:50%;}
#othermessage dl { width:50%;}
#breadcrumbnav ul { width:100%;}
#breadcrumbnav ul li { line-height:14px; font-family:"ËÎÌå"; padding:0px 10px; margin:0; background:none; }
#othermessage span { padding:0px 10px;}
#footer { margin:20px -20px 0px -20px;}
.navbar .nav li a { font-family:"Microsoft YaHei";}
#div_zhengwen { font-family:"SimSun";}
#div_zhengwen p{ font-family:"SimSun"; padding:0;}
select { width:75px; float:left; height:35px;}
.search .input{ border:1px solid #c1c1c1; width:290px;}
.bdsharebuttonbox { float:left; width:80%;}
.navbar .nav li a { padding: 10px 48px 11px 49px;}
.nav_weather span { float:right;}
#footer { position:absolute; left:0; right:0; margin:20px 0 0 0;}
#essaybottom {font-family:"simsun"; }
#pic { text-align:center; }
#pic ul { padding-top:10px; display:none; }
#pic li {font-family:"SimSun";}
.content_text h1 {line-height:150%;}
.version { float:right; padding:48px 50px 0 0}
.search { padding: 50px 0 0 70px;}
.nav_weather a { font-family:simsun;}
.version li a { font-family:simsun;}
.footer-class { font-family:simsun;}
@media only screen and (max-width: 480px)
{
#pic img { width:100%;}
}
@media only screen and (max-width: 320px)
{
#pic img { width:100%;}
}
@media only screen and (max-width: 640px)
{
#pic img { width:100%;}
}
#filerider .filelink {font-family:"SimSun";}
#filerider .filelink a:link { color:#0000ff; font-family:"SimSun";}
</style>
<sCRipT type="text/javasCRipT">
var pageName = "t1424135";
var pageExt = "htm";
var pageIndex = 0 + 1;
var pageCount = 1;
function getCurrentPage() {
document.write(pageIndex);
}
function generatePageList() {
for (i=0;i<1;i++) {
var curPage = i+1;
document.write('<option value=' + curPage);
if (curPage == pageIndex)
document.write(' selected');
document.write('>' + curPage + '</option>');
}
}
function preVious(n) {
if (pageIndex == 1) {
alert('ÒѾÊÇÊ×Ò³£¡');
} else {
getPageLocation(pageIndex-1);
}
}
function next(n) {
if (pageIndex == pageCount) {
alert('ÒѾÊÇβҳ£¡');
} else {
nextPage(pageIndex);
}
}
function nextPage(page) {
var gotoPage = "";
if (page == 0) {
gotoPage = pageName + "." + pageExt;
} else {
gotoPage = pageName + "_" + page + "." + pageExt;
}
location.href = gotoPage;
}
function getPageLocation(page) {
var gotoPage = "";
var tpage;
if (page == 1) {
gotoPage = pageName + "." + pageExt;
} else {
tpage=page-1;
gotoPage = pageName + "_" + tpage + "." + pageExt;
}
location.href = gotoPage;
}
</sCRipT>
<SCRIPT type=text/javasCRipT>
function $(xixi) {
return document.getElementById(xixi);
}
//ת»»×ÖºÅ
function doZoom(size){
if(size==12){
$("contentText").style.fontSize = size + "px";
$("fs12").style.display = "";
$("fs14").style.display = "none";
$("fs16").style.display = "none";
}
if(size==14){
$("contentText").style.fontSize = size + "px";
$("fs12").style.display = "none";
$("fs14").style.display = "";
$("fs16").style.display = "none";
}
if(size==16){
$("contentText").style.fontSize = size + "px";
$("fs12").style.display = "none";
$("fs14").style.display = "none";
$("fs16").style.display = "";
}
}
</SCRIPT>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<sCRipT src="//html5shim.googlecode.com/svn/trunk/html5.js"></sCRipT>
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">
<sCRipT type="text/javasCRipT">
window.onload = function(){
var picurl = [
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
];
var i=0;
for(i=0;i<picurl.length;i++)
{
picurl[i].index=i;
if(picurl[i]!="")
{
document.getElementById("pic_"+i).style.display = "block";
}
}
}
</sCRipT>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="nav_weather">
<div class="container"><a href="http://zhengwu.beijing.gov.cn/sld/swld/swsj/t1232150.htm" title="ÊÐί" target="_blank">ÊÐί</a> | <a href="http://www.bjrd.gov.cn/" title="ÊÐÈË´ó" target="_blank">ÊÐÈË´ó</a> | <a href="http://www.beijing.gov.cn/" title="ÊÐÕþ¸®" target="_blank">ÊÐÕþ¸®</a> | <a href="http://www.bjzx.gov.cn/" title="ÊÐÕþÐ" target="_blank">ÊÐÕþÐ</a></div>
</div>
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="span12">
<a class="brand" href="http://www.beijing.gov.cn/"><img src="http://www.beijing.gov.cn/images/zhuanti/xysym/logo.png" /></a>
<div class="search">
<sCRipT language="JavaScript" type="text/javasCRipT">
function checkForm(){
var temp = searchForm.temp.value;
var database = searchForm.database.value;
if(temp==null || temp==""){
alert("ÇëÊäÈëËÑË÷Ìõ¼þ");
}
else{
var url="http://so.beijing.gov.cn/Query?qt="+encodeURIComponent(temp)+"&database="+encodeURIComponent(database);
window.open(url);
}
return false;
}
</sCRipT>
<form id="search" method="get" name="searchForm" action="" target="_blank" onSubmit="return checkForm()">
<input type="hidden" value="bj" id="database" name="database" />
<input name="temp" id="keyword" type="text" value="È«ÎÄËÑË÷" class="input" title="È«ÎÄËÑË÷¹Ø¼ü×Ö" />
<input id="searchbutton" type="image" src="http://www.beijing.gov.cn/images/zhuanti/xysym/search_btn.gif" width="66" height="35" title="µã»÷ËÑË÷" alt="ËÑË÷" />
</form>
</div>
<div class="version"><ul>
<li><a title="ÎÞÕϰ" href="http://wza.beijing.gov.cn/" target="_blank" id="yx_style_nav">ÎÞÕϰ</a></li>
<li><a target="_blank" title="·±Ìå°æ" href="http://210.75.193.158/gate/big5/www.beijing.gov.cn">·±Ìå</a></li>
<li><a target="_blank" title="¼òÌå°æ" href="http://www.beijing.gov.cn">¼òÌå</a></li>
<li class="last"><a target="_blank" title="English Version" href="http://www.ebeijing.gov.cn">English</a></li></ul><ul>
<li><a href="javasCRipT:void(0)" onclick="SetHome(this,window.location)" title="ÉèΪÊ×Ò³">ÉèΪÊ×Ò³</a></li>
<li><a title="¼ÓÈëÊÕ²Ø" href="javasCRipT:void(0)" onclick="shoucang(document.title,window.location)">¼ÓÈëÊÕ²Ø</a></li>
<li class="last"><a target="_blank" title="ÒÆ¶¯°æ" href="http://www.beijing.gov.cn/sjbsy/">ÒÆ¶¯°æ</a></li></ul></div>
</div>
</div>
<div class="nav-collapse">
<div class="container">
<ul class="nav">
<li ><a href="http://www.beijing.gov.cn/" class="normal" title="Ê×Ò³">Ê×Ò³</a></li>
<li><a href="http://zhengwu.beijing.gov.cn/" class="normal" title="ÕþÎñÐÅÏ¢">ÕþÎñÐÅÏ¢</a></li>
<li><a href="http://www.beijing.gov.cn/sqmy/default.htm" class="normal" title="ÉçÇéÃñÒâ">ÉçÇéÃñÒâ</a></li>
<li><a href="http://banshi.beijing.gov.cn" class="normal" title="ÕþÎñ·þÎñ">ÕþÎñ·þÎñ</a></li>
<li><a href="http://www.beijing.gov.cn/bmfw" class="normal" title="±ãÃñ·þÎñ">±ãÃñ·þÎñ</a></li>
<li style="background:none;"><a href="http://www.beijing.gov.cn/rwbj/default.htm" class="normal" title="ÈËÎı±¾©">ÈËÎı±¾©</a></li>
</ul>
</div>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<div class="container" style="background:#fff; margin-top:24px;">
<div class="content_text">
<div id="breadcrumbnav">
<ul>
<li>Ê×Ò³¡¡>¡¡±ãÃñ·þÎñ¡¡>¡¡×îÐÂÌáʾ</li>
</ul>
<div class="clearboth"></div>
</div>
<h1>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<div id="othermessage">
<p>
<span>À´Ô´£º±±¾©ÈÕ±¨</span>
<span>ÈÕÆÚ£º2017-04-21 20:52:12</span></p>
<dl>
<sCRipT language='JavaScript' type="text/javasCRipT">
function changeSize(size){document.getElementById('div_zhengwen').style.fontSize=size+'px'}</sCRipT>
¡¾×ֺŠ<a href='javasCRipT:changeSize(18)' style="font-size:16px;">´ó</a> <a href='javasCRipT:changeSize(14)' style="font-size:14px;">ÖÐ</a> <a href='javasCRipT:changeSize(12)' style="font-size:12px;">С</a>¡¿</dl>
</div>
</h1>
<div id="div_zhengwen">
<div id="pic">
<ul id="pic_0">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_1">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_2">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_3">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_4">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_5">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_6">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_7">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_8">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
<ul id="pic_9">
<li><img src="" border="0" alt="" title="" /></li>
<li></li>
</ul>
</div>
<div class=TRS_Editor><p align="justify">¡¡¡¡±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® »¶Ó´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨</p>
<img src="{img}" width="300" height="330"/>
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q8512341.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q4572165.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q2591990.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q8561463.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q4521287.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®
<p align="justify">¡¡¡¡<p>¡¡¡¡ÈÕǰ£¬Â½¾üÊ×Ö§Å®×Óµ¼µ¯Á¬£¬ÓÀ´ÁËËýÃǵÄ4Ëê¡°ÉúÈÕ¡±¡£</p>
<p>¡¡¡¡2013Ä꣬°´ÕÕ½«Å®±ø±àÅä´Ó±£ÕϸÚλÏò×÷Õ½¸ÚÎ»ÍØÕ¹µÄÒªÇ󣬵Ú41¼¯Ížüµ³Î¯¾ö¶¨£¬´ÓËùÊô²¿¶Ó³éµ÷Å®±ø×齨һ¸öµ¼µ¯·¢ÉäÁ¬¡£µ±Äê3ÔÂ20ÈÕ£¬Ä³Âõ¼µ¯¶þÓªËÑË÷·¢ÉäÁ¬×齨Íê±ÏÕýʽµ®Éú¡£</p>
<div align="center"><img src="http://photocdn.sohu.com/20170327/Img485062022.jpeg" alt="¡°Õþʶù¡±(gcxxjgzh)ÊáÀí·¢ÏÖ£¬¶Ì¶ÌËÄÄêÀ´£¬ÕâȺŮº¢10Óà´Î½ÓÊÜÉϼ¶¾üÊ¿¼ºË£¬´´ÏÂÁ˵¼µ¯Ò¹¼äÉä»÷¡¢´ò»÷³¬µÍ¿Õ¸ßËٰлúµÈ¶àÏîÈ«¾ü¼Í¼£¬±»ÆÀΪ¡°È«¹úÈý°ËºìÆì¼¯Ì塱¡¢¡°È«¹úÎåËĺìÆìÍÅÖ§²¿¡±¡¢Ô¹ãÖݾüÇø¡°»ù²ã½¨Éè±ê±øµ¥Î»¡±¡¢¡°¾üÊÂѵÁ·¼â×ÓÁ¬¡±µÈÈÙÓþ³ÆºÅ¡£" align="middle" border="1" /</p></div>
<div id="filerider">
<div class="filelink" style="margin:10px 0 0 0;"><a href="./P020160207382291268334.doc">¸½¼þ£º2016Äê±±¾©µØÇø²©Îï¹Ý´º½ÚϵÁлһÀÀ±í</a></div>
</div>
</div>
<div id="essaybottom" style="border:0; overflow:hidden; margin-bottom:0;">
<div style="padding-bottom:8px;" id="proclaim"><p style="float:left; line-height:30px;">·ÖÏíµ½£º</p><div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone"></a><a href="#" class="bds_tsina" data-cmd="tsina"></a><a href="#" class="bds_tqq" data-cmd="tqq"></a><a href="#" class="bds_renren" data-cmd="renren"></a><a href="#" class="bds_weixin" data-cmd="weixin"></a></div>
<sCRipT>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdPic":"","bdStyle":"0","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"·ÖÏíµ½£º","viewSize":"16"},"selectShare":{"bdContainerClass":null,"bdSelectMiniList":["qzone","tsina","tqq","renren","weixin"]}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('sCRipT')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</sCRipT></div>
</div>
<div id="essaybottom" style="margin-top:0;">
<div style="padding-bottom:8px;" id="proclaim">תժÉùÃ÷£º×ªÕªÇë×¢Ã÷³ö´¦²¢×ö»ØÁ´</div>
</div>
</div>
</div>
<!-- /container -->
<div id="footer">
<div class="container">
<div class="span1" style="text-align:center"><sCRipT type="text/javasCRipT">document.write(unescape("%3Cspan id='_ideConac' %3E%3C/span%3E%3CsCRipT src='http://dcs.conac.cn/js/01/000/0000/60429971/CA010000000604299710004.js' type='text/javasCRipT'%3E%3C/sCRipT%3E"));</sCRipT></div>
<div class="span8">
<div class="footer-top">
<div class="footer-class">
<p> <a title="¹ØÓÚÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306339.htm" style=" background:0">¹ØÓÚÎÒÃÇ</a><a target="_blank" title="Õ¾µãµØÍ¼" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306342.htm">Õ¾µãµØÍ¼</a><a target="_blank" title="ÁªÏµÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306343.htm">ÁªÏµÎÒÃÇ</a><a target="_blank" title="ÆÀ¼ÛÊ×¶¼Ö®´°" href="mailto:service@beijing.gov.cn">ÆÀ¼ÛÊ×¶¼Ö®´°</a><a target="_blank" title="·¨ÂÉÉùÃ÷" href="http://www.beijing.gov.cn/zdxx/t709204.htm">·¨ÂÉÉùÃ÷</a> </p>
<p>Ö÷°ì£º±±¾©ÊÐÈËÃñÕþ¸® °æÈ¨ËùÓга죺±±¾©Êо¼ÃºÍÐÅÏ¢»¯Î¯Ô±»á ¾©ICP±¸05060933ºÅ ÔËÐйÜÀí£ºÊ×¶¼Ö®´°ÔËÐйÜÀíÖÐÐÄ</p>
<p>¾©¹«Íø°²±¸ 110105000722 µØÖ·£º±±¾©Êг¯ÑôÇø±±³½Î÷·Êý×Ö±±¾©´óÏÃÄϰ˲㠴«Õ棺84371700 ¿Í·þÖÐÐĵ绰£º59321109</p>
</div>
</div>
</div>
</div>
</div>
<div style="display:none">
<sCRipT type="text/javasCRipT">document.write(unescape("%3CsCRipT src='http://yhfx.beijing.gov.cn/webdig.js?z=12' type='text/javasCRipT'%3E%3C/sCRipT%3E"));</sCRipT>
<sCRipT type="text/javasCRipT">wd_paramtracker("_wdxid=000000000000000000000000000000000000000000")</sCRipT>
</div>
<sCRipT src="http://static.gridsumdissector.com/js/Clients/GWD-800003-C99186/gs.js" language="JavaScript"></sCRipT>
<sCRipT type="text/javasCRipT">
// ÉèÖÃΪÖ÷Ò³
function SetHome(obj,vrl){
try{
obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl);
}
catch(e){
if(window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch (e) {
alert("´Ë²Ù×÷±»ä¯ÀÀÆ÷¾Ü¾ø£¡\nÇëÔÚä¯ÀÀÆ÷µØÖ·À¸ÊäÈë¡°about:config¡±²¢»Ø³µ\nÈ»ºó½« [signed.applets.codebase_principal_support]µÄÖµÉèÖÃΪ'true',Ë«»÷¼´¿É¡£");
}
var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage',vrl);
}else{
alert("ÄúµÄä¯ÀÀÆ÷²»Ö§³Ö£¬Çë°´ÕÕÏÂÃæ²½Öè²Ù×÷£º1.´ò¿ªä¯ÀÀÆ÷ÉèÖá£2.µã»÷ÉèÖÃÍøÒ³¡£3.ÊäÈ룺"+vrl+"µã»÷È·¶¨¡£");
}
}
}
// ¼ÓÈëÊÕ²Ø ¼æÈÝ360ºÍIE6
function shoucang(sTitle,sURL)
{
try
{
window.external.addFavorite(sURL, sTitle);
}
catch (e)
{
try
{
window.sidebar.addPanel(sTitle, sURL, "");
}
catch (e)
{
alert("¼ÓÈëÊÕ²ØÊ§°Ü£¬ÇëʹÓÃCtrl+D½øÐÐÌí¼Ó");
}
}
}
</sCRipT>
<!-- Le javasCRipT
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<sCRipT src="/images/zhuanti/xysym/jquery.js"></sCRipT>
<sCRipT src="/images/zhuanti/xysym/bootstrap-collapse.js"></sCRipT>
<sCRipT>
$(document).ready(function(){
$(".ui-select").selectWidget({
change : function (changes) {
return changes;
},
effect : "slide",
keyControl : true,
speed : 200,
scrollHeight : 250
});
});
</sCRipT>
</body>
</html> | Java |
ExpData_plot2
=============
| Java |
<HTML>
<HEAD>
<TITLE> Paint by Numbers - 32x32 #27</TITLE>
</HEAD>
<BODY>
<h1> Paint by Numbers - 32x32 #27</h1>
<p>
<applet
code=PBN10a.class
name=Paint by Numbers
width=616
height=556 >
<param name=filename value=32x32/bridge.xbm>
<param name=solved value=false>
</applet>
<p>
Each number to the right of the grid gives the sizes of
the contiguous blocks of black squares within that row.
Each number below the grid does the same for its column.
<p>
<table border=1 cellpadding=3>
<tr><td>To turn a square: <td>use this mouse button:<td>or this key with the mouse button:
<tr><td align=center>black <td align=center>left <td align=center>none
<tr><td align=center>white <td align=center>right <td align=center>Control
<tr><td align=center>gray <td align=center>middle <td align=center>Shift
</table>
<p>
You can drag the mouse to set a bunch of squares at one time.
<p>
<a href="printable/g32x32-27.html">Printable version of this puzzle</a><br>
<a href="puzzles.html">Back to main page</a>
</BODY>
</HTML>
| Java |
#!/usr/bin/env python
#
# Copyright (C) 2007 Sascha Peilicke <sasch.pe@gmx.de>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#
from random import randrange
from zipfile import ZipFile
from StringIO import StringIO
# Constants
DEFAULT_LEVELPACK = './data/default_pack.zip'
SKILL_EASY = 'Easy' # These values should match the
SKILL_MEDIUM = 'Medium' # the level files!
SKILL_HARD = 'Hard'
FIELD_INVALID = 0 # Constants describing a field on
FIELD_VALID = 1 # the playfield
FIELD_MARKED_VALID = 2
FIELD_MARKED_INVALID = 4
FIELD_OPEN = 8
class Game(object):
"""A paint by numbers game also called nonogram.
"""
def __init__(self, skill=None):
"""Creates a picross game.
Parameters:
skill - Desired skill level (None == random)
"""
self.__level = None
self.__name = None
self.__skill = None
self.__fieldsToOpen = 0
self.__fieldsOpened = 0
self.load(skill=skill)
#
# Miscellaneous methods
#
def _debug_print(self):
print self.getInfo()
print 'go: %s' % (self.__gameOver)
for row in self.__level:
print row
#
# Game information retrieval
#
def getInfo(self):
"""Returns the name, skill and size of the level
"""
return self.__name,self.__skill,len(self.__level)
def getRowHint(self,row):
"""Returns the hint for a specific row.
"""
hint,count = [],0
for columnItem in self.__level[row]:
if columnItem == FIELD_VALID:
count += 1
else:
if count > 0:
hint.append(count)
count = 0
if count > 0:
hint.append(count)
if not hint:
hint.append(0)
return hint
def getColumnHint(self,col):
"""Returns the hint for a specific column.
"""
hint,count = [],0
for row in self.__level:
if row[col] == FIELD_VALID:
count += 1
else:
if count > 0:
hint.append(count)
count = 0
if count > 0:
hint.append(count)
if not hint:
hint.append(0)
return hint
def getField(self,col,row):
return self.__level[row][col]
def isGameWon(self):
return self.__fieldsOpened == self.__fieldsToOpen
#
# Game manipulation methods
#
def restart(self):
"""Reinitializes the current game
"""
for i, row in enumerate(self.__level):
for j, field in enumerate(row):
if field == FIELD_OPEN or field == FIELD_MARKED_VALID:
self.__level[i][j] = FIELD_VALID
elif field == FIELD_MARKED_INVALID:
self.__level[i][j] = FIELD_INVALID
self.__gameOver = False
self.__fieldsOpened = 0
def openField(self,col,row):
field = self.__level[row][col]
if field == FIELD_VALID or field == FIELD_MARKED_VALID:
self.__level[row][col] = FIELD_OPEN
self.__fieldsOpened += 1
return True
else:
return False
def markField(self,col,row):
field = self.__level[row][col]
if field == FIELD_VALID:
self.__level[row][col] = FIELD_MARKED_VALID
elif field == FIELD_MARKED_VALID:
self.__level[row][col] = FIELD_VALID
elif field == FIELD_INVALID:
self.__level[row][col] = FIELD_MARKED_INVALID
elif field == FIELD_MARKED_INVALID:
self.__level[row][col] = FIELD_INVALID
return self.__level[row][col]
def load(self,file=DEFAULT_LEVELPACK,skill=None):
"""Loads a level either from a zipped levelpack or from a textfile.
Parameters:
file - Can be a file path or zipped levelpack
skill - Desired level skill (None == random)
"""
if file.endswith('.lvl'):
# Set the skill variable
if file.startswith('easy'): self.__skill = SKILL_EASY
elif file.startswith('medium'): self.__skill = SKILL_MEDIUM
elif file.startswith('hard'): self.__skill = SKILL_HARD
self.__loadFileContent(open(file,'r'))
elif file.endswith('.zip'):
zip = ZipFile(file)
# We have to select from which files in the zipfile we
# want to choose randomly based on the level's skill
candidates = []
if skill == SKILL_EASY:
for file in zip.namelist():
if file.startswith('easy'):
candidates.append(file)
elif skill == SKILL_MEDIUM:
for file in zip.namelist():
if file.startswith('medium'):
candidates.append(file)
elif skill == SKILL_HARD:
for file in zip.namelist():
if file.startswith('hard'):
candidates.append(file)
# This should never happen in a good levelpack, but if it
# is malformed, just pick something!
if not candidates:
candidates = zip.namelist()
# Select one candidate randomly
which = candidates[randrange(len(candidates))]
# Set the skill variable
if which.startswith('easy'): self.__skill = SKILL_EASY
elif which.startswith('medium'):self.__skill = SKILL_MEDIUM
elif which.startswith('hard'): self.__skill = SKILL_HARD
# Read from zipfile and load file content
buf = zip.read(which)
self.__loadFileContent(StringIO(buf))
def __loadFileContent(self,file):
"""Actually loads the level data from a file.
"""
self.__level = []
for line in file:
if line.startswith('name:'):
self.__name = line[5:].strip()
elif line[0] == '0' or line[0] == '1':
row = []
for field in line:
if field == '0':
row.append(FIELD_INVALID)
elif field == '1':
self.__fieldsToOpen += 1
row.append(FIELD_VALID)
self.__level.append(row)
| Java |
/*
* Copyright (C) 2001-2015 Jacek Sieka, arnetheduck on gmail point com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "stdinc.h"
#include "Mapper_WinUPnP.h"
#include "Util.h"
#include "Text.h"
#include "w.h"
#include "AirUtil.h"
#ifdef HAVE_WINUPNP_H
#include <ole2.h>
#include <natupnp.h>
#else // HAVE_WINUPNP_H
struct IUPnPNAT { };
struct IStaticPortMappingCollection { };
#endif // HAVE_WINUPNP_H
namespace dcpp {
const string Mapper_WinUPnP::name = "Windows UPnP";
Mapper_WinUPnP::Mapper_WinUPnP(const string& localIp, bool v6) :
Mapper(localIp, v6)
{
}
bool Mapper_WinUPnP::supportsProtocol(bool aV6) const {
return !aV6;
}
#ifdef HAVE_WINUPNP_H
bool Mapper_WinUPnP::init() {
HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if(FAILED(hr))
return false;
if(pUN)
return true;
// Lacking the __uuidof in mingw...
CLSID upnp;
OLECHAR upnps[] = L"{AE1E00AA-3FD5-403C-8A27-2BBDC30CD0E1}";
CLSIDFromString(upnps, &upnp);
IID iupnp;
OLECHAR iupnps[] = L"{B171C812-CC76-485A-94D8-B6B3A2794E99}";
CLSIDFromString(iupnps, &iupnp);
pUN = 0;
hr = ::CoCreateInstance(upnp, 0, CLSCTX_INPROC_SERVER, iupnp, reinterpret_cast<LPVOID*>(&pUN));
if(FAILED(hr))
pUN = 0;
return pUN ? true : false;
}
void Mapper_WinUPnP::uninit() {
::CoUninitialize();
}
bool Mapper_WinUPnP::add(const string& port, const Protocol protocol, const string& description) {
IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection();
if(!pSPMC)
return false;
/// @todo use a BSTR wrapper
BSTR protocol_ = SysAllocString(Text::toT(protocols[protocol]).c_str());
BSTR description_ = SysAllocString(Text::toT(description).c_str());
BSTR localIP = !localIp.empty() ? SysAllocString(Text::toT(localIp).c_str()) : nullptr;
auto port_ = Util::toInt(port);
IStaticPortMapping* pSPM = 0;
HRESULT hr = pSPMC->Add(port_, protocol_, port_, localIP, VARIANT_TRUE, description_, &pSPM);
SysFreeString(protocol_);
SysFreeString(description_);
SysFreeString(localIP);
bool ret = SUCCEEDED(hr);
if(ret) {
pSPM->Release();
lastPort = port_;
lastProtocol = protocol;
}
pSPMC->Release();
return ret;
}
bool Mapper_WinUPnP::remove(const string& port, const Protocol protocol) {
IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection();
if(!pSPMC)
return false;
/// @todo use a BSTR wrapper
BSTR protocol_ = SysAllocString(Text::toT(protocols[protocol]).c_str());
auto port_ = Util::toInt(port);
HRESULT hr = pSPMC->Remove(port_, protocol_);
pSPMC->Release();
SysFreeString(protocol_);
bool ret = SUCCEEDED(hr);
if(ret && port_ == lastPort && protocol == lastProtocol) {
lastPort = 0;
}
return ret;
}
string Mapper_WinUPnP::getDeviceName() {
/// @todo use IUPnPDevice::ModelName <http://msdn.microsoft.com/en-us/library/aa381670(VS.85).aspx>?
return Util::emptyString;
}
string Mapper_WinUPnP::getExternalIP() {
// Get the External IP from the last added mapping
if(!lastPort)
return Util::emptyString;
IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection();
if(!pSPMC)
return Util::emptyString;
/// @todo use a BSTR wrapper
BSTR protocol_ = SysAllocString(Text::toT(protocols[lastProtocol]).c_str());
// Lets Query our mapping
IStaticPortMapping* pSPM;
HRESULT hr = pSPMC->get_Item(lastPort, protocol_, &pSPM);
SysFreeString(protocol_);
// Query failed!
if(FAILED(hr) || !pSPM) {
pSPMC->Release();
return Util::emptyString;
}
BSTR bstrExternal = 0;
hr = pSPM->get_ExternalIPAddress(&bstrExternal);
if(FAILED(hr) || !bstrExternal) {
pSPM->Release();
pSPMC->Release();
return Util::emptyString;
}
// convert the result
string ret = Text::wideToAcp(bstrExternal);
// no longer needed
SysFreeString(bstrExternal);
// no longer needed
pSPM->Release();
pSPMC->Release();
return ret;
}
IStaticPortMappingCollection* Mapper_WinUPnP::getStaticPortMappingCollection() {
if(!pUN)
return 0;
IStaticPortMappingCollection* ret = 0;
HRESULT hr = 0;
// some routers lag here
for(int i = 0; i < 3; i++) {
hr = pUN->get_StaticPortMappingCollection (&ret);
if(SUCCEEDED(hr) && ret) break;
Sleep(1500);
}
if(FAILED(hr))
return 0;
return ret;
}
#else // HAVE_WINUPNP_H
bool Mapper_WinUPnP::init() {
return false;
}
void Mapper_WinUPnP::uninit() {
}
bool Mapper_WinUPnP::add(const string& /*port*/, const Protocol /*protocol*/, const string& /*description*/) {
return false;
}
bool Mapper_WinUPnP::remove(const string& /*port*/, const Protocol /*protocol*/) {
return false;
}
string Mapper_WinUPnP::getDeviceName() {
return Util::emptyString;
}
string Mapper_WinUPnP::getExternalIP() {
return Util::emptyString;
}
IStaticPortMappingCollection* Mapper_WinUPnP::getStaticPortMappingCollection() {
return 0;
}
#endif // HAVE_WINUPNP_H
} // dcpp namespace
| Java |
<?php
/*******************************************************************************
* HA2.php
* year : 2014
*
* The HA2 algorithm is a combination between two algorithms (CBA and WBA), where
* the first one is based on the language characters, and the second one is
* based on the language and common words. The HA2 algorithm consists of adding
* the sum of frequencies of the two algorithms for each language, and
* consequently, the promising language is the one having the highest new sum.
*
* NOTE: the algorithm requires including CBA.h, WBA.h and defines.h header
* files to work perfectly.
******************************************************************************/
require_once('CBA.php');
require_once('WBA.php');
class HA2
{
private $cba;
private $wba;
/*
* Constructor, in which the reference characters and reference words are
* loaded for each language.
*/
public function HA2()
{
// instantiate the CBA and WBA classes
$this->cba = new CBA();
$this->wba = new WBA();
}
/*
* Identification: function concerns the identification of an input text
* file, and it consists of adding the probabilities computed by the CBA
* and WBA for each language.
*
* [output]: the number of the promising language (between 0-31).
*
* @param text: is the text to identify.
*/
public function identification($text)
{
$cbaProbabilities = $this->cba->computeProbabilities($text); // retrieve probabilities computed by CBA
$wbaProbabilities = $this->wba->computeProbabilities($text); // retrieve probabilities computed by WBA
// add the probabilities for each language
$probabilities = array();
for($language=0; $language<NUMBER_LANGUAGES; $language++)
{
$probabilities[$language] = $cbaProbabilities[$language] + $wbaProbabilities[$language];
}
return $this->classification($probabilities);
}
/*
* Classification: function to classify the input text to the
* corresponding language using the sum of probabilities (CBA + WBA).
*
* [output]: the number of the promising language (between 0-31).
*
* @param probabilities: a table of probabilities of all the languages.
*/
public function classification($probabilities)
{
// retrieve the highest probability (sum of frequencies)
$max = 0; // keeps the highest probability
$promising_language = -1; // keeps the promising language
for($language=0; $language<NUMBER_LANGUAGES; $language++)
{
if($probabilities[$language] > $max)
{
$max = $probabilities[$language];
$promising_language = $language;
}
}
// determine exactly the promising language by applying an order of classification
if($promising_language != LNG_CHINESE && $promising_language != LNG_GREEK &&
$promising_language != LNG_HEBREW && $promising_language != LNG_HINDI &&
$promising_language != LNG_THAI)
{
if($max == $probabilities[LNG_ARABIC]) $promising_language = LNG_ARABIC;
else if($max == $probabilities[LNG_PERSIAN]) $promising_language = LNG_PERSIAN;
else if($max == $probabilities[LNG_URDU]) $promising_language = LNG_URDU;
else if($max == $probabilities[LNG_BULGARIAN]) $promising_language = LNG_BULGARIAN;
else if($max == $probabilities[LNG_RUSSIAN]) $promising_language = LNG_RUSSIAN;
else if($max == $probabilities[LNG_ENGLISH]) $promising_language = LNG_ENGLISH;
else if($max == $probabilities[LNG_DUTCH]) $promising_language = LNG_DUTCH;
else if($max == $probabilities[LNG_INDONESIAN]) $promising_language = LNG_INDONESIAN;
else if($max == $probabilities[LNG_MALAYSIAN]) $promising_language = LNG_MALAYSIAN;
else if($max == $probabilities[LNG_LATIN]) $promising_language = LNG_LATIN;
else if($max == $probabilities[LNG_ROMAN]) $promising_language = LNG_ROMAN;
else if($max == $probabilities[LNG_FRENCH]) $promising_language = LNG_FRENCH;
else if($max == $probabilities[LNG_ITALIAN]) $promising_language = LNG_ITALIAN;
else if($max == $probabilities[LNG_IRISH]) $promising_language = LNG_IRISH;
else if($max == $probabilities[LNG_SPANISH]) $promising_language = LNG_SPANISH;
else if($max == $probabilities[LNG_PORTUGUESE]) $promising_language = LNG_PORTUGUESE;
else if($max == $probabilities[LNG_ALBANIAN]) $promising_language = LNG_ALBANIAN;
else if($max == $probabilities[LNG_CZECH]) $promising_language = LNG_CZECH;
else if($max == $probabilities[LNG_FINNISH]) $promising_language = LNG_FINNISH;
else if($max == $probabilities[LNG_HUNGARIAN]) $promising_language = LNG_HUNGARIAN;
else if($max == $probabilities[LNG_SWEDISH]) $promising_language = LNG_SWEDISH;
else if($max == $probabilities[LNG_GERMAN]) $promising_language = LNG_GERMAN;
else if($max == $probabilities[LNG_NORWEGIAN]) $promising_language = LNG_NORWEGIAN;
else if($max == $probabilities[LNG_DANISH]) $promising_language = LNG_DANISH;
else if($max == $probabilities[LNG_ICELANDIC]) $promising_language = LNG_ICELANDIC;
else if($max == $probabilities[LNG_TURKISH]) $promising_language = LNG_TURKISH;
else if($max == $probabilities[LNG_POLISH]) $promising_language = LNG_POLISH;
}
return $promising_language;
}
}
?> | Java |
/*
* IRIS -- Intelligent Roadway Information System
* Copyright (C) 2007-2016 Minnesota Department of Transportation
* Copyright (C) 2014 AHMCT, University of California
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package us.mn.state.dot.tms.server.comm;
import us.mn.state.dot.tms.DeviceRequest;
import us.mn.state.dot.tms.server.CameraImpl;
/**
* CameraPoller is an interface for pollers which can send camera control
* messages.
*
* @author Douglas Lau
* @author Travis Swanston
*/
public interface CameraPoller {
/** Send a PTZ camera move command */
void sendPTZ(CameraImpl c, float p, float t, float z);
/** Send a store camera preset command */
void sendStorePreset(CameraImpl c, int preset);
/** Send a recall camera preset command */
void sendRecallPreset(CameraImpl c, int preset);
/** Send a device request
* @param c The CameraImpl object.
* @param r The desired DeviceRequest. */
void sendRequest(CameraImpl c, DeviceRequest r);
}
| Java |
# WordPlay
Word Play is basic two player game that removes the letters from a word where the other play is the guess the original word.
Word Play is one the first games that made, definitely the first use looping as base.
WordPlay is considered to complete and will not change.
| Java |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
"""Windowing and user-interface events.
This module allows applications to create and display windows with an
OpenGL context. Windows can be created with a variety of border styles
or set fullscreen.
You can register event handlers for keyboard, mouse and window events.
For games and kiosks you can also restrict the input to your windows,
for example disabling users from switching away from the application
with certain key combinations or capturing and hiding the mouse.
Getting started
---------------
Call the Window constructor to create a new window::
from pyglet.window import Window
win = Window(width=640, height=480)
Attach your own event handlers::
@win.event
def on_key_press(symbol, modifiers):
# ... handle this event ...
Place drawing code for the window within the `Window.on_draw` event handler::
@win.event
def on_draw():
# ... drawing code ...
Call `pyglet.app.run` to enter the main event loop (by default, this
returns when all open windows are closed)::
from pyglet import app
app.run()
Creating a game window
----------------------
Use `Window.set_exclusive_mouse` to hide the mouse cursor and receive relative
mouse movement events. Specify ``fullscreen=True`` as a keyword argument to
the `Window` constructor to render to the entire screen rather than opening a
window::
win = Window(fullscreen=True)
win.set_exclusive_mouse()
Working with multiple screens
-----------------------------
By default, fullscreen windows are opened on the primary display (typically
set by the user in their operating system settings). You can retrieve a list
of attached screens and select one manually if you prefer. This is useful for
opening a fullscreen window on each screen::
display = window.get_platform().get_default_display()
screens = display.get_screens()
windows = []
for screen in screens:
windows.append(window.Window(fullscreen=True, screen=screen))
Specifying a screen has no effect if the window is not fullscreen.
Specifying the OpenGL context properties
----------------------------------------
Each window has its own context which is created when the window is created.
You can specify the properties of the context before it is created
by creating a "template" configuration::
from pyglet import gl
# Create template config
config = gl.Config()
config.stencil_size = 8
config.aux_buffers = 4
# Create a window using this config
win = window.Window(config=config)
To determine if a given configuration is supported, query the screen (see
above, "Working with multiple screens")::
configs = screen.get_matching_configs(config)
if not configs:
# ... config is not supported
else:
win = window.Window(config=configs[0])
"""
from __future__ import division
from builtins import object
from future.utils import with_metaclass
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import sys
import pyglet
from pyglet import gl
from pyglet.event import EventDispatcher
import pyglet.window.key
import pyglet.window.event
_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc
class WindowException(Exception):
"""The root exception for all window-related errors."""
pass
class NoSuchDisplayException(WindowException):
"""An exception indicating the requested display is not available."""
pass
class NoSuchConfigException(WindowException):
"""An exception indicating the requested configuration is not
available."""
pass
class NoSuchScreenModeException(WindowException):
"""An exception indicating the requested screen resolution could not be
met."""
pass
class MouseCursorException(WindowException):
"""The root exception for all mouse cursor-related errors."""
pass
class MouseCursor(object):
"""An abstract mouse cursor."""
#: Indicates if the cursor is drawn using OpenGL. This is True
#: for all mouse cursors except system cursors.
drawable = True
def draw(self, x, y):
"""Abstract render method.
The cursor should be drawn with the "hot" spot at the given
coordinates. The projection is set to the pyglet default (i.e.,
orthographic in window-space), however no other aspects of the
state can be assumed.
:Parameters:
`x` : int
X coordinate of the mouse pointer's hot spot.
`y` : int
Y coordinate of the mouse pointer's hot spot.
"""
raise NotImplementedError('abstract')
class DefaultMouseCursor(MouseCursor):
"""The default mouse cursor used by the operating system."""
drawable = False
class ImageMouseCursor(MouseCursor):
"""A user-defined mouse cursor created from an image.
Use this class to create your own mouse cursors and assign them
to windows. There are no constraints on the image size or format.
"""
drawable = True
def __init__(self, image, hot_x=0, hot_y=0):
"""Create a mouse cursor from an image.
:Parameters:
`image` : `pyglet.image.AbstractImage`
Image to use for the mouse cursor. It must have a
valid ``texture`` attribute.
`hot_x` : int
X coordinate of the "hot" spot in the image relative to the
image's anchor.
`hot_y` : int
Y coordinate of the "hot" spot in the image, relative to the
image's anchor.
"""
self.texture = image.get_texture()
self.hot_x = hot_x
self.hot_y = hot_y
def draw(self, x, y):
gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT)
gl.glColor4f(1, 1, 1, 1)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
self.texture.blit(x - self.hot_x, y - self.hot_y, 0)
gl.glPopAttrib()
def _PlatformEventHandler(data):
"""Decorator for platform event handlers.
Apply giving the platform-specific data needed by the window to associate
the method with an event. See platform-specific subclasses of this
decorator for examples.
The following attributes are set on the function, which is returned
otherwise unchanged:
_platform_event
True
_platform_event_data
List of data applied to the function (permitting multiple decorators
on the same method).
"""
def _event_wrapper(f):
f._platform_event = True
if not hasattr(f, '_platform_event_data'):
f._platform_event_data = []
f._platform_event_data.append(data)
return f
return _event_wrapper
def _ViewEventHandler(f):
f._view = True
return f
class _WindowMetaclass(type):
"""Sets the _platform_event_names class variable on the window
subclass.
"""
def __init__(cls, name, bases, dict):
cls._platform_event_names = set()
for base in bases:
if hasattr(base, '_platform_event_names'):
cls._platform_event_names.update(base._platform_event_names)
for name, func in dict.items():
if hasattr(func, '_platform_event'):
cls._platform_event_names.add(name)
super(_WindowMetaclass, cls).__init__(name, bases, dict)
class BaseWindow(with_metaclass(_WindowMetaclass, EventDispatcher)):
"""Platform-independent application window.
A window is a "heavyweight" object occupying operating system resources.
The "client" or "content" area of a window is filled entirely with
an OpenGL viewport. Applications have no access to operating system
widgets or controls; all rendering must be done via OpenGL.
Windows may appear as floating regions or can be set to fill an entire
screen (fullscreen). When floating, windows may appear borderless or
decorated with a platform-specific frame (including, for example, the
title bar, minimize and close buttons, resize handles, and so on).
While it is possible to set the location of a window, it is recommended
that applications allow the platform to place it according to local
conventions. This will ensure it is not obscured by other windows,
and appears on an appropriate screen for the user.
To render into a window, you must first call `switch_to`, to make
it the current OpenGL context. If you use only one window in the
application, there is no need to do this.
:Ivariables:
`has_exit` : bool
True if the user has attempted to close the window.
:deprecated: Windows are closed immediately by the default
`on_close` handler when `pyglet.app.event_loop` is being
used.
"""
# Filled in by metaclass with the names of all methods on this (sub)class
# that are platform event handlers.
_platform_event_names = set()
#: The default window style.
WINDOW_STYLE_DEFAULT = None
#: The window style for pop-up dialogs.
WINDOW_STYLE_DIALOG = 'dialog'
#: The window style for tool windows.
WINDOW_STYLE_TOOL = 'tool'
#: A window style without any decoration.
WINDOW_STYLE_BORDERLESS = 'borderless'
#: The default mouse cursor.
CURSOR_DEFAULT = None
#: A crosshair mouse cursor.
CURSOR_CROSSHAIR = 'crosshair'
#: A pointing hand mouse cursor.
CURSOR_HAND = 'hand'
#: A "help" mouse cursor; typically a question mark and an arrow.
CURSOR_HELP = 'help'
#: A mouse cursor indicating that the selected operation is not permitted.
CURSOR_NO = 'no'
#: A mouse cursor indicating the element can be resized.
CURSOR_SIZE = 'size'
#: A mouse cursor indicating the element can be resized from the top
#: border.
CURSOR_SIZE_UP = 'size_up'
#: A mouse cursor indicating the element can be resized from the
#: upper-right corner.
CURSOR_SIZE_UP_RIGHT = 'size_up_right'
#: A mouse cursor indicating the element can be resized from the right
#: border.
CURSOR_SIZE_RIGHT = 'size_right'
#: A mouse cursor indicating the element can be resized from the lower-right
#: corner.
CURSOR_SIZE_DOWN_RIGHT = 'size_down_right'
#: A mouse cursor indicating the element can be resized from the bottom
#: border.
CURSOR_SIZE_DOWN = 'size_down'
#: A mouse cursor indicating the element can be resized from the lower-left
#: corner.
CURSOR_SIZE_DOWN_LEFT = 'size_down_left'
#: A mouse cursor indicating the element can be resized from the left
#: border.
CURSOR_SIZE_LEFT = 'size_left'
#: A mouse cursor indicating the element can be resized from the upper-left
#: corner.
CURSOR_SIZE_UP_LEFT = 'size_up_left'
#: A mouse cursor indicating the element can be resized vertically.
CURSOR_SIZE_UP_DOWN = 'size_up_down'
#: A mouse cursor indicating the element can be resized horizontally.
CURSOR_SIZE_LEFT_RIGHT = 'size_left_right'
#: A text input mouse cursor (I-beam).
CURSOR_TEXT = 'text'
#: A "wait" mouse cursor; typically an hourglass or watch.
CURSOR_WAIT = 'wait'
#: The "wait" mouse cursor combined with an arrow.
CURSOR_WAIT_ARROW = 'wait_arrow'
has_exit = False
#: Window display contents validity. The `pyglet.app` event loop
#: examines every window each iteration and only dispatches the `on_draw`
#: event to windows that have `invalid` set. By default, windows always
#: have `invalid` set to ``True``.
#:
#: You can prevent redundant redraws by setting this variable to ``False``
#: in the window's `on_draw` handler, and setting it to True again in
#: response to any events that actually do require a window contents
#: update.
#:
#: :type: bool
#: :since: pyglet 1.1
invalid = True
#: Legacy invalidation flag introduced in pyglet 1.2: set by all event
#: dispatches that go to non-empty handlers. The default 1.2 event loop
#: will therefore redraw after any handled event or scheduled function.
_legacy_invalid = True
# Instance variables accessible only via properties
_width = None
_height = None
_caption = None
_resizable = False
_style = WINDOW_STYLE_DEFAULT
_fullscreen = False
_visible = False
_vsync = False
_screen = None
_config = None
_context = None
# Used to restore window size and position after fullscreen
_windowed_size = None
_windowed_location = None
# Subclasses should update these after relevant events
_mouse_cursor = DefaultMouseCursor()
_mouse_x = 0
_mouse_y = 0
_mouse_visible = True
_mouse_exclusive = False
_mouse_in_window = False
_event_queue = None
_enable_event_queue = True # overridden by EventLoop.
_allow_dispatch_event = False # controlled by dispatch_events stack frame
# Class attributes
_default_width = 640
_default_height = 480
def __init__(self,
width=None,
height=None,
caption=None,
resizable=False,
style=WINDOW_STYLE_DEFAULT,
fullscreen=False,
visible=True,
vsync=True,
display=None,
screen=None,
config=None,
context=None,
mode=None):
"""Create a window.
All parameters are optional, and reasonable defaults are assumed
where they are not specified.
The `display`, `screen`, `config` and `context` parameters form
a hierarchy of control: there is no need to specify more than
one of these. For example, if you specify `screen` the `display`
will be inferred, and a default `config` and `context` will be
created.
`config` is a special case; it can be a template created by the
user specifying the attributes desired, or it can be a complete
`config` as returned from `Screen.get_matching_configs` or similar.
The context will be active as soon as the window is created, as if
`switch_to` was just called.
:Parameters:
`width` : int
Width of the window, in pixels. Defaults to 640, or the
screen width if `fullscreen` is True.
`height` : int
Height of the window, in pixels. Defaults to 480, or the
screen height if `fullscreen` is True.
`caption` : str or unicode
Initial caption (title) of the window. Defaults to
``sys.argv[0]``.
`resizable` : bool
If True, the window will be resizable. Defaults to False.
`style` : int
One of the ``WINDOW_STYLE_*`` constants specifying the
border style of the window.
`fullscreen` : bool
If True, the window will cover the entire screen rather
than floating. Defaults to False.
`visible` : bool
Determines if the window is visible immediately after
creation. Defaults to True. Set this to False if you
would like to change attributes of the window before
having it appear to the user.
`vsync` : bool
If True, buffer flips are synchronised to the primary screen's
vertical retrace, eliminating flicker.
`display` : `Display`
The display device to use. Useful only under X11.
`screen` : `Screen`
The screen to use, if in fullscreen.
`config` : `pyglet.gl.Config`
Either a template from which to create a complete config,
or a complete config.
`context` : `pyglet.gl.Context`
The context to attach to this window. The context must
not already be attached to another window.
`mode` : `ScreenMode`
The screen will be switched to this mode if `fullscreen` is
True. If None, an appropriate mode is selected to accomodate
`width` and `height.`
"""
EventDispatcher.__init__(self)
self._event_queue = []
if not display:
display = get_platform().get_default_display()
if not screen:
screen = display.get_default_screen()
if not config:
for template_config in [
gl.Config(double_buffer=True, depth_size=24),
gl.Config(double_buffer=True, depth_size=16),
None]:
try:
config = screen.get_best_config(template_config)
break
except NoSuchConfigException:
pass
if not config:
raise NoSuchConfigException('No standard config is available.')
if not config.is_complete():
config = screen.get_best_config(config)
if not context:
context = config.create_context(gl.current_context)
# Set these in reverse order to above, to ensure we get user
# preference
self._context = context
self._config = self._context.config
# XXX deprecate config's being screen-specific
if hasattr(self._config, 'screen'):
self._screen = self._config.screen
else:
display = self._config.canvas.display
self._screen = display.get_default_screen()
self._display = self._screen.display
if fullscreen:
if width is None and height is None:
self._windowed_size = self._default_width, self._default_height
width, height = self._set_fullscreen_mode(mode, width, height)
if not self._windowed_size:
self._windowed_size = width, height
else:
if width is None:
width = self._default_width
if height is None:
height = self._default_height
self._width = width
self._height = height
self._resizable = resizable
self._fullscreen = fullscreen
self._style = style
if pyglet.options['vsync'] is not None:
self._vsync = pyglet.options['vsync']
else:
self._vsync = vsync
if caption is None:
caption = sys.argv[0]
# Decode hack for Python2 unicode support:
if hasattr(caption, "decode"):
try:
caption = caption.decode("utf8")
except UnicodeDecodeError:
caption = "pyglet"
self._caption = caption
from pyglet import app
app.windows.add(self)
self._create()
self.switch_to()
if visible:
self.set_visible(True)
self.activate()
def __del__(self):
# Always try to clean up the window when it is dereferenced.
# Makes sure there are no dangling pointers or memory leaks.
# If the window is already closed, pass silently.
try:
self.close()
except: # XXX Avoid a NoneType error if already closed.
pass
def __repr__(self):
return '%s(width=%d, height=%d)' % \
(self.__class__.__name__, self.width, self.height)
def _create(self):
raise NotImplementedError('abstract')
def _recreate(self, changes):
"""Recreate the window with current attributes.
:Parameters:
`changes` : list of str
List of attribute names that were changed since the last
`_create` or `_recreate`. For example, ``['fullscreen']``
is given if the window is to be toggled to or from fullscreen.
"""
raise NotImplementedError('abstract')
def flip(self):
"""Swap the OpenGL front and back buffers.
Call this method on a double-buffered window to update the
visible display with the back buffer. The contents of the back buffer
is undefined after this operation.
Windows are double-buffered by default. This method is called
automatically by `EventLoop` after the `on_draw` event.
"""
raise NotImplementedError('abstract')
def switch_to(self):
"""Make this window the current OpenGL rendering context.
Only one OpenGL context can be active at a time. This method sets
the current window's context to be current. You should use this
method in preference to `pyglet.gl.Context.set_current`, as it may
perform additional initialisation functions.
"""
raise NotImplementedError('abstract')
def set_fullscreen(self, fullscreen=True, screen=None, mode=None,
width=None, height=None):
"""Toggle to or from fullscreen.
After toggling fullscreen, the GL context should have retained its
state and objects, however the buffers will need to be cleared and
redrawn.
If `width` and `height` are specified and `fullscreen` is True, the
screen may be switched to a different resolution that most closely
matches the given size. If the resolution doesn't match exactly,
a higher resolution is selected and the window will be centered
within a black border covering the rest of the screen.
:Parameters:
`fullscreen` : bool
True if the window should be made fullscreen, False if it
should be windowed.
`screen` : Screen
If not None and fullscreen is True, the window is moved to the
given screen. The screen must belong to the same display as
the window.
`mode` : `ScreenMode`
The screen will be switched to the given mode. The mode must
have been obtained by enumerating `Screen.get_modes`. If
None, an appropriate mode will be selected from the given
`width` and `height`.
`width` : int
Optional width of the window. If unspecified, defaults to the
previous window size when windowed, or the screen size if
fullscreen.
**Since:** pyglet 1.2
`height` : int
Optional height of the window. If unspecified, defaults to
the previous window size when windowed, or the screen size if
fullscreen.
**Since:** pyglet 1.2
"""
if (fullscreen == self._fullscreen and
(screen is None or screen is self._screen) and
(width is None or width == self._width) and
(height is None or height == self._height)):
return
if not self._fullscreen:
# Save windowed size
self._windowed_size = self.get_size()
self._windowed_location = self.get_location()
if fullscreen and screen is not None:
assert screen.display is self.display
self._screen = screen
self._fullscreen = fullscreen
if self._fullscreen:
self._width, self._height = self._set_fullscreen_mode(
mode, width, height)
else:
self.screen.restore_mode()
self._width, self._height = self._windowed_size
if width is not None:
self._width = width
if height is not None:
self._height = height
self._recreate(['fullscreen'])
if not self._fullscreen and self._windowed_location:
# Restore windowed location.
# TODO: Move into platform _create?
# Not harmless on Carbon because upsets _width and _height
# via _on_window_bounds_changed.
if pyglet.compat_platform != 'darwin' or pyglet.options['darwin_cocoa']:
self.set_location(*self._windowed_location)
def _set_fullscreen_mode(self, mode, width, height):
if mode is not None:
self.screen.set_mode(mode)
if width is None:
width = self.screen.width
if height is None:
height = self.screen.height
elif width is not None or height is not None:
if width is None:
width = 0
if height is None:
height = 0
mode = self.screen.get_closest_mode(width, height)
if mode is not None:
self.screen.set_mode(mode)
elif self.screen.get_modes():
# Only raise exception if mode switching is at all possible.
raise NoSuchScreenModeException(
'No mode matching %dx%d' % (width, height))
else:
width = self.screen.width
height = self.screen.height
return width, height
def on_resize(self, width, height):
"""A default resize event handler.
This default handler updates the GL viewport to cover the entire
window and sets the ``GL_PROJECTION`` matrix to be orthogonal in
window space. The bottom-left corner is (0, 0) and the top-right
corner is the width and height of the window in pixels.
Override this event handler with your own to create another
projection, for example in perspective.
"""
# XXX avoid GLException by not allowing 0 width or height.
width = max(1, width)
height = max(1, height)
gl.glViewport(0, 0, width, height)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glLoadIdentity()
gl.glOrtho(0, width, 0, height, -1, 1)
gl.glMatrixMode(gl.GL_MODELVIEW)
def on_close(self):
"""Default on_close handler."""
self.has_exit = True
from pyglet import app
if app.event_loop.is_running:
self.close()
def on_key_press(self, symbol, modifiers):
"""Default on_key_press handler."""
if symbol == key.ESCAPE and not (modifiers & ~(key.MOD_NUMLOCK |
key.MOD_CAPSLOCK |
key.MOD_SCROLLLOCK)):
self.dispatch_event('on_close')
def close(self):
"""Close the window.
After closing the window, the GL context will be invalid. The
window instance cannot be reused once closed (see also `set_visible`).
The `pyglet.app.EventLoop.on_window_close` event is dispatched on
`pyglet.app.event_loop` when this method is called.
"""
from pyglet import app
if not self._context:
return
app.windows.remove(self)
self._context.destroy()
self._config = None
self._context = None
if app.event_loop:
app.event_loop.dispatch_event('on_window_close', self)
self._event_queue = []
def draw_mouse_cursor(self):
"""Draw the custom mouse cursor.
If the current mouse cursor has ``drawable`` set, this method
is called before the buffers are flipped to render it.
This method always leaves the ``GL_MODELVIEW`` matrix as current,
regardless of what it was set to previously. No other GL state
is affected.
There is little need to override this method; instead, subclass
``MouseCursor`` and provide your own ``draw`` method.
"""
# Draw mouse cursor if set and visible.
# XXX leaves state in modelview regardless of starting state
if (self._mouse_cursor.drawable and
self._mouse_visible and
self._mouse_in_window):
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glOrtho(0, self.width, 0, self.height, -1, 1)
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPushMatrix()
gl.glLoadIdentity()
self._mouse_cursor.draw(self._mouse_x, self._mouse_y)
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPopMatrix()
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPopMatrix()
# Properties provide read-only access to instance variables. Use
# set_* methods to change them if applicable.
@property
def caption(self):
"""The window caption (title). Read-only.
:type: str
"""
return self._caption
@property
def resizeable(self):
"""True if the window is resizable. Read-only.
:type: bool
"""
return self._resizable
@property
def style(self):
"""The window style; one of the ``WINDOW_STYLE_*`` constants.
Read-only.
:type: int
"""
return self._style
@property
def fullscreen(self):
"""True if the window is currently fullscreen. Read-only.
:type: bool
"""
return self._fullscreen
@property
def visible(self):
"""True if the window is currently visible. Read-only.
:type: bool
"""
return self._visible
@property
def vsync(self):
"""True if buffer flips are synchronised to the screen's vertical
retrace. Read-only.
:type: bool
"""
return self._vsync
@property
def display(self):
"""The display this window belongs to. Read-only.
:type: `Display`
"""
return self._display
@property
def screen(self):
"""The screen this window is fullscreen in. Read-only.
:type: `Screen`
"""
return self._screen
@property
def config(self):
"""A GL config describing the context of this window. Read-only.
:type: `pyglet.gl.Config`
"""
return self._config
@property
def context(self):
"""The OpenGL context attached to this window. Read-only.
:type: `pyglet.gl.Context`
"""
return self._context
# These are the only properties that can be set
@property
def width(self):
"""The width of the window, in pixels. Read-write.
:type: int
"""
return self.get_size()[0]
@width.setter
def width(self, new_width):
self.set_size(new_width, self.height)
@property
def height(self):
"""The height of the window, in pixels. Read-write.
:type: int
"""
return self.get_size()[1]
@height.setter
def height(self, new_height):
self.set_size(self.width, new_height)
def set_caption(self, caption):
"""Set the window's caption.
The caption appears in the titlebar of the window, if it has one,
and in the taskbar on Windows and many X11 window managers.
:Parameters:
`caption` : str or unicode
The caption to set.
"""
raise NotImplementedError('abstract')
def set_minimum_size(self, width, height):
"""Set the minimum size of the window.
Once set, the user will not be able to resize the window smaller
than the given dimensions. There is no way to remove the
minimum size constraint on a window (but you could set it to 0,0).
The behaviour is undefined if the minimum size is set larger than
the current size of the window.
The window size does not include the border or title bar.
:Parameters:
`width` : int
Minimum width of the window, in pixels.
`height` : int
Minimum height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def set_maximum_size(self, width, height):
"""Set the maximum size of the window.
Once set, the user will not be able to resize the window larger
than the given dimensions. There is no way to remove the
maximum size constraint on a window (but you could set it to a large
value).
The behaviour is undefined if the maximum size is set smaller than
the current size of the window.
The window size does not include the border or title bar.
:Parameters:
`width` : int
Maximum width of the window, in pixels.
`height` : int
Maximum height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def set_size(self, width, height):
"""Resize the window.
The behaviour is undefined if the window is not resizable, or if
it is currently fullscreen.
The window size does not include the border or title bar.
:Parameters:
`width` : int
New width of the window, in pixels.
`height` : int
New height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def get_size(self):
"""Return the current size of the window.
The window size does not include the border or title bar.
:rtype: (int, int)
:return: The width and height of the window, in pixels.
"""
raise NotImplementedError('abstract')
def set_location(self, x, y):
"""Set the position of the window.
:Parameters:
`x` : int
Distance of the left edge of the window from the left edge
of the virtual desktop, in pixels.
`y` : int
Distance of the top edge of the window from the top edge of
the virtual desktop, in pixels.
"""
raise NotImplementedError('abstract')
def get_location(self):
"""Return the current position of the window.
:rtype: (int, int)
:return: The distances of the left and top edges from their respective
edges on the virtual desktop, in pixels.
"""
raise NotImplementedError('abstract')
def activate(self):
"""Attempt to restore keyboard focus to the window.
Depending on the window manager or operating system, this may not
be successful. For example, on Windows XP an application is not
allowed to "steal" focus from another application. Instead, the
window's taskbar icon will flash, indicating it requires attention.
"""
raise NotImplementedError('abstract')
def set_visible(self, visible=True):
"""Show or hide the window.
:Parameters:
`visible` : bool
If True, the window will be shown; otherwise it will be
hidden.
"""
raise NotImplementedError('abstract')
def minimize(self):
"""Minimize the window.
"""
raise NotImplementedError('abstract')
def maximize(self):
"""Maximize the window.
The behaviour of this method is somewhat dependent on the user's
display setup. On a multi-monitor system, the window may maximize
to either a single screen or the entire virtual desktop.
"""
raise NotImplementedError('abstract')
def set_vsync(self, vsync):
"""Enable or disable vertical sync control.
When enabled, this option ensures flips from the back to the front
buffer are performed only during the vertical retrace period of the
primary display. This can prevent "tearing" or flickering when
the buffer is updated in the middle of a video scan.
Note that LCD monitors have an analogous time in which they are not
reading from the video buffer; while it does not correspond to
a vertical retrace it has the same effect.
With multi-monitor systems the secondary monitor cannot be
synchronised to, so tearing and flicker cannot be avoided when the
window is positioned outside of the primary display. In this case
it may be advisable to forcibly reduce the framerate (for example,
using `pyglet.clock.set_fps_limit`).
:Parameters:
`vsync` : bool
If True, vsync is enabled, otherwise it is disabled.
"""
raise NotImplementedError('abstract')
def set_mouse_visible(self, visible=True):
"""Show or hide the mouse cursor.
The mouse cursor will only be hidden while it is positioned within
this window. Mouse events will still be processed as usual.
:Parameters:
`visible` : bool
If True, the mouse cursor will be visible, otherwise it
will be hidden.
"""
self._mouse_visible = visible
self.set_mouse_platform_visible()
def set_mouse_platform_visible(self, platform_visible=None):
"""Set the platform-drawn mouse cursor visibility. This is called
automatically after changing the mouse cursor or exclusive mode.
Applications should not normally need to call this method, see
`set_mouse_visible` instead.
:Parameters:
`platform_visible` : bool or None
If None, sets platform visibility to the required visibility
for the current exclusive mode and cursor type. Otherwise,
a bool value will override and force a visibility.
"""
raise NotImplementedError()
def set_mouse_cursor(self, cursor=None):
"""Change the appearance of the mouse cursor.
The appearance of the mouse cursor is only changed while it is
within this window.
:Parameters:
`cursor` : `MouseCursor`
The cursor to set, or None to restore the default cursor.
"""
if cursor is None:
cursor = DefaultMouseCursor()
self._mouse_cursor = cursor
self.set_mouse_platform_visible()
def set_exclusive_mouse(self, exclusive=True):
"""Hide the mouse cursor and direct all mouse events to this
window.
When enabled, this feature prevents the mouse leaving the window. It
is useful for certain styles of games that require complete control of
the mouse. The position of the mouse as reported in subsequent events
is meaningless when exclusive mouse is enabled; you should only use
the relative motion parameters ``dx`` and ``dy``.
:Parameters:
`exclusive` : bool
If True, exclusive mouse is enabled, otherwise it is disabled.
"""
raise NotImplementedError('abstract')
def set_exclusive_keyboard(self, exclusive=True):
"""Prevent the user from switching away from this window using
keyboard accelerators.
When enabled, this feature disables certain operating-system specific
key combinations such as Alt+Tab (Command+Tab on OS X). This can be
useful in certain kiosk applications, it should be avoided in general
applications or games.
:Parameters:
`exclusive` : bool
If True, exclusive keyboard is enabled, otherwise it is
disabled.
"""
raise NotImplementedError('abstract')
def get_system_mouse_cursor(self, name):
"""Obtain a system mouse cursor.
Use `set_mouse_cursor` to make the cursor returned by this method
active. The names accepted by this method are the ``CURSOR_*``
constants defined on this class.
:Parameters:
`name` : str
Name describing the mouse cursor to return. For example,
``CURSOR_WAIT``, ``CURSOR_HELP``, etc.
:rtype: `MouseCursor`
:return: A mouse cursor which can be used with `set_mouse_cursor`.
"""
raise NotImplementedError()
def set_icon(self, *images):
"""Set the window icon.
If multiple images are provided, one with an appropriate size
will be selected (if the correct size is not provided, the image
will be scaled).
Useful sizes to provide are 16x16, 32x32, 64x64 (Mac only) and
128x128 (Mac only).
:Parameters:
`images` : sequence of `pyglet.image.AbstractImage`
List of images to use for the window icon.
"""
pass
def clear(self):
"""Clear the window.
This is a convenience method for clearing the color and depth
buffer. The window must be the active context (see `switch_to`).
"""
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
def dispatch_event(self, *args):
if not self._enable_event_queue or self._allow_dispatch_event:
if EventDispatcher.dispatch_event(self, *args) != False:
self._legacy_invalid = True
else:
self._event_queue.append(args)
def dispatch_events(self):
"""Poll the operating system event queue for new events and call
attached event handlers.
This method is provided for legacy applications targeting pyglet 1.0,
and advanced applications that must integrate their event loop
into another framework.
Typical applications should use `pyglet.app.run`.
"""
raise NotImplementedError('abstract')
# If documenting, show the event methods. Otherwise, leave them out
# as they are not really methods.
if _is_epydoc:
def on_key_press(symbol, modifiers):
"""A key on the keyboard was pressed (and held down).
In pyglet 1.0 the default handler sets `has_exit` to ``True`` if
the ``ESC`` key is pressed.
In pyglet 1.1 the default handler dispatches the `on_close`
event if the ``ESC`` key is pressed.
:Parameters:
`symbol` : int
The key symbol pressed.
`modifiers` : int
Bitwise combination of the key modifiers active.
:event:
"""
def on_key_release(symbol, modifiers):
"""A key on the keyboard was released.
:Parameters:
`symbol` : int
The key symbol pressed.
`modifiers` : int
Bitwise combination of the key modifiers active.
:event:
"""
def on_text(text):
"""The user input some text.
Typically this is called after `on_key_press` and before
`on_key_release`, but may also be called multiple times if the key
is held down (key repeating); or called without key presses if
another input method was used (e.g., a pen input).
You should always use this method for interpreting text, as the
key symbols often have complex mappings to their unicode
representation which this event takes care of.
:Parameters:
`text` : unicode
The text entered by the user.
:event:
"""
def on_text_motion(motion):
"""The user moved the text input cursor.
Typically this is called after `on_key_press` and before
`on_key_release`, but may also be called multiple times if the key
is help down (key repeating).
You should always use this method for moving the text input cursor
(caret), as different platforms have different default keyboard
mappings, and key repeats are handled correctly.
The values that `motion` can take are defined in
`pyglet.window.key`:
* MOTION_UP
* MOTION_RIGHT
* MOTION_DOWN
* MOTION_LEFT
* MOTION_NEXT_WORD
* MOTION_PREVIOUS_WORD
* MOTION_BEGINNING_OF_LINE
* MOTION_END_OF_LINE
* MOTION_NEXT_PAGE
* MOTION_PREVIOUS_PAGE
* MOTION_BEGINNING_OF_FILE
* MOTION_END_OF_FILE
* MOTION_BACKSPACE
* MOTION_DELETE
:Parameters:
`motion` : int
The direction of motion; see remarks.
:event:
"""
def on_text_motion_select(motion):
"""The user moved the text input cursor while extending the
selection.
Typically this is called after `on_key_press` and before
`on_key_release`, but may also be called multiple times if the key
is help down (key repeating).
You should always use this method for responding to text selection
events rather than the raw `on_key_press`, as different platforms
have different default keyboard mappings, and key repeats are
handled correctly.
The values that `motion` can take are defined in `pyglet.window.key`:
* MOTION_UP
* MOTION_RIGHT
* MOTION_DOWN
* MOTION_LEFT
* MOTION_NEXT_WORD
* MOTION_PREVIOUS_WORD
* MOTION_BEGINNING_OF_LINE
* MOTION_END_OF_LINE
* MOTION_NEXT_PAGE
* MOTION_PREVIOUS_PAGE
* MOTION_BEGINNING_OF_FILE
* MOTION_END_OF_FILE
:Parameters:
`motion` : int
The direction of selection motion; see remarks.
:event:
"""
def on_mouse_motion(x, y, dx, dy):
"""The mouse was moved with no buttons held down.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`dx` : int
Relative X position from the previous mouse position.
`dy` : int
Relative Y position from the previous mouse position.
:event:
"""
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
"""The mouse was moved with one or more mouse buttons pressed.
This event will continue to be fired even if the mouse leaves
the window, so long as the drag buttons are continuously held down.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`dx` : int
Relative X position from the previous mouse position.
`dy` : int
Relative Y position from the previous mouse position.
`buttons` : int
Bitwise combination of the mouse buttons currently pressed.
`modifiers` : int
Bitwise combination of any keyboard modifiers currently
active.
:event:
"""
def on_mouse_press(x, y, button, modifiers):
"""A mouse button was pressed (and held down).
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`button` : int
The mouse button that was pressed.
`modifiers` : int
Bitwise combination of any keyboard modifiers currently
active.
:event:
"""
def on_mouse_release(x, y, button, modifiers):
"""A mouse button was released.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`button` : int
The mouse button that was released.
`modifiers` : int
Bitwise combination of any keyboard modifiers currently
active.
:event:
"""
def on_mouse_scroll(x, y, scroll_x, scroll_y):
"""The mouse wheel was scrolled.
Note that most mice have only a vertical scroll wheel, so
`scroll_x` is usually 0. An exception to this is the Apple Mighty
Mouse, which has a mouse ball in place of the wheel which allows
both `scroll_x` and `scroll_y` movement.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
`scroll_x` : int
Number of "clicks" towards the right (left if negative).
`scroll_y` : int
Number of "clicks" upwards (downwards if negative).
:event:
"""
def on_close():
"""The user attempted to close the window.
This event can be triggered by clicking on the "X" control box in
the window title bar, or by some other platform-dependent manner.
The default handler sets `has_exit` to ``True``. In pyglet 1.1, if
`pyglet.app.event_loop` is being used, `close` is also called,
closing the window immediately.
:event:
"""
def on_mouse_enter(x, y):
"""The mouse was moved into the window.
This event will not be trigged if the mouse is currently being
dragged.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
:event:
"""
def on_mouse_leave(x, y):
"""The mouse was moved outside of the window.
This event will not be trigged if the mouse is currently being
dragged. Note that the coordinates of the mouse pointer will be
outside of the window rectangle.
:Parameters:
`x` : int
Distance in pixels from the left edge of the window.
`y` : int
Distance in pixels from the bottom edge of the window.
:event:
"""
def on_expose():
"""A portion of the window needs to be redrawn.
This event is triggered when the window first appears, and any time
the contents of the window is invalidated due to another window
obscuring it.
There is no way to determine which portion of the window needs
redrawing. Note that the use of this method is becoming
increasingly uncommon, as newer window managers composite windows
automatically and keep a backing store of the window contents.
:event:
"""
def on_resize(width, height):
"""The window was resized.
The window will have the GL context when this event is dispatched;
there is no need to call `switch_to` in this handler.
:Parameters:
`width` : int
The new width of the window, in pixels.
`height` : int
The new height of the window, in pixels.
:event:
"""
def on_move(x, y):
"""The window was moved.
:Parameters:
`x` : int
Distance from the left edge of the screen to the left edge
of the window.
`y` : int
Distance from the top edge of the screen to the top edge of
the window. Note that this is one of few methods in pyglet
which use a Y-down coordinate system.
:event:
"""
def on_activate():
"""The window was activated.
This event can be triggered by clicking on the title bar, bringing
it to the foreground; or by some platform-specific method.
When a window is "active" it has the keyboard focus.
:event:
"""
def on_deactivate():
"""The window was deactivated.
This event can be triggered by clicking on another application
window. When a window is deactivated it no longer has the
keyboard focus.
:event:
"""
def on_show():
"""The window was shown.
This event is triggered when a window is restored after being
minimised, or after being displayed for the first time.
:event:
"""
def on_hide():
"""The window was hidden.
This event is triggered when a window is minimised or (on Mac OS X)
hidden by the user.
:event:
"""
def on_context_lost():
"""The window's GL context was lost.
When the context is lost no more GL methods can be called until it
is recreated. This is a rare event, triggered perhaps by the user
switching to an incompatible video mode. When it occurs, an
application will need to reload all objects (display lists, texture
objects, shaders) as well as restore the GL state.
:event:
"""
def on_context_state_lost():
"""The state of the window's GL context was lost.
pyglet may sometimes need to recreate the window's GL context if
the window is moved to another video device, or between fullscreen
or windowed mode. In this case it will try to share the objects
(display lists, texture objects, shaders) between the old and new
contexts. If this is possible, only the current state of the GL
context is lost, and the application should simply restore state.
:event:
"""
def on_draw():
"""The window contents must be redrawn.
The `EventLoop` will dispatch this event when the window
should be redrawn. This will happen during idle time after
any window events and after any scheduled functions were called.
The window will already have the GL context, so there is no
need to call `switch_to`. The window's `flip` method will
be called after this event, so your event handler should not.
You should make no assumptions about the window contents when
this event is triggered; a resize or expose event may have
invalidated the framebuffer since the last time it was drawn.
:since: pyglet 1.1
:event:
"""
BaseWindow.register_event_type('on_key_press')
BaseWindow.register_event_type('on_key_release')
BaseWindow.register_event_type('on_text')
BaseWindow.register_event_type('on_text_motion')
BaseWindow.register_event_type('on_text_motion_select')
BaseWindow.register_event_type('on_mouse_motion')
BaseWindow.register_event_type('on_mouse_drag')
BaseWindow.register_event_type('on_mouse_press')
BaseWindow.register_event_type('on_mouse_release')
BaseWindow.register_event_type('on_mouse_scroll')
BaseWindow.register_event_type('on_mouse_enter')
BaseWindow.register_event_type('on_mouse_leave')
BaseWindow.register_event_type('on_close')
BaseWindow.register_event_type('on_expose')
BaseWindow.register_event_type('on_resize')
BaseWindow.register_event_type('on_move')
BaseWindow.register_event_type('on_activate')
BaseWindow.register_event_type('on_deactivate')
BaseWindow.register_event_type('on_show')
BaseWindow.register_event_type('on_hide')
BaseWindow.register_event_type('on_context_lost')
BaseWindow.register_event_type('on_context_state_lost')
BaseWindow.register_event_type('on_draw')
class FPSDisplay(object):
"""Display of a window's framerate.
This is a convenience class to aid in profiling and debugging. Typical
usage is to create an `FPSDisplay` for each window, and draw the display
at the end of the windows' `on_draw` event handler::
window = pyglet.window.Window()
fps_display = FPSDisplay(window)
@window.event
def on_draw():
# ... perform ordinary window drawing operations ...
fps_display.draw()
The style and position of the display can be modified via the `label`
attribute. Different text can be substituted by overriding the
`set_fps` method. The display can be set to update more or less often
by setting the `update_period` attribute.
:Ivariables:
`label` : Label
The text label displaying the framerate.
"""
#: Time in seconds between updates.
#:
#: :type: float
update_period = 0.25
def __init__(self, window):
from time import time
from pyglet.text import Label
self.label = Label('', x=10, y=10,
font_size=24, bold=True,
color=(127, 127, 127, 127))
self.window = window
self._window_flip = window.flip
window.flip = self._hook_flip
self.time = 0.0
self.last_time = time()
self.count = 0
def update(self):
"""Records a new data point at the current time. This method
is called automatically when the window buffer is flipped.
"""
from time import time
t = time()
self.count += 1
self.time += t - self.last_time
self.last_time = t
if self.time >= self.update_period:
self.set_fps(self.count / self.update_period)
self.time %= self.update_period
self.count = 0
def set_fps(self, fps):
"""Set the label text for the given FPS estimation.
Called by `update` every `update_period` seconds.
:Parameters:
`fps` : float
Estimated framerate of the window.
"""
self.label.text = '%.2f' % fps
def draw(self):
"""Draw the label.
The OpenGL state is assumed to be at default values, except
that the MODELVIEW and PROJECTION matrices are ignored. At
the return of this method the matrix mode will be MODELVIEW.
"""
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glMatrixMode(gl.GL_PROJECTION)
gl.glPushMatrix()
gl.glLoadIdentity()
gl.glOrtho(0, self.window.width, 0, self.window.height, -1, 1)
self.label.draw()
gl.glPopMatrix()
gl.glMatrixMode(gl.GL_MODELVIEW)
gl.glPopMatrix()
def _hook_flip(self):
self.update()
self._window_flip()
if _is_epydoc:
# We are building documentation
Window = BaseWindow
Window.__name__ = 'Window'
del BaseWindow
else:
# Try to determine which platform to use.
if pyglet.compat_platform == 'darwin':
if pyglet.options['darwin_cocoa']:
from pyglet.window.cocoa import CocoaWindow as Window
else:
from pyglet.window.carbon import CarbonWindow as Window
elif pyglet.compat_platform in ('win32', 'cygwin'):
from pyglet.window.win32 import Win32Window as Window
else:
# XXX HACK around circ problem, should be fixed after removal of
# shadow nonsense
#pyglet.window = sys.modules[__name__]
#import key, mouse
from pyglet.window.xlib import XlibWindow as Window
# Deprecated API
def get_platform():
"""Get an instance of the Platform most appropriate for this
system.
:deprecated: Use `pyglet.canvas.Display`.
:rtype: `Platform`
:return: The platform instance.
"""
return Platform()
class Platform(object):
"""Operating-system-level functionality.
The platform instance can only be obtained with `get_platform`. Use
the platform to obtain a `Display` instance.
:deprecated: Use `pyglet.canvas.Display`
"""
def get_display(self, name):
"""Get a display device by name.
This is meaningful only under X11, where the `name` is a
string including the host name and display number; for example
``"localhost:1"``.
On platforms other than X11, `name` is ignored and the default
display is returned. pyglet does not support multiple multiple
video devices on Windows or OS X. If more than one device is
attached, they will appear as a single virtual device comprising
all the attached screens.
:deprecated: Use `pyglet.canvas.get_display`.
:Parameters:
`name` : str
The name of the display to connect to.
:rtype: `Display`
"""
for display in pyglet.app.displays:
if display.name == name:
return display
return pyglet.canvas.Display(name)
def get_default_display(self):
"""Get the default display device.
:deprecated: Use `pyglet.canvas.get_display`.
:rtype: `Display`
"""
return pyglet.canvas.get_display()
if _is_epydoc:
class Display(object):
"""A display device supporting one or more screens.
Use `Platform.get_display` or `Platform.get_default_display` to obtain
an instance of this class. Use a display to obtain `Screen` instances.
:deprecated: Use `pyglet.canvas.Display`.
"""
def __init__(self):
raise NotImplementedError('deprecated')
def get_screens(self):
"""Get the available screens.
A typical multi-monitor workstation comprises one `Display` with
multiple `Screen` s. This method returns a list of screens which
can be enumerated to select one for full-screen display.
For the purposes of creating an OpenGL config, the default screen
will suffice.
:rtype: list of `Screen`
"""
raise NotImplementedError('deprecated')
def get_default_screen(self):
"""Get the default screen as specified by the user's operating system
preferences.
:rtype: `Screen`
"""
raise NotImplementedError('deprecated')
def get_windows(self):
"""Get the windows currently attached to this display.
:rtype: sequence of `Window`
"""
raise NotImplementedError('deprecated')
else:
Display = pyglet.canvas.Display
Screen = pyglet.canvas.Screen
# XXX remove
# Create shadow window. (trickery is for circular import)
if not _is_epydoc:
pyglet.window = sys.modules[__name__]
gl._create_shadow_window()
| Java |
/*
* Copyright (c) 2010 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef __INC_BLOCK_H
#define __INC_BLOCK_H
#include "vp8/common/onyx.h"
#include "vp8/common/blockd.h"
#include "vp8/common/entropymv.h"
#include "vp8/common/entropy.h"
#include "vpx_ports/mem.h"
#define MAX_MODES 20
#define MAX_ERROR_BINS 1024
typedef struct
{
MV mv;
int offset;
} search_site;
typedef struct block
{
short *src_diff;
short *coeff;
short *quant;
short *quant_fast;
short *quant_shift;
short *zbin;
short *zrun_zbin_boost;
short *round;
short zbin_extra;
unsigned char **base_src;
int src;
int src_stride;
} BLOCK;
typedef struct
{
int count;
struct
{
B_PREDICTION_MODE mode;
int_mv mv;
} bmi[16];
} PARTITION_INFO;
typedef struct macroblock
{
DECLARE_ALIGNED(16, short, src_diff[400]);
DECLARE_ALIGNED(16, short, coeff[400]);
DECLARE_ALIGNED(16, unsigned char, thismb[256]);
unsigned char *thismb_ptr;
BLOCK block[25];
YV12_BUFFER_CONFIG src;
MACROBLOCKD e_mbd;
PARTITION_INFO *partition_info;
PARTITION_INFO *pi;
PARTITION_INFO *pip;
int ref_frame_cost[MAX_REF_FRAMES];
search_site *ss;
int ss_count;
int searches_per_step;
int errorperbit;
int sadperbit16;
int sadperbit4;
int rddiv;
int rdmult;
unsigned int * mb_activity_ptr;
int * mb_norm_activity_ptr;
signed int act_zbin_adj;
signed int last_act_zbin_adj;
int *mvcost[2];
int *mvsadcost[2];
int (*mbmode_cost)[MB_MODE_COUNT];
int (*intra_uv_mode_cost)[MB_MODE_COUNT];
int (*bmode_costs)[10][10];
int *inter_bmode_costs;
int (*token_costs)[COEF_BANDS][PREV_COEF_CONTEXTS]
[MAX_ENTROPY_TOKENS];
int mv_col_min;
int mv_col_max;
int mv_row_min;
int mv_row_max;
int skip;
unsigned int encode_breakout;
signed char *gf_active_ptr;
unsigned char *active_ptr;
MV_CONTEXT *mvc;
int optimize;
int q_index;
#if CONFIG_TEMPORAL_DENOISING
MB_PREDICTION_MODE best_sse_inter_mode;
int_mv best_sse_mv;
MV_REFERENCE_FRAME best_reference_frame;
MV_REFERENCE_FRAME best_zeromv_reference_frame;
unsigned char need_to_clamp_best_mvs;
#endif
int skip_true_count;
unsigned int coef_counts [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [MAX_ENTROPY_TOKENS];
unsigned int MVcount [2] [MVvals];
int ymode_count [VP8_YMODES];
int uv_mode_count[VP8_UV_MODES];
int64_t prediction_error;
int64_t intra_error;
int count_mb_ref_frame_usage[MAX_REF_FRAMES];
int rd_thresh_mult[MAX_MODES];
int rd_threshes[MAX_MODES];
unsigned int mbs_tested_so_far;
unsigned int mode_test_hit_counts[MAX_MODES];
int zbin_mode_boost_enabled;
int zbin_mode_boost;
int last_zbin_mode_boost;
int last_zbin_over_quant;
int zbin_over_quant;
int error_bins[MAX_ERROR_BINS];
void (*short_fdct4x4)(short *input, short *output, int pitch);
void (*short_fdct8x4)(short *input, short *output, int pitch);
void (*short_walsh4x4)(short *input, short *output, int pitch);
void (*quantize_b)(BLOCK *b, BLOCKD *d);
void (*quantize_b_pair)(BLOCK *b1, BLOCK *b2, BLOCKD *d0, BLOCKD *d1);
} MACROBLOCK;
#endif
| Java |
// **********************************************************************
//
// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
//
// **********************************************************************
#include <Ice/Ice.h>
#include <IceGrid/IceGrid.h>
#include <Hello.h>
using namespace std;
using namespace Demo;
class HelloClient : public Ice::Application
{
public:
HelloClient();
virtual int run(int, char*[]);
private:
void menu();
void usage();
};
int
main(int argc, char* argv[])
{
HelloClient app;
return app.main(argc, argv, "config.client");
}
HelloClient::HelloClient() :
//
// Since this is an interactive demo we don't want any signal
// handling.
//
Ice::Application(Ice::NoSignalHandling)
{
}
int
HelloClient::run(int argc, char* argv[])
{
if(argc > 2)
{
usage();
return EXIT_FAILURE;
}
bool addContext = false;
if(argc == 2)
{
if(string(argv[1]) == "--context")
{
addContext = true;
}
else
{
usage();
return EXIT_FAILURE;
}
}
//
// Add the context entry that allows the client to use the locator
//
if(addContext)
{
Ice::LocatorPrx locator = communicator()->getDefaultLocator();
Ice::Context ctx;
ctx["SECRET"] = "LetMeIn";
communicator()->setDefaultLocator(locator->ice_context(ctx));
}
//
// Now we try to connect to the object with the `hello' identity.
//
HelloPrx hello = HelloPrx::checkedCast(communicator()->stringToProxy("hello"));
if(!hello)
{
cerr << argv[0] << ": couldn't find a `hello' object." << endl;
return EXIT_FAILURE;
}
menu();
char c = 'x';
do
{
try
{
cout << "==> ";
cin >> c;
if(c == 't')
{
hello->sayHello();
}
else if(c == 't')
{
hello->sayHello();
}
else if(c == 's')
{
hello->shutdown();
}
else if(c == 'x')
{
// Nothing to do
}
else if(c == '?')
{
menu();
}
else
{
cout << "unknown command `" << c << "'" << endl;
menu();
}
}
catch(const Ice::Exception& ex)
{
cerr << ex << endl;
}
}
while(cin.good() && c != 'x');
return EXIT_SUCCESS;
}
void
HelloClient::menu()
{
cout <<
"usage:\n"
"t: send greeting\n"
"s: shutdown server\n"
"x: exit\n"
"?: help\n";
}
void
HelloClient::usage()
{
cerr << "Usage: " << appName() << " [--context]" << endl;
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Luayats: src/win/winobj.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.6.1 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<h1>src/win/winobj.h</h1><a href="winobj_8h.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*************************************************************************</span>
<a name="l00002"></a>00002 <span class="comment">*</span>
<a name="l00003"></a>00003 <span class="comment">* YATS - Yet Another Tiny Simulator</span>
<a name="l00004"></a>00004 <span class="comment">*</span>
<a name="l00005"></a>00005 <span class="comment">**************************************************************************</span>
<a name="l00006"></a>00006 <span class="comment">*</span>
<a name="l00007"></a>00007 <span class="comment">* Copyright (C) 1995-1997 Chair for Telecommunications</span>
<a name="l00008"></a>00008 <span class="comment">* Dresden University of Technology</span>
<a name="l00009"></a>00009 <span class="comment">* D-01062 Dresden</span>
<a name="l00010"></a>00010 <span class="comment">* Germany</span>
<a name="l00011"></a>00011 <span class="comment">*</span>
<a name="l00012"></a>00012 <span class="comment">*</span>
<a name="l00013"></a>00013 <span class="comment">**************************************************************************</span>
<a name="l00014"></a>00014 <span class="comment">*</span>
<a name="l00015"></a>00015 <span class="comment">* This program is free software; you can redistribute it and/or modify</span>
<a name="l00016"></a>00016 <span class="comment">* it under the terms of the GNU General Public License as published by</span>
<a name="l00017"></a>00017 <span class="comment">* the Free Software Foundation; either version 2 of the License, or</span>
<a name="l00018"></a>00018 <span class="comment">* (at your option) any later version.</span>
<a name="l00019"></a>00019 <span class="comment">*</span>
<a name="l00020"></a>00020 <span class="comment">* This program is distributed in the hope that it will be useful,</span>
<a name="l00021"></a>00021 <span class="comment">* but WITHOUT ANY WARRANTY; without even the implied warranty of</span>
<a name="l00022"></a>00022 <span class="comment">* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span>
<a name="l00023"></a>00023 <span class="comment">* GNU General Public License for more details.</span>
<a name="l00024"></a>00024 <span class="comment">*</span>
<a name="l00025"></a>00025 <span class="comment">* You should have received a copy of the GNU General Public License</span>
<a name="l00026"></a>00026 <span class="comment">* along with this program; if not, write to the Free Software</span>
<a name="l00027"></a>00027 <span class="comment">* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.</span>
<a name="l00028"></a>00028 <span class="comment">*</span>
<a name="l00029"></a>00029 <span class="comment">**************************************************************************</span>
<a name="l00030"></a>00030 <span class="comment">*</span>
<a name="l00031"></a>00031 <span class="comment">* Module author: Herbert Leuwer, Marconi Ondata GmbH</span>
<a name="l00032"></a>00032 <span class="comment">* Creation: 2004</span>
<a name="l00033"></a>00033 <span class="comment">*</span>
<a name="l00034"></a>00034 <span class="comment">*************************************************************************/</span>
<a name="l00035"></a>00035 <span class="preprocessor">#ifndef _WINOBJ_H_</span>
<a name="l00036"></a>00036 <span class="preprocessor"></span><span class="preprocessor">#define _WINOBJ_H_</span>
<a name="l00037"></a>00037 <span class="preprocessor"></span>
<a name="l00038"></a>00038 <span class="keyword">extern</span> <span class="stringliteral">"C"</span> {
<a name="l00039"></a>00039 <span class="preprocessor">#include "lua.h"</span>
<a name="l00040"></a>00040 <span class="preprocessor">#include "iup/iup.h"</span>
<a name="l00041"></a>00041 <span class="preprocessor">#include "cd/cd.h"</span>
<a name="l00042"></a>00042 <span class="preprocessor">#include "cd/wd.h"</span>
<a name="l00043"></a>00043 <span class="preprocessor">#include "cd/cddbuf.h"</span>
<a name="l00044"></a>00044 <span class="preprocessor">#include "cd/cdimage.h"</span>
<a name="l00045"></a>00045 <span class="preprocessor">#include "cd/cdirgb.h"</span>
<a name="l00046"></a>00046 }
<a name="l00047"></a>00047 <span class="preprocessor">#include "<a class="code" href="inxout_8h.html">inxout.h</a>"</span>
<a name="l00048"></a>00048
<a name="l00049"></a><a class="code" href="structXSegment.html">00049</a> <span class="keyword">typedef</span> <span class="keyword">struct </span>{
<a name="l00050"></a><a class="code" href="structXSegment.html#a081c4c4ec2bb306f365ee4ebc8b47178">00050</a> <span class="keywordtype">short</span> x1, x2, y1, y2;
<a name="l00051"></a>00051 } <a class="code" href="structXSegment.html">XSegment</a>;
<a name="l00052"></a>00052
<a name="l00053"></a><a class="code" href="structviewport.html">00053</a> <span class="keyword">struct </span><a class="code" href="structviewport.html">viewport</a> {
<a name="l00054"></a><a class="code" href="structviewport.html#ad9b05f6251917e453290a040a8dcfc18">00054</a> <span class="keywordtype">int</span> <a class="code" href="structviewport.html#ad9b05f6251917e453290a040a8dcfc18">xmin</a>;
<a name="l00055"></a><a class="code" href="structviewport.html#a208da7172a2614ef2b378472aaca3dd2">00055</a> <span class="keywordtype">int</span> <a class="code" href="structviewport.html#a208da7172a2614ef2b378472aaca3dd2">xmax</a>;
<a name="l00056"></a><a class="code" href="structviewport.html#aeffd66914138d0e2d44447ceeea51ac3">00056</a> <span class="keywordtype">int</span> <a class="code" href="structviewport.html#aeffd66914138d0e2d44447ceeea51ac3">ymin</a>;
<a name="l00057"></a><a class="code" href="structviewport.html#aed23763a123c3d00941fdcaf660279c2">00057</a> <span class="keywordtype">int</span> <a class="code" href="structviewport.html#aed23763a123c3d00941fdcaf660279c2">ymax</a>;
<a name="l00058"></a>00058 };
<a name="l00059"></a>00059
<a name="l00060"></a>00060 <span class="comment">//tolua_begin</span>
<a name="l00061"></a><a class="code" href="winobj_8h.html#ae54e510918b5a97af07c7e5b037b56cb">00061</a> <span class="preprocessor">#define CDTYPE_IUP (1)</span>
<a name="l00062"></a><a class="code" href="winobj_8h.html#ae321be6df0b536ec7572a418135c2d0e">00062</a> <span class="preprocessor"></span><span class="preprocessor">#define CDTYPE_DBUFFER (2)</span>
<a name="l00063"></a><a class="code" href="winobj_8h.html#a9a682ca41774ce6b098dd6f355dc6879">00063</a> <span class="preprocessor"></span><span class="preprocessor">#define CDTYPE_SERVERIMG (3)</span>
<a name="l00064"></a><a class="code" href="winobj_8h.html#ad3765b329e172e60ae940ec8b1e81895">00064</a> <span class="preprocessor"></span><span class="preprocessor">#define CDTYPE_CLIENTIMG (4)</span>
<a name="l00065"></a><a class="code" href="classwinobj.html">00065</a> <span class="preprocessor"></span><span class="keyword">class </span><a class="code" href="classwinobj.html">winobj</a>: <span class="keyword">public</span> <a class="code" href="classinxout.html">inxout</a> {
<a name="l00066"></a>00066 <span class="keyword">typedef</span> <a class="code" href="classinxout.html">inxout</a> <a class="code" href="classroot.html">baseclass</a>;
<a name="l00067"></a>00067 <span class="keyword">public</span>:
<a name="l00068"></a>00068 <a class="code" href="classwinobj.html#a962fb38e7d8aeb9f5b7b9ca816e54eb4">winobj</a>();
<a name="l00069"></a>00069 <a class="code" href="classwinobj.html#a9a171bc1a1fd0e561407b518e41c16b0">~winobj</a>();
<a name="l00070"></a>00070 <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#aed06bad9352dfac934a357143b7c41f0">set_textsize</a>(<span class="keywordtype">int</span>);
<a name="l00071"></a>00071 cdCanvas *<a class="code" href="classwinobj.html#ac01559e41120617f805ebf24cad8eef3">map</a>(<span class="keywordtype">void</span> *iupcanvas, <span class="keywordtype">void</span> *wid,
<a name="l00072"></a>00072 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#af4e4e80ea9fd32096b91a6144f8d51ae">width</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a39a9abca0530f1cc1d765464fc6c2818">height</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a14d9c26ffe911a780edaa863a61cd5db">xpos</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a09d31c0505a11232509d3e5b8174cd39">ypos</a>,
<a name="l00073"></a>00073 <span class="keyword">const</span> <span class="keywordtype">char</span> *wrtypeface = <span class="stringliteral">"Helvetica"</span>,
<a name="l00074"></a>00074 <span class="keywordtype">int</span> wrstyle = <a class="code" href="cd__pkg_8h.html#a385c44f6fb256e5716a2302a5b940388a5acd5688fe1a05dc4dff09cb8ce98c9c">CD_BOLD</a>,
<a name="l00075"></a>00075 <span class="keywordtype">int</span> wrsize = 10,
<a name="l00076"></a>00076 <span class="keywordtype">void</span> *wrcol = (<span class="keywordtype">void</span> *) <a class="code" href="cd__pkg_8h.html#aa151cc8bc4b43aab96d04e04e8def2e2">CD_BLACK</a>,
<a name="l00077"></a>00077 <span class="keywordtype">int</span> wrmode = <a class="code" href="cd__pkg_8h.html#ac705ce3d609ed366b0efeb8787b9f98aadec23484c84b6a6b5a8284fe3342fcc4">CD_REPLACE</a>,
<a name="l00078"></a>00078 <span class="keywordtype">void</span> *fgcol = (<span class="keywordtype">void</span> *) CD_BLACK,
<a name="l00079"></a>00079 <span class="keywordtype">int</span> fgmode = <a class="code" href="cd__pkg_8h.html#ac705ce3d609ed366b0efeb8787b9f98aadec23484c84b6a6b5a8284fe3342fcc4">CD_REPLACE</a>,
<a name="l00080"></a>00080 <span class="keywordtype">int</span> fgstyle = <a class="code" href="cd__pkg_8h.html#a05d5745a26f0528e3bffebd8a03dcedba48e2d0b7258a5f49989f914e51882930">CD_CONTINUOUS</a>,
<a name="l00081"></a>00081 <span class="keywordtype">int</span> fgwidth = 1,
<a name="l00082"></a>00082 <span class="keywordtype">void</span> *bgcol = (<span class="keywordtype">void</span> *) <a class="code" href="cd__pkg_8h.html#a38a02e70691cf61759ee97b041857acc">CD_WHITE</a>,
<a name="l00083"></a>00083 <span class="keywordtype">int</span> opacity = <a class="code" href="cd__pkg_8h.html#a7e59f212705e8a9d21a7225cf48bb7adab5e3c20eea4e0c4470106fb608529f84">CD_TRANSPARENT</a>,
<a name="l00084"></a>00084 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a338445bcf35090a13f8991aa1384cbe3">usepoly</a> = 0,
<a name="l00085"></a>00085 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a14b24189118f91e41ef35a3dd52d7c9a">polytype</a> = CD_OPEN_LINES,
<a name="l00086"></a>00086 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a99435c16c71caef3c37cca6438a55c28">polystep</a> = 0,
<a name="l00087"></a>00087 <span class="keywordtype">int</span> canvastype = <a class="code" href="winobj_8h.html#a9a682ca41774ce6b098dd6f355dc6879">CDTYPE_SERVERIMG</a>);
<a name="l00088"></a>00088 <span class="comment">// void * map(void *, void*, </span>
<a name="l00089"></a>00089 <span class="comment">// int, int, int, int, </span>
<a name="l00090"></a>00090 <span class="comment">// int, int, int, int, </span>
<a name="l00091"></a>00091 <span class="comment">// int, int, int, int,</span>
<a name="l00092"></a>00092 <span class="comment">// int, int, int);</span>
<a name="l00093"></a>00093 <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#ab6103b0a4f873a6b2d3aa265722c91a9">unmap</a>(<span class="keywordtype">void</span>);
<a name="l00094"></a>00094 <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#a8815c22efb95f851421df6cafecdd92b">draw_values</a>(<span class="keywordtype">int</span> *, <span class="keywordtype">void</span> *color, <span class="keywordtype">int</span> nvals, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a338445bcf35090a13f8991aa1384cbe3">usepoly</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a14b24189118f91e41ef35a3dd52d7c9a">polytype</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a99435c16c71caef3c37cca6438a55c28">polystep</a>, <span class="keywordtype">int</span> flush);
<a name="l00095"></a>00095 <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#a8815c22efb95f851421df6cafecdd92b">draw_values</a>(<span class="keywordtype">double</span> *, <span class="keywordtype">double</span> *, <span class="keywordtype">void</span> *color, <span class="keywordtype">int</span> nvals, <span class="keywordtype">int</span> usepoly, <span class="keywordtype">int</span> polytype, <span class="keywordtype">int</span> polystep, <span class="keywordtype">int</span> flush);
<a name="l00096"></a><a class="code" href="classwinobj.html#a1211aaf8fb8f77713217543c85c741f5">00096</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#a1211aaf8fb8f77713217543c85c741f5">drawWin</a>(<span class="keywordtype">int</span> activate = 1, <span class="keywordtype">int</span> clear = 1, <span class="keywordtype">int</span> flush = 1){}
<a name="l00097"></a>00097 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#aa9d178670489edfaffcca4cb427500fe">getexp</a>(<a class="code" href="structexp__typ.html">exp_typ</a> *);
<a name="l00098"></a><a class="code" href="classwinobj.html#a3fb336be24d1eea6577db8c0521ad7e4">00098</a> cdCanvas* <a class="code" href="classwinobj.html#a3fb336be24d1eea6577db8c0521ad7e4">setCanvas</a>(cdCanvas * cv){
<a name="l00099"></a>00099 <span class="keywordflow">if</span> (<a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">canvas_mapped</a> == <span class="keyword">false</span>)
<a name="l00100"></a>00100 <span class="keywordflow">return</span> NULL;
<a name="l00101"></a>00101 cdCanvas *ocv = <a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>;
<a name="l00102"></a>00102 <a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a> = cv;
<a name="l00103"></a>00103 <span class="keywordflow">return</span> ocv;
<a name="l00104"></a>00104 }
<a name="l00105"></a><a class="code" href="classwinobj.html#ad5fc8e3c0bfcff77680baafb8d6667a6">00105</a> cdCanvas* <a class="code" href="classwinobj.html#ad5fc8e3c0bfcff77680baafb8d6667a6">getCanvas</a>(<span class="keywordtype">void</span>){
<a name="l00106"></a>00106 <span class="keywordflow">if</span> (<a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">canvas_mapped</a> == <span class="keyword">true</span>)
<a name="l00107"></a>00107 <span class="keywordflow">return</span> <a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>;
<a name="l00108"></a>00108 <span class="keywordflow">else</span>
<a name="l00109"></a>00109 <span class="keywordflow">return</span> NULL;
<a name="l00110"></a>00110 }
<a name="l00111"></a><a class="code" href="classwinobj.html#a14b0bccef2254fdacded2f26baba207a">00111</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a14b0bccef2254fdacded2f26baba207a">activateCanvas</a>(<span class="keywordtype">void</span>){
<a name="l00112"></a>00112 <span class="keywordflow">if</span> (<a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">canvas_mapped</a> == <span class="keyword">true</span>)
<a name="l00113"></a>00113 <span class="keywordflow">return</span> cdCanvasActivate(<a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>);
<a name="l00114"></a>00114 <span class="keywordflow">else</span>
<a name="l00115"></a>00115 <span class="keywordflow">return</span> CD_ERROR;
<a name="l00116"></a>00116 }
<a name="l00117"></a><a class="code" href="classwinobj.html#afc77036e1293f0f4581b54d8acf34053">00117</a> <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#afc77036e1293f0f4581b54d8acf34053">setScale</a>(<span class="keywordtype">double</span> scx, <span class="keywordtype">double</span> scy){
<a name="l00118"></a>00118 <a class="code" href="classwinobj.html#a6633c6e017e3f60fb2d547943c13b9f6">sx</a> = scx;
<a name="l00119"></a>00119 <a class="code" href="classwinobj.html#a67bb589183765fc767a323df2c94070c">sy</a> = scy;
<a name="l00120"></a>00120 }
<a name="l00121"></a><a class="code" href="classwinobj.html#afbf73470c5f5faf16ac7d5e695d3bb63">00121</a> <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#afbf73470c5f5faf16ac7d5e695d3bb63">setViewport</a>(<span class="keywordtype">int</span> xmin, <span class="keywordtype">int</span> xmax, <span class="keywordtype">int</span> ymin, <span class="keywordtype">int</span> ymax){
<a name="l00122"></a>00122 <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#ad9b05f6251917e453290a040a8dcfc18">xmin</a> = xmin;
<a name="l00123"></a>00123 <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#a208da7172a2614ef2b378472aaca3dd2">xmax</a> = xmax;
<a name="l00124"></a>00124 <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#aeffd66914138d0e2d44447ceeea51ac3">ymin</a> = ymin;
<a name="l00125"></a>00125 <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#aed23763a123c3d00941fdcaf660279c2">ymax</a> = ymax;
<a name="l00126"></a>00126 wdCanvasViewport(<a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>, <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#ad9b05f6251917e453290a040a8dcfc18">xmin</a>, <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#a208da7172a2614ef2b378472aaca3dd2">xmax</a>, <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#aeffd66914138d0e2d44447ceeea51ac3">ymin</a>, <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#aed23763a123c3d00941fdcaf660279c2">ymax</a>);
<a name="l00127"></a>00127 }
<a name="l00128"></a><a class="code" href="classwinobj.html#af2dadec9ca2c5ac161ce99c4120e479d">00128</a> <a class="code" href="classroot.html">root</a> *<a class="code" href="classwinobj.html#af2dadec9ca2c5ac161ce99c4120e479d">exp_obj</a>;
<a name="l00129"></a><a class="code" href="classwinobj.html#a5f149b5a6efe246f794a90b09ce8f3b0">00129</a> <span class="keywordtype">char</span> *<a class="code" href="classwinobj.html#a5f149b5a6efe246f794a90b09ce8f3b0">exp_varname</a>;
<a name="l00130"></a><a class="code" href="classwinobj.html#a0161fea8d4972fc0265b54ec76821e73">00130</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a0161fea8d4972fc0265b54ec76821e73">exp_idx</a>;
<a name="l00131"></a><a class="code" href="classwinobj.html#abecc923a3e18888f6103d86916d5df04">00131</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#abecc923a3e18888f6103d86916d5df04">exp_idx2</a>;
<a name="l00132"></a><a class="code" href="classwinobj.html#a9f40c79216ca22a23b4f6f428e30ba8b">00132</a> <span class="keywordtype">char</span> *<a class="code" href="classwinobj.html#a9f40c79216ca22a23b4f6f428e30ba8b">title</a>;
<a name="l00133"></a><a class="code" href="classwinobj.html#a42e844b0cf15416d055476503a6c1d09">00133</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a42e844b0cf15416d055476503a6c1d09">cvtype</a>;
<a name="l00134"></a><a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">00134</a> cdCanvas *<a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>;
<a name="l00135"></a><a class="code" href="classwinobj.html#a16b472b5a9b0c49bc8f44873e32e8b51">00135</a> cdCanvas *<a class="code" href="classwinobj.html#a16b472b5a9b0c49bc8f44873e32e8b51">bcanvas</a>;
<a name="l00136"></a><a class="code" href="classwinobj.html#a9f8ebe79dfa0683610bdf68c6d8d8582">00136</a> cdImage *<a class="code" href="classwinobj.html#a9f8ebe79dfa0683610bdf68c6d8d8582">simg</a>;
<a name="l00137"></a><a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">00137</a> <span class="keywordtype">bool</span> <a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">canvas_mapped</a>;
<a name="l00138"></a><a class="code" href="classwinobj.html#af041c6b7fd6ff07d92ae3eb9beeb457e">00138</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#af041c6b7fd6ff07d92ae3eb9beeb457e">drawoper</a>;
<a name="l00139"></a><a class="code" href="classwinobj.html#a47c066fcf1692dbb6632f9d4eb2c8b65">00139</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a47c066fcf1692dbb6632f9d4eb2c8b65">drawstyle</a>;
<a name="l00140"></a><a class="code" href="classwinobj.html#a8e8b11ae02ced81b825726bfb3830d7c">00140</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a8e8b11ae02ced81b825726bfb3830d7c">drawwidth</a>;
<a name="l00141"></a><a class="code" href="classwinobj.html#a3d5d467da7f531e6615143a2e0cda205">00141</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a3d5d467da7f531e6615143a2e0cda205">textoper</a>;
<a name="l00142"></a><a class="code" href="classwinobj.html#aa7a79ced697fded84c60d9b9c62784e1">00142</a> <span class="keywordtype">char</span> *<a class="code" href="classwinobj.html#aa7a79ced697fded84c60d9b9c62784e1">texttypeface</a>;
<a name="l00143"></a><a class="code" href="classwinobj.html#a88151f63245aac2924f2488a055dc1fe">00143</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a88151f63245aac2924f2488a055dc1fe">textstyle</a>;
<a name="l00144"></a><a class="code" href="classwinobj.html#a6213da470644191345393eb791d6d721">00144</a> <span class="keywordtype">void</span> *<a class="code" href="classwinobj.html#a6213da470644191345393eb791d6d721">textcolor</a>;
<a name="l00145"></a><a class="code" href="classwinobj.html#a92ecfdc12216529a62fc4e24ba56a297">00145</a> <span class="keywordtype">void</span> *<a class="code" href="classwinobj.html#a92ecfdc12216529a62fc4e24ba56a297">bgcolor</a>;
<a name="l00146"></a><a class="code" href="classwinobj.html#a292b1a68c62ca6b54b4db924d65f785a">00146</a> <span class="keywordtype">void</span> *<a class="code" href="classwinobj.html#a292b1a68c62ca6b54b4db924d65f785a">drawcolor</a>;
<a name="l00147"></a><a class="code" href="classwinobj.html#ab88ceec0bb8f96ee18e3a3f1afbd2dca">00147</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#ab88ceec0bb8f96ee18e3a3f1afbd2dca">textsize</a>;
<a name="l00148"></a><a class="code" href="classwinobj.html#a7fe1494c3b52b71e5fa2df6aed1a6059">00148</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a7fe1494c3b52b71e5fa2df6aed1a6059">bgopacity</a>;
<a name="l00149"></a><a class="code" href="classwinobj.html#a09d31c0505a11232509d3e5b8174cd39">00149</a> <span class="keywordtype">int</span> width, height, xpos, ypos;
<a name="l00150"></a><a class="code" href="classwinobj.html#a338445bcf35090a13f8991aa1384cbe3">00150</a> <span class="keywordtype">int</span> usepoly, polytype, polystep;
<a name="l00151"></a><a class="code" href="classwinobj.html#a67bb589183765fc767a323df2c94070c">00151</a> <span class="keywordtype">double</span> <a class="code" href="classwinobj.html#a6633c6e017e3f60fb2d547943c13b9f6">sx</a>, <a class="code" href="classwinobj.html#a67bb589183765fc767a323df2c94070c">sy</a>;
<a name="l00152"></a><a class="code" href="classwinobj.html#a8e3848bb4c631cbaf167e42d44ed1a6a">00152</a> <span class="keywordtype">double</span> <a class="code" href="classwinobj.html#a38a0e70c065d42cd3d82fa3c58071eea">xlast</a>, <a class="code" href="classwinobj.html#a8e3848bb4c631cbaf167e42d44ed1a6a">ylast</a>;
<a name="l00153"></a>00153 <span class="comment">//tolua_end</span>
<a name="l00154"></a><a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">00154</a> <span class="keyword">struct </span><a class="code" href="structviewport.html">viewport</a> <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>;
<a name="l00155"></a>00155 <span class="comment">//tolua_begin</span>
<a name="l00156"></a>00156 };
<a name="l00157"></a>00157 <span class="comment">//tolua_end</span>
<a name="l00158"></a>00158 <span class="preprocessor">#endif </span>
</pre></div></div>
<hr size="1"/><address style="text-align: right;"><small>Generated on Sun Feb 14 12:31:43 2010 for Luayats by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.1 </small></address>
</body>
</html>
| Java |
<?php
/** ---------------------------------------------------------------------
* JavascriptLoadManager.php : class to control loading of Javascript libraries
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2009-2010 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* @package CollectiveAccess
* @subpackage Misc
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3
*
* ----------------------------------------------------------------------
*/
/**
*
*/
require_once(__CA_LIB_DIR__.'/core/Configuration.php');
/*
* Globals used by Javascript load manager
*/
/**
* Contains configuration object for javascript.conf file
*/
$g_javascript_config = null;
/**
* Contains list of Javascript libraries to load
*/
$g_javascript_load_list = null;
/**
* Contains array of complementary Javasscript code to load
*/
$g_javascript_complementary = null;
class JavascriptLoadManager {
# --------------------------------------------------------------------------------
# --------------------------------------------------------------------------------
static function init() {
global $g_javascript_config, $g_javascript_load_list;
$o_config = Configuration::load();
$g_javascript_config = Configuration::load($o_config->get('javascript_config'));
$g_javascript_load_list = array();
JavascriptLoadManager::register('_default');
}
# --------------------------------------------------------------------------------
/**
* Causes the specified Javascript library (or libraries) to be loaded for the current request.
* There are two ways you can trigger loading of Javascript:
* (1) If you pass via the $ps_package parameter a loadSet name defined in javascript.conf then all of the libraries in that loadSet will be loaded
* (2) If you pass a package and library name (via $ps_package and $ps_library) then the specified library will be loaded
*
* Whether you use a loadSet or a package/library combination, if it doesn't have a definition in javascript.conf nothing will be loaded.
*
* @param $ps_package (string) - The package name containing the library to be loaded *or* a loadSet name. LoadSets describe a set of libraries to be loaded as a unit.
* @param $ps_library (string) - The name of the library contained in $ps_package to be loaded.
* @return bool - false if load failed, true if load succeeded
*/
static function register($ps_package, $ps_library=null) {
global $g_javascript_config, $g_javascript_load_list;
if (!$g_javascript_config) { JavascriptLoadManager::init(); }
$va_packages = $g_javascript_config->getAssoc('packages');
if ($ps_library) {
// register package/library
$va_pack_path = explode('/', $ps_package);
$vs_main_package = array_shift($va_pack_path);
if (!($va_list = $va_packages[$vs_main_package])) { return false; }
while(sizeof($va_pack_path) > 0) {
$vs_pack = array_shift($va_pack_path);
$va_list = $va_list[$vs_pack];
}
if ($va_list[$ps_library]) {
$g_javascript_load_list[$ps_package.'/'.$va_list[$ps_library]] = true;
return true;
}
} else {
// register loadset
$va_loadsets = $g_javascript_config->getAssoc('loadSets');
if ($va_loadset = $va_loadsets[$ps_package]) {
$vs_loaded_ok = true;
foreach($va_loadset as $vs_path) {
$va_tmp = explode('/', $vs_path);
$vs_library = array_pop($va_tmp);
$vs_package = join('/', $va_tmp);
if (!JavascriptLoadManager::register($vs_package, $vs_library)) {
$vs_loaded_ok = false;
}
}
return $vs_loaded_ok;
}
}
return false;
}
# --------------------------------------------------------------------------------
/**
* Causes the specified Javascript code to be loaded.
*
* @param $ps_scriptcontent (string) - script content to load
* @return (bool) - false if empty code, true if load succeeded
*/
static function addComplementaryScript($ps_content=null) {
global $g_javascript_config, $g_javascript_load_list, $g_javascript_complementary;
if (!$g_javascript_config) { JavascriptLoadManager::init(); }
if (!$ps_content) return false;
$g_javascript_complementary[]=$ps_content;
return true;
}
# --------------------------------------------------------------------------------
/**
* Returns HTML to load registered libraries. Typically you'll output this HTML in the <head> of your page.
*
* @param $ps_baseurlpath (string) - URL path containing the application's "js" directory.
* @return string - HTML loading registered libraries
*/
static function getLoadHTML($ps_baseurlpath) {
global $g_javascript_config, $g_javascript_load_list, $g_javascript_complementary;
if (!$g_javascript_config) { JavascriptLoadManager::init(); }
$vs_buf = '';
if (is_array($g_javascript_load_list)) {
foreach($g_javascript_load_list as $vs_lib => $vn_x) {
if (preg_match('!(http[s]{0,1}://.*)!', $vs_lib, $va_matches)) {
$vs_url = $va_matches[1];
} else {
$vs_url = "{$ps_baseurlpath}/js/{$vs_lib}";
}
$vs_buf .= "<script src='{$vs_url}' type='text/javascript'></script>\n";
}
}
if (is_array($g_javascript_complementary)) {
foreach($g_javascript_complementary as $vs_code) {
$vs_buf .= "<script type='text/javascript'>\n".$vs_code."</script>\n";
}
}
return $vs_buf;
}
# --------------------------------------------------------------------------------
}
?> | Java |
<?php
/**
* @package Joomla.Site
* @subpackage mod_menu
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
<<<<<<< HEAD
// Note. It is important to remove spaces between elements.
$class = $item->anchor_css ? ' ' . $item->anchor_css : '';
$title = $item->anchor_title ? ' title="' . $item->anchor_title . '" ' : '';
=======
$title = $item->anchor_title ? ' title="' . $item->anchor_title . '"' : '';
$anchor_css = $item->anchor_css ? $item->anchor_css : '';
$linktype = $item->title;
>>>>>>> joomla/staging
if ($item->menu_image)
{
$linktype = JHtml::_('image', $item->menu_image, $item->title);
if ($item->params->get('menu_text', 1))
{
<<<<<<< HEAD
$item->params->get('menu_text', 1) ?
$linktype = '<img src="' . $item->menu_image . '" alt="' . $item->title . '" /><span class="image-title">' . $item->title . '</span> ' :
$linktype = '<img src="' . $item->menu_image . '" alt="' . $item->title . '" />';
}
else
{
$linktype = $item->title;
}
?>
<span class="separator<?php echo $class;?>"<?php echo $title; ?>>
<?php echo $linktype; ?>
</span>
=======
$linktype .= '<span class="image-title">' . $item->title . '</span>';
}
}
?>
<span class="separator <?php echo $anchor_css; ?>"<?php echo $title; ?>><?php echo $linktype; ?></span>
>>>>>>> joomla/staging
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Data;
using System.Windows.Controls.Primitives;
using System.Reflection;
using System.Windows.Threading;
using System.ComponentModel;
using System.Windows.Shapes;
namespace MusicCollectionWPF.Infra
{
public class CustoSlider : Slider
{
private Canvas _Matrix;
private Image _Cursor;
private Popup _autoToolTip;
private TextBlock _TB;
private Line _B;
private DispatcherTimer _Time;
private int _ImobileCount=0;
public event EventHandler<EventArgs> DragStarted;
public event EventHandler<EventArgs> DragCompleted;
public CustoSlider()
: base()
{
NeedTP = false;
_Time = new DispatcherTimer();
_Time.Interval = TimeSpan.FromMilliseconds(200);
_Time.Tick += Tick;
_Time.IsEnabled = false;
}
private void UpdateToolTip(double xp)
{
_TB.Text = AutoToolTipContent.Convert(ConvertToValue(xp), this.Minimum, this.Maximum);
FrameworkElement ch = (this._autoToolTip.Child as FrameworkElement);
bool force = false;
if (ch.ActualWidth==0)
{
_TB.Visibility=Visibility.Hidden;
_autoToolTip.IsOpen = true;
force = true;
}
this._autoToolTip.HorizontalOffset = xp - ch.ActualWidth / 2;
if (force)
{
_autoToolTip.IsOpen = false;
_TB.Visibility = Visibility.Visible;
}
}
private void UpdateToolTip(Point p)
{
UpdateToolTip(p.X);
}
private Point _Current;
private void Tick(object s, EventArgs ea)
{
Point nCurrent = Mouse.GetPosition(_Matrix);
if (nCurrent == _Current)
{
_ImobileCount++;
if (_ImobileCount==3)
OnImmobile(nCurrent);
}
else
{
_ImobileCount = 0;
if (_autoToolTip.IsOpen)
{
UpdateToolTip(nCurrent);
}
}
_Current = nCurrent;
}
private void OnImmobile(Point p)
{
if (!this.NeedTP)
return;
if (this._Trig)
return;
UpdateToolTip(p);
_autoToolTip.IsOpen = true;
}
private void ME(object s, EventArgs ea)
{
_Time.IsEnabled = true;
}
private void ML(object s, MouseEventArgs ea)
{
_Time.IsEnabled = false;
_autoToolTip.IsOpen = false;
}
private double ConvertToValue(double delta)
{
return Math.Min(this.Maximum, Math.Max(this.Minimum, this.Minimum + (delta * (this.Maximum - this.Minimum)) / _Matrix.ActualWidth));
}
private double ConvertToRealValue(double delta)
{
return Math.Min(_Matrix.ActualWidth, Math.Max(0, delta));
}
public double LineThickness
{
get { return (double)GetValue(LineTicknessProperty); }
set { SetValue(LineTicknessProperty, value); }
}
public static readonly DependencyProperty LineTicknessProperty = DependencyProperty.Register(
"LineThickness",
typeof(double),
typeof(CustoSlider),
new FrameworkPropertyMetadata(2D));
public bool FillLineVisible
{
get { return (bool)GetValue(FillLineVisibleProperty); }
set { SetValue(FillLineVisibleProperty, value); }
}
public static readonly DependencyProperty TickLineBrushProperty = DependencyProperty.Register(
"TickLineBrush", typeof(Brush), typeof(CustoSlider));
public Brush TickLineBrush
{
get { return (Brush)GetValue(TickLineBrushProperty); }
set { SetValue(TickLineBrushProperty, value); }
}
public static readonly DependencyProperty FillLineVisibleProperty = DependencyProperty.Register(
"FillLineVisible",
typeof(bool),
typeof(CustoSlider),
new FrameworkPropertyMetadata(false));
public ISliderMultiConverter AutoToolTipContent
{
get { return (ISliderMultiConverter)GetValue(AutoToolTipContentProperty); }
set { SetValue(AutoToolTipContentProperty, value); }
}
public static readonly DependencyProperty AutoToolTipContentProperty = DependencyProperty.Register(
"AutoToolTipContent",
typeof(ISliderMultiConverter),
typeof(CustoSlider),
new FrameworkPropertyMetadata(null, AutoToolTipPropertyChangedCallback));
private static void AutoToolTipPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CustoSlider cs = d as CustoSlider;
cs.NeedTP = true;
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
try
{
_Matrix = (Canvas)GetTemplateChild("Matrix");
this.MouseDown += Canvas_MouseDown;
_Cursor = (Image)GetTemplateChild("Cursor");
_Cursor.PreviewMouseLeftButtonDown += Image_PreviewMouseDown;
_Cursor.MouseLeftButtonUp += Image_MouseUp;
_Cursor.MouseMove += Image_MouseMove;
_B = (Line)GetTemplateChild("Bar");
_B.MouseEnter += ME;
_B.MouseLeave += ML;
_autoToolTip = GetTemplateChild("AutoToolTip") as Popup;
_TB = (TextBlock)GetTemplateChild("AutoToolTipContentTextBox");
}
catch (Exception)
{
}
}
protected override void OnRender(DrawingContext dc)
{
if (TickPlacement != TickPlacement.None)
{
Size size = new Size(base.ActualWidth, base.ActualHeight);
double MidHeight = size.Height / 2;
double BigCircle = size.Height / 5;
double SmallCircle = (BigCircle * 2) / 3;
dc.DrawEllipse(FillLineVisible? this.TickLineBrush: this.BorderBrush, new Pen(), new Point(10, MidHeight), BigCircle, BigCircle);
dc.DrawEllipse(this.BorderBrush, new Pen(), new Point(size.Width + 10, MidHeight), BigCircle, BigCircle);
int tickCount = (int)((this.Maximum - this.Minimum) / this.TickFrequency) -1;
Double tickFrequencySize = (size.Width * this.TickFrequency / (this.Maximum - this.Minimum));
for (int i = 0; i <tickCount; i++)
{
dc.DrawEllipse(this.BorderBrush, new Pen(), new Point(10 + (i + 1) * tickFrequencySize, MidHeight),
SmallCircle, SmallCircle);
}
}
base.OnRender(dc);
}
private async void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
if (_Trig)
return;
Point p = Mouse.GetPosition(_Matrix);
_autoToolTip.IsOpen = false;
_Trig = true;
var target = ConvertToValue(p.X);
await this.SmoothSetAsync(ValueProperty, target, TimeSpan.FromSeconds(0.1));
Value = target;
OnThumbDragCompleted(new DragCompletedEventArgs(0, 0, false));
if (DragCompleted != null)
DragCompleted(this, new EventArgs());
_Trig = false;
}
private void Image_MouseMove(object sender, MouseEventArgs e)
{
if (!_Trig)
return;
OnThumbDragDelta(e);
}
private bool _Trig = false;
private void Image_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
_Cursor.CaptureMouse();
e.Handled = true;
_Trig = true;
_autoToolTip.IsOpen = false;
OnThumbDragStarted(e);
if (DragStarted != null)
DragStarted(this, new EventArgs());
}
private void Image_MouseUp(object sender, MouseButtonEventArgs e)
{
if (!_Trig)
return;
_Cursor.ReleaseMouseCapture();
e.Handled = true;
_Trig = false;
OnThumbDragCompleted(e);
if (DragCompleted != null)
DragCompleted(this, new EventArgs());
}
private void OnThumbDragStarted(MouseEventArgs e)
{
if (NeedTP)
{
_autoToolTip.IsOpen = true;
UpdateToolTip(e.GetPosition(_Matrix));
}
}
private void OnThumbDragDelta(MouseEventArgs e)
{
Point p = e.GetPosition(_Matrix);
Value = ConvertToValue(p.X);
if (NeedTP)
{
UpdateToolTip(e.GetPosition(_Matrix));
}
}
public bool InDrag
{
get{ return _Trig; }
}
private void OnThumbDragCompleted(MouseEventArgs e)
{
Point p = e.GetPosition(_Matrix);
Value = ConvertToValue(p.X);
if (NeedTP)
{
_autoToolTip.IsOpen = false;
}
}
private bool NeedTP
{
get;
set;
}
protected void OnPropertyChanged(string pn)
{
if (PropertyChanged == null)
return;
PropertyChanged(this, new PropertyChangedEventArgs(pn));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
| Java |
// Copyright (c) 2000 Max-Planck-Institute Saarbruecken (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// You can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL: https://github.com/CGAL/cgal/blob/releases/CGAL-4.14.1/Partition_2/include/CGAL/Partition_2/Rotation_tree_2.h $
// $Id: Rotation_tree_2.h b33ab79 %aI Andreas Fabri
// SPDX-License-Identifier: GPL-3.0+
//
//
// Author(s) : Susan Hert <hert@mpi-sb.mpg.de>
/*
A rotation tree for computing the vertex visibility graph of a set of
non-intersecting segments in the plane (e.g. edges of a polygon).
Let $V$ be the set of segment endpoints and
let $p_{\infinity}$ ($p_{-\infinity}$) be a point with $y$ coordinate
$\infinity$ ($-\infinity$) and $x$ coordinate larger than all points
in $V$. The tree $G$ is a tree with node set
$V \cup \{p_{\infinity}, p_{-\infinity}\}$. Every node (except the one
corresponding to $p_{\infinity}$) has exactly one outgoing edge to the
point $q$ with the following property: $q$ is the first point encountered
when looking from $p$ in direction $d$ and rotating counterclockwise.
*/
#ifndef CGAL_ROTATION_TREE_H
#define CGAL_ROTATION_TREE_H
#include <CGAL/disable_warnings.h>
#include <CGAL/license/Partition_2.h>
#include <CGAL/vector.h>
#include <CGAL/Partition_2/Rotation_tree_node_2.h>
#include <boost/bind.hpp>
namespace CGAL {
template <class Traits_>
class Rotation_tree_2 : public internal::vector< Rotation_tree_node_2<Traits_> >
{
public:
typedef Traits_ Traits;
typedef Rotation_tree_node_2<Traits> Node;
typedef typename internal::vector<Node>::iterator Self_iterator;
typedef typename Traits::Point_2 Point_2;
using internal::vector< Rotation_tree_node_2<Traits_> >::push_back;
class Greater {
typename Traits::Less_xy_2 less;
typedef typename Traits::Point_2 Point;
public:
Greater(typename Traits::Less_xy_2 less) : less(less) {}
template <typename Point_like>
bool operator()(const Point_like& p1, const Point_like& p2) {
return less(Point(p2), Point(p1));
}
};
// constructor
template<class ForwardIterator>
Rotation_tree_2(ForwardIterator first, ForwardIterator beyond)
{
for (ForwardIterator it = first; it != beyond; it++)
push_back(*it);
Greater greater (Traits().less_xy_2_object());
std::sort(this->begin(), this->end(), greater);
std::unique(this->begin(), this->end());
// front() is the point with the largest x coordinate
// push the point p_minus_infinity; the coordinates should never be used
push_back(Point_2( 1, -1));
// push the point p_infinity; the coordinates should never be used
push_back(Point_2(1, 1));
_p_inf = this->end(); // record the iterators to these extreme points
_p_inf--;
_p_minus_inf = _p_inf;
_p_minus_inf--;
Self_iterator child;
// make p_minus_inf a child of p_inf
set_rightmost_child(_p_minus_inf, _p_inf);
child = this->begin(); // now points to p_0
while (child != _p_minus_inf) // make all points children of p_minus_inf
{
set_rightmost_child(child, _p_minus_inf);
child++;
}
}
// the point that comes first in the right-to-left ordering is first
// in the ordering, after the auxilliary points p_minus_inf and p_inf
Self_iterator rightmost_point_ref()
{
return this->begin();
}
Self_iterator right_sibling(Self_iterator p)
{
if (!(*p).has_right_sibling()) return this->end();
return (*p).right_sibling();
}
Self_iterator left_sibling(Self_iterator p)
{
if (!(*p).has_left_sibling()) return this->end();
return (*p).left_sibling();
}
Self_iterator rightmost_child(Self_iterator p)
{
if (!(*p).has_children()) return this->end();
return (*p).rightmost_child();
}
Self_iterator parent(Self_iterator p)
{
if (!(*p).has_parent()) return this->end();
return (*p).parent();
}
bool parent_is_p_infinity(Self_iterator p)
{
return parent(p) == _p_inf;
}
bool parent_is_p_minus_infinity(Self_iterator p)
{
return parent(p) == _p_minus_inf;
}
// makes *p the parent of *q
void set_parent (Self_iterator p, Self_iterator q)
{
CGAL_assertion(q != this->end());
if (p == this->end())
(*q).clear_parent();
else
(*q).set_parent(p);
}
// makes *p the rightmost child of *q
void set_rightmost_child(Self_iterator p, Self_iterator q);
// makes *p the left sibling of *q
void set_left_sibling(Self_iterator p, Self_iterator q);
// makes *p the right sibling of *q
void set_right_sibling(Self_iterator p, Self_iterator q);
// NOTE: this function does not actually remove the node p from the
// list; it only reorganizes the pointers so this node is not
// in the tree structure anymore
void erase(Self_iterator p);
private:
Self_iterator _p_inf;
Self_iterator _p_minus_inf;
};
}
#include <CGAL/Partition_2/Rotation_tree_2_impl.h>
#include <CGAL/enable_warnings.h>
#endif // CGAL_ROTATION_TREE_H
// For the Emacs editor:
// Local Variables:
// c-basic-offset: 3
// End:
| Java |
# Copyright (C) 2008-2013 Zentyal S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
use strict;
use warnings;
package EBox::Samba::CGI::EditUser;
use base 'EBox::CGI::ClientPopupBase';
use EBox::Global;
use EBox::Samba;
use EBox::Samba::User;
use EBox::Samba::Group;
use EBox::Gettext;
use EBox::Exceptions::External;
sub new
{
my $class = shift;
my $self = $class->SUPER::new('template' => '/samba/edituser.mas', @_);
bless($self, $class);
return $self;
}
sub _process
{
my ($self) = @_;
my $global = EBox::Global->getInstance();
my $users = $global->modInstance('samba');
$self->{'title'} = __('Users');
my @args = ();
$self->_requireParam('dn', 'dn');
my $dn = $self->unsafeParam('dn');
my $user = new EBox::Samba::User(dn => $dn);
my $components = $users->allUserAddOns($user);
my $usergroups = $user->groups(internal => 0, system => 1);
my $remaingroups = $user->groupsNotIn(internal => 0, system => 1);
my $editable = $users->editableMode();
push(@args, 'user' => $user);
push(@args, 'usergroups' => $usergroups);
push(@args, 'remaingroups' => $remaingroups);
push(@args, 'components' => $components);
push(@args, 'slave' => not $editable);
$self->{params} = \@args;
if ($self->param('edit')) {
my $setText = undef;
$self->{json} = { success => 0 };
$self->_requireParam('User_quota_selected');
my $quotaTypeSelected = $self->param('User_quota_selected');
my $quota;
if ($quotaTypeSelected eq 'quota_disabled') {
$quota = 0;
} elsif ($quotaTypeSelected eq 'quota_size') {
$quota = $self->param('User_quota_size');
}
if (defined ($quota) and $user->hasValue('objectClass', 'systemQuotas')) {
$user->set('quota', $quota, 1);
}
my $addMail;
my $delMail;
if ($editable) {
$self->_requireParamAllowEmpty('givenname', __('first name'));
$self->_requireParamAllowEmpty('surname', __('last name'));
$self->_requireParamAllowEmpty('displayname', __('display name'));
$self->_requireParamAllowEmpty('description', __('description'));
$self->_requireParamAllowEmpty('mail', __('E-Mail'));
$self->_requireParamAllowEmpty('password', __('password'));
$self->_requireParamAllowEmpty('repassword', __('confirm password'));
my $givenName = $self->param('givenname');
my $surname = $self->param('surname');
my $disabled = $self->param('disabled');
my $displayname = $self->unsafeParam('displayname');
if (length ($displayname)) {
$user->set('displayName', $displayname, 1);
$setText = $user->name() . " ($displayname)";
} else {
$user->delete('displayName', 1);
$setText = $user->name();
}
my $description = $self->unsafeParam('description');
if (length ($description)) {
$user->set('description', $description, 1);
} else {
$user->delete('description', 1);
}
my $mail = $self->unsafeParam('mail');
my $oldMail = $user->get('mail');
if ($mail) {
$mail = lc $mail;
if (not $oldMail) {
$addMail = $mail;
} elsif ($mail ne $oldMail) {
$delMail = 1;
$addMail = $mail;
}
} elsif ($oldMail) {
$delMail = 1;
}
my $mailMod = $global->modInstance('mail');
if ($delMail) {
if ($mailMod and $mailMod->configured()) {
$mailMod->_ldapModImplementation()->delUserAccount($user);
} else {
$user->delete('mail', 1);
}
}
if ($addMail) {
if ($mailMod and $mailMod->configured()) {
$mailMod->_ldapModImplementation()->setUserAccount($user, $addMail);
} else {
$user->checkMail($addMail);
$user->set('mail', $addMail, 1);
}
}
$user->set('givenname', $givenName, 1) if ($givenName);
$user->set('sn', $surname, 1) if ($surname);
$user->setDisabled($disabled, 1);
# Change password if not empty
my $password = $self->unsafeParam('password');
if ($password) {
my $repassword = $self->unsafeParam('repassword');
if ($password ne $repassword){
throw EBox::Exceptions::External(__('Passwords do not match.'));
}
$user->changePassword($password, 1);
}
}
$user->save();
$self->{json}->{success} = 1;
$self->{json}->{msg} = __('User updated');
if ($setText) {
$self->{json}->{set_text} = $setText;
}
if ($addMail) {
$self->{json}->{mail} = $addMail;
} elsif ($delMail) {
$self->{json}->{mail} = '';
}
} elsif ($self->param('addgrouptouser')) {
$self->{json} = { success => 0 };
$self->_requireParam('addgroup', __('group'));
my @groups = $self->unsafeParam('addgroup');
foreach my $gr (@groups) {
my $group = new EBox::Samba::Group(samAccountName => $gr);
$user->addGroup($group);
}
$self->{json}->{success} = 1;
} elsif ($self->param('delgroupfromuser')) {
$self->{json} = { success => 0 };
$self->_requireParam('delgroup', __('group'));
my @groups = $self->unsafeParam('delgroup');
foreach my $gr (@groups){
my $group = new EBox::Samba::Group(samAccountName => $gr);
$user->removeGroup($group);
}
$self->{json}->{success} = 1;
} elsif ($self->param('groupInfo')) {
$self->{json} = {
success => 1,
member => [ map { $_->name } @{ $usergroups }],
noMember => [ map { $_->name } @{ $remaingroups }],
};
}
}
1;
| Java |
/*****************************************************************************/
/* */
/* Ittiam 802.11 MAC SOFTWARE */
/* */
/* ITTIAM SYSTEMS PVT LTD, BANGALORE */
/* COPYRIGHT(C) 2005 */
/* */
/* This program is proprietary to Ittiam Systems Private Limited and */
/* is protected under Indian Copyright Law as an unpublished work. Its use */
/* and disclosure is limited by the terms and conditions of a license */
/* agreement. It may not be copied or otherwise reproduced or disclosed to */
/* persons outside the licensee's organization except in accordance with the*/
/* terms and conditions of such an agreement. All copies and */
/* reproductions shall be the property of Ittiam Systems Private Limited and*/
/* must bear this notice in its entirety. */
/* */
/*****************************************************************************/
/*****************************************************************************/
/* */
/* File Name : common.c */
/* */
/* Description : This file contains the functions used by both AP/STA */
/* modes in MAC. */
/* */
/* List of Functions : set_dscr_fn */
/* get_dscr_fn */
/* */
/* Issues / Problems : None */
/* */
/*****************************************************************************/
/*****************************************************************************/
/* File Includes */
/*****************************************************************************/
#include "common.h"
#include "mh.h"
#include "csl_linux.h"
#include "trout_share_mem.h"
#ifdef MAC_HW_UNIT_TEST_MODE
#include "mh_test.h"
#endif /* MAC_HW_UNIT_TEST_MODE */
/*****************************************************************************/
/* Global Variables */
/*****************************************************************************/
UWORD32 g_calib_cnt = DEFAULT_CALIB_COUNT;
extern UWORD32 g_done_wifi_suspend;
#ifdef DEBUG_MODE
mac_stats_t g_mac_stats = {0};
reset_stats_t g_reset_stats = {0};
UWORD8 g_enable_debug_print = 1;
UWORD8 g_11n_print_stats = 0;
#endif /* DEBUG_MODE */
#ifdef MEM_DEBUG_MODE
mem_stats_t g_mem_stats = {0};
#endif /* MEM_DEBUG_MODE */
#ifdef MAC_HW_UNIT_TEST_MODE
#endif /* MAC_HW_UNIT_TEST_MODE */
#ifdef DSCR_MACROS_NOT_DEFINED
/*****************************************************************************/
/* */
/* Function Name : set_dscr_fn */
/* */
/* Description : This function modifies the packet descriptor with the */
/* new specified value. The descriptor field to be modified */
/* is specified by the descriptor offset and width */
/* */
/* Inputs : 1) Offset of the descriptor field */
/* 2) Width of the descriptor field */
/* 3) Pointer to the packet descriptor to be modified */
/* 4) The new value for the descriptor field */
/* */
/* Globals : None */
/* */
/* Processing : Modifies the specified descriptor with the supplied */
/* value. */
/* */
/* Outputs : None */
/* Returns : None */
/* Issues : None */
/* */
/*****************************************************************************/
void set_dscr_fn(UWORD8 offset, UWORD16 width, UWORD32 *ptr, UWORD32 value)
{
UWORD32 mask_inverse = 0;
UWORD32 mask = 0;
UWORD32 temp = 0;
UWORD32 shift_offset = 32 - width - offset;
#ifdef DEBUG_MODE
if((width + offset) > 32)
{
/* Signal Erroneous input */
}
#endif /* DEBUG_MODE */
/* Calculate the inverse of the Mask */
if(width < 32)
mask_inverse = ((1 << width) - 1) << shift_offset;
else
mask_inverse = 0xFFFFFFFF;
/* Generate the mask */
mask = ~mask_inverse;
/* Read the descriptor word in little endian format */
temp = convert_to_le(*ptr);
/* Updating the value of the descriptor field with the help of masks */
temp = ((value << shift_offset) & mask_inverse) | (temp & mask);
/* Swap the byte order in the word if required for endian-ness change */
*ptr = convert_to_le(temp);
}
/*****************************************************************************/
/* */
/* Function Name : get_dscr_fn */
/* */
/* Description : This function reads a word32 location to extract a */
/* specified descriptor field.of specified width. */
/* */
/* Inputs : 1) Offset of the descriptor field in the 32 bit boundary */
/* 2) Width of the desired descriptor field */
/* 3) Pointer to the word32 location of the field */
/* */
/* Globals : None */
/* */
/* Processing : Reads the descriptor for the specific field and returns */
/* the value. */
/* */
/* Outputs : None */
/* */
/* Returns : Descriptor field value */
/* */
/* Issues : None */
/* */
/*****************************************************************************/
UWORD32 get_dscr_fn(UWORD8 offset, UWORD16 width, UWORD32 *ptr)
{
UWORD32 mask = 0;
UWORD32 temp = 0;
UWORD32 value = 0;
UWORD32 shift_offset = 32 - width - offset;
#ifdef DEBUG_MODE
if((width + offset) > 32)
{
/* Signal Erroneous input */
}
#endif /* DEBUG_MODE */
/* Calculate the Mask */
if(width < 32)
mask = ((1 << width) - 1) << shift_offset;
else
mask = 0xFFFFFFFF;
/* Swap the byte order in the word if required for endian-ness change */
temp = convert_to_le(*ptr);
/* Obtain the value of the descriptor field with the help of masks */
value = (temp & mask) >> shift_offset;
return value;
}
#endif /* DSCR_MACROS_NOT_DEFINED */
#ifdef MWLAN
/*****************************************************************************/
/* */
/* Function Name : itm_memset */
/* */
/* Description : This function sets the specified number of bytes in the */
/* buffer to the required value. The functionality is */
/* similar to the standard memset function. The new */
/* implementation was required due to the bug seen when */
/* using memset function across the bridge on MWLAN. */
/* */
/* Inputs : 1) Pointer to the buffer. */
/* 2) Value of character to set */
/* 3) Number of characters to set. */
/* */
/* Globals : None */
/* */
/* Processing : */
/* */
/* Outputs : None */
/* */
/* Returns : Pointer to the buffer */
/* */
/* Issues : None */
/* */
/*****************************************************************************/
void *itm_memset(void *buff, UWORD8 val, UWORD32 num)
{
UWORD8 *cbuff = (UWORD8 *)buff;
if(num < 20)
while(num--)
*cbuff++ = val;
else
{
UWORD32 *wbuff = NULL;
UWORD32 wval = val;
UWORD32 temp = 0;
temp = (UWORD32)cbuff & 0x3;
/* Unaligned buffer */
num -= temp;
while(temp--)
*cbuff++ = val;
/* Word transfers */
wval += (wval << 8) + (wval << 16) + (wval << 24);
wbuff = (UWORD32 *)cbuff;
while(num > 3)
{
*wbuff++ = wval;
num -= 4;
}
/* Unaligned length */
cbuff = (UWORD8 *)wbuff;
while(num--)
*cbuff++ = val;
}
return buff;
}
#endif /* MWLAN */
/*****************************************************************************/
/* */
/* Function Name : calibrate_delay_loop */
/* */
/* Description : This function calibrates the delay loop counter using */
/* MAC H/w TSF Timer . */
/* */
/* Inputs : None */
/* */
/* Globals : g_calib_cnt */
/* */
/* Processing : MAC H/w version register is read a fixed number of times */
/* to introduce delay in S/w. This function calibrates this */
/* delay mechanism. It updates the global variable */
/* (g_calib_cnt) which holds the number of times the */
/* version register should be read to introduce a delay of */
/* 10us. */
/* */
/* Outputs : None */
/* Returns : None */
/* Issues : None */
/* */
/*****************************************************************************/
void calibrate_delay_loop(void)
{
UWORD32 i = 0;
UWORD32 entry_time = 0;
UWORD32 exit_time = 0;
BOOL_T pa_enabled = BFALSE;
BOOL_T tbtt_mask = BFALSE;
UWORD32 tsf_ctrl_bkup = 0;
UWORD32 calib_thresh = 0;
TROUT_FUNC_ENTER;
/* Backup the registers which will be used for the calibration process */
pa_enabled = is_machw_enabled();
tbtt_mask = is_machw_tbtt_int_masked();
tsf_ctrl_bkup = get_machw_tsf_ctrl();
critical_section_start();
/* PA is disabled but TBTT Interrupts can still come. Mask it. */
disable_machw_phy_and_pa();
mask_machw_tbtt_int();
set_machw_tsf_start();
set_machw_tsf_beacon_tx_suspend_enable();
/* Initialize Calibration Parameters */
calib_thresh = 1000;
entry_time = get_machw_tsf_timer_lo();
for(i = 0; i < calib_thresh; i++)
{
GET_TIME(); //modified by chengwg.
}
exit_time = get_machw_tsf_timer_lo();
/* Restore the Backed-up registers */
if(pa_enabled == BTRUE)
enable_machw_phy_and_pa();
if(tbtt_mask == BFALSE)
unmask_machw_tbtt_int();
set_machw_tsf_ctrl(tsf_ctrl_bkup);
critical_section_end();
/* The Delay Calibration Count is computed to provide a delay of 10us */
if(exit_time > entry_time)
g_calib_cnt = ((calib_thresh+2)*10)/(exit_time-entry_time) + 1;
TROUT_DBG4("Delay Calibration: Cnt=%d Delay=%d Calib_Cnt=%d\n",calib_thresh+2,
(exit_time-entry_time), g_calib_cnt);
TROUT_FUNC_EXIT;
}
#ifdef COMBO_SCAN
void calibrate_delay_loop_plus(void)
{
UWORD32 i = 0;
UWORD32 entry_time = 0;
UWORD32 exit_time = 0;
BOOL_T pa_enabled = BFALSE;
BOOL_T tbtt_mask = BFALSE;
UWORD32 tsf_ctrl_bkup = 0;
UWORD32 calib_thresh = 0;
TROUT_FUNC_ENTER;
/* Backup the registers which will be used for the calibration process */
pa_enabled = is_machw_enabled();
tbtt_mask = is_machw_tbtt_int_masked();
tsf_ctrl_bkup = get_machw_tsf_ctrl();
critical_section_start();
/* PA is disabled but TBTT Interrupts can still come. Mask it. */
disable_machw_phy_and_pa();
mask_machw_tbtt_int();
set_machw_tsf_start();
set_machw_tsf_beacon_tx_suspend_enable();
/* Initialize Calibration Parameters */
calib_thresh = 1000;
entry_time = get_machw_tsf_timer_lo();
for(i = 0; i < calib_thresh; i++)
{
GET_TIME(); //modified by chengwg.
}
exit_time = get_machw_tsf_timer_lo();
/* Restore the Backed-up registers */
if(pa_enabled == BTRUE)
enable_machw_phy_and_pa();
if(tbtt_mask == BFALSE)
unmask_machw_tbtt_int();
set_machw_tsf_ctrl(tsf_ctrl_bkup);
critical_section_end();
/* The Delay Calibration Count is computed to provide a delay of 10us */
//if(exit_time > entry_time)
//g_calib_cnt = ((calib_thresh+2)*10)/(exit_time-entry_time) + 1;
//TROUT_DBG4("Delay Calibration: Cnt=%d Delay=%d Calib_Cnt=%d\n",calib_thresh+2,
//(exit_time-entry_time), g_calib_cnt);
TROUT_FUNC_EXIT;
}
#endif
/*****************************************************************************/
/* */
/* Function Name : add_calib_delay */
/* */
/* Description : This function provides a minimum S/w delay of the */
/* required time specified in units of 10us */
/* */
/* Inputs : 1) The required delay in units of 10us. i.e. Input 10 */
/* will provide a delay of 100us */
/* */
/* Globals : g_calib_cnt */
/* */
/* Processing : The MAC H/w version number is read continuously for a */
/* precomputed number of times to provide the required */
/* delay. */
/* */
/* Outputs : None */
/* */
/* Returns : None */
/* */
/* Issues : None */
/* */
/*****************************************************************************/
void add_calib_delay(UWORD32 delay)
{
UWORD32 i = 0;
// UWORD32 j = 0;
UWORD32 delay_thresh = g_calib_cnt * delay;
for(i = 0; i < delay_thresh; i++)
//j += get_machw_pa_ver();
//j += (*(volatile UWORD32 *)HOST_DELAY_FOR_TROUT_PHY); //add by chengq.
GET_TIME();
}
#ifdef DEBUG_MODE
void print_ba_debug_stats(void)
{
UWORD32 idx = 0;
PRINTK("BA Frames Rxd = %d\n\r", g_mac_stats.babarxd);
PRINTK("BAR Frames successfully Txd = %d\n\r", g_mac_stats.babartxd);
PRINTK("BAR Frames Rxd = %d\n\r", g_mac_stats.babarrxd);
PRINTK("Data Frames retransmitted = %d\n\r", g_mac_stats.badatretx);
PRINTK("Times Window is moved = %d\n\r", g_mac_stats.bawinmove);
PRINTK("BAR Tx-Failures = %d\n\r", g_mac_stats.babarfail);
PRINTK("Data Tx-Failures = %d\n\r", g_mac_stats.badatfail);
PRINTK("Missing Buffers = %d\n\r", g_mac_stats.babufmiss);
PRINTK("Frames deleted during Buffer cleanup = %d\n\r", g_mac_stats.badatclnup);
PRINTK("Pending Frames discarded = %d\n\r", g_mac_stats.bapenddrop);
PRINTK("Frames Txd from the Pending Q = %d\n\r", g_mac_stats.bapendingtxwlantxd);
PRINTK("Stale BA frames received = %d\n\r", g_mac_stats.baoldbarxd);
PRINTK("Stale BA frames received = %d\n\r", g_mac_stats.baoldbarrxd);
PRINTK("Frames received out of window and hence droped = %d\n\r",g_mac_stats.barxdatoutwin);
PRINTK("Re-queue failures = %d\n\r", g_mac_stats.bartrqfail);
PRINTK("Number of blocks Qed = %d\n\r", g_mac_stats.banumblks);
PRINTK("Number of Frames Qed = %d\n\r", g_mac_stats.banumqed);
PRINTK("Number of times the pending Q was empty while enqueing = %d\n\r",g_mac_stats.baemptyQ);
PRINTK("Num of times grp=%d\n\r", g_mac_stats.num_buffto);
PRINTK("ba_num_dq=%d\n\r", g_mac_stats.ba_num_dq);
PRINTK("ba_num_dqed=%d\n\r", g_mac_stats.ba_num_dqed);
PRINTK("batxfba=%d\n\r", g_mac_stats.batxfba);
for(idx = 0; idx < 10; idx++)
PRINTK("batemp[%d] = %d\n\r", idx, g_mac_stats.batemp[idx]);
}
UWORD8 print_mem_stats(void)
{
UWORD8 print_flag = 0;
#ifdef MEM_DEBUG_MODE
print_flag |= printe("nosizeallocexc", g_mem_stats.nosizeallocexc);
print_flag |= printe("nofreeallocexc", g_mem_stats.nofreeallocexc);
print_flag |= printe("reallocexc", g_mem_stats.reallocexc);
print_flag |= printe("corruptallocexc", g_mem_stats.corruptallocexc);
print_flag |= printe("nullfreeexc", g_mem_stats.nullfreeexc);
print_flag |= printe("oobfreeexc", g_mem_stats.oobfreeexc);
print_flag |= printe("refreeexc", g_mem_stats.refreeexc);
print_flag |= printe("corruptfreeexc", g_mem_stats.corruptfreeexc);
print_flag |= printe("invalidfreeexc", g_mem_stats.invalidfreeexc);
print_flag |= printe("excessfreeexc", g_mem_stats.excessfreeexc);
print_flag |= printe("nulladdexc", g_mem_stats.nulladdexc);
print_flag |= printe("oobaddexc", g_mem_stats.oobaddexc);
print_flag |= printe("freeaddexc", g_mem_stats.freeaddexc);
print_flag |= printe("invalidaddexc", g_mem_stats.invalidaddexc);
print_flag |= printe("excessaddexc", g_mem_stats.excessaddexc);
print_flag |= printe("nofreeDscrallocexc[0]", g_mem_stats.nofreeDscrallocexc[0]);
print_flag |= printe("nofreeDscrallocexc[1]", g_mem_stats.nofreeDscrallocexc[1]);
print_flag |= printe("nofreePktallocexc[0]", g_mem_stats.nofreePktallocexc[0]);
print_flag |= printe("nofreePktallocexc[1]", g_mem_stats.nofreePktallocexc[1]);
print_flag |= printe("nofreePktallocexc[2]", g_mem_stats.nofreePktallocexc[2]);
print_flag |= printe("nofreePktallocexc[3]", g_mem_stats.nofreePktallocexc[3]);
print_flag |= printe("nofreePktallocexc[4]", g_mem_stats.nofreePktallocexc[4]);
print_flag |= printe("nofreeLocalallocexc[0]", g_mem_stats.nofreeLocalallocexc[0]);
print_flag |= printe("nofreeLocalallocexc[1]", g_mem_stats.nofreeLocalallocexc[1]);
print_flag |= printe("nofreeLocalallocexc[2]", g_mem_stats.nofreeLocalallocexc[2]);
print_flag |= printe("nofreeLocalallocexc[3]", g_mem_stats.nofreeLocalallocexc[3]);
print_flag |= printe("nofreeLocalallocexc[4]", g_mem_stats.nofreeLocalallocexc[4]);
print_flag |= printe("nofreeLocalallocexc[5]", g_mem_stats.nofreeLocalallocexc[5]);
print_flag |= printe("nofreeLocalallocexc[6]", g_mem_stats.nofreeLocalallocexc[6]);
print_flag |= printe("nofreeLocalallocexc[7]", g_mem_stats.nofreeLocalallocexc[7]);
print_flag |= printe("nofreeEventallocexc", g_mem_stats.nofreeEventallocexc);
/* Print the size of the maximum Shared memory used and reset it after that */
PRINTK("Max Scratch Memory Utilized = %d", get_max_scratch_mem_usage());
reset_scratch_mem_usage();
#endif /* MEM_DEBUG_MODE */
return print_flag;
}
void print_debug_stats(void)
{
UWORD8 i = 0;
#ifdef MEM_DEBUG_MODE
PRINTK("Memory Statistics\n\r");
PRINTK("sdalloc = %d\n\r",g_mem_stats.sdalloc);
PRINTK("sdfree = %d\n\r",g_mem_stats.sdfree);
PRINTK("sdtotalfree = %d\n\r",g_mem_stats.sdtotalfree);
PRINTK("spalloc = %d\n\r",g_mem_stats.spalloc);
PRINTK("spfree = %d\n\r",g_mem_stats.spfree);
PRINTK("sptotalfree = %d\n\r",g_mem_stats.sptotalfree);
PRINTK("lalloc = %d\n\r",g_mem_stats.lalloc);
PRINTK("lfree = %d\n\r",g_mem_stats.lfree);
PRINTK("ltotalfree = %d\n\r",g_mem_stats.ltotalfree);
PRINTK("ealloc = %d\n\r",g_mem_stats.ealloc);
PRINTK("efree = %d\n\r",g_mem_stats.efree);
PRINTK("etotalfree = %d\n\r",g_mem_stats.etotalfree);
PRINTK("nosizeallocexc = %d\n\r",g_mem_stats.nosizeallocexc);
PRINTK("nofreeallocexc = %d\n\r",g_mem_stats.nofreeallocexc);
PRINTK("reallocexc = %d\n\r",g_mem_stats.reallocexc);
PRINTK("corruptallocexc = %d\n\r",g_mem_stats.corruptallocexc);
PRINTK("nullfreeexc = %d\n\r",g_mem_stats.nullfreeexc);
PRINTK("oobfreeexc = %d\n\r",g_mem_stats.oobfreeexc);
PRINTK("refreeexc = %d\n\r",g_mem_stats.refreeexc);
PRINTK("corruptfreeexc = %d\n\r",g_mem_stats.corruptfreeexc);
PRINTK("invalidfreeexc = %d\n\r",g_mem_stats.invalidfreeexc);
PRINTK("excessfreeexc = %d\n\r",g_mem_stats.excessfreeexc);
PRINTK("nulladdexc = %d\n\r",g_mem_stats.nulladdexc);
PRINTK("oobaddexc = %d\n\r",g_mem_stats.oobaddexc);
PRINTK("freeaddexc = %d\n\r",g_mem_stats.freeaddexc);
PRINTK("invalidaddexc = %d\n\r",g_mem_stats.invalidaddexc);
PRINTK("excessaddexc = %d\n\r",g_mem_stats.excessaddexc);
PRINTK("nofreeDscrallocexc[0] = %d\n\r",g_mem_stats.nofreeDscrallocexc[0]);
PRINTK("nofreeDscrallocexc[1] = %d\n\r",g_mem_stats.nofreeDscrallocexc[1]);
for(i = 0; i < 5; i++)
PRINTK("nofreePktallocexc[%d] = %d\n\r",i,
g_mem_stats.nofreePktallocexc[i]);
for(i = 0; i < 8; i++)
PRINTK("nofreeLocalallocexc[%d] = %d\n\r",i,
g_mem_stats.nofreeLocalallocexc[i]);
PRINTK("nofreeEventallocexc = %d\n\r",
g_mem_stats.nofreeEventallocexc);
#endif /* MEM_DEBUG_MODE */
PRINTK("\nMAC Statistics\n\r");
#ifndef MAC_HW_UNIT_TEST_MODE
PRINTK("itbtt = %d\n\r",g_mac_stats.itbtt);
PRINTK("itxc = %d\n\r",g_mac_stats.itxc);
PRINTK("irxc = %d\n\r",g_mac_stats.irxc);
PRINTK("ihprxc = %d\n\r",g_mac_stats.ihprxc);
PRINTK("ierr = %d\n\r",g_mac_stats.ierr);
PRINTK("ideauth = %d\n\r",g_mac_stats.ideauth);
PRINTK("icapend = %d\n\r",g_mac_stats.icapend);
PRINTK("enpmsdu = %d\n\r",g_mac_stats.enpmsdu);
PRINTK("erxqemp = %d\n\r",g_mac_stats.erxqemp);
PRINTK("etxsus1machang = %d\n\r",g_mac_stats.etxsus1machang);
PRINTK("etxsus1phyhang = %d\n\r",g_mac_stats.etxsus1phyhang);
PRINTK("etxsus3 = %d\n\r",g_mac_stats.etxsus3);
PRINTK("ebus = %d\n\r",g_mac_stats.ebus);
PRINTK("ebwrsig = %d\n\r",g_mac_stats.ebwrsig);
PRINTK("emsaddr = %d\n\r",g_mac_stats.emsaddr);
PRINTK("etxfifo = %d\n\r",g_mac_stats.etxfifo);
PRINTK("erxfifo = %d\n\r",g_mac_stats.erxfifo);
PRINTK("ehprxfifo = %d\n\r",g_mac_stats.ehprxfifo);
PRINTK("etxqempt = %d\n\r",g_mac_stats.etxqempt);
PRINTK("edmanoerr = %d\n\r",g_mac_stats.edmanoerr);
PRINTK("etxcenr = %d\n\r",g_mac_stats.etxcenr);
PRINTK("erxcenr = %d\n\r",g_mac_stats.erxcenr);
PRINTK("esgaf = %d\n\r",g_mac_stats.esgaf);
PRINTK("eother = %d\n\r",g_mac_stats.eother);
PRINTK("qatxp = %d\n\r",g_mac_stats.qatxp);
PRINTK("qdtxp = %d\n\r",g_mac_stats.qdtxp);
#else /* MAC_HW_UNIT_TEST_MODE */
PRINTK("rxci = %d\n\r",g_test_stats.rxci);
PRINTK("hprxci = %d\n\r",g_test_stats.hprxci);
PRINTK("txci = %d\n\r",g_test_stats.txci);
PRINTK("tbtti = %d\n\r",g_test_stats.tbtti);
PRINTK("erri = %d\n\r",g_test_stats.erri);
PRINTK("capei = %d\n\r",g_test_stats.capei);
PRINTK("uki = %d\n\r",g_test_stats.uki);
PRINTK("err.enpmsdu = %d\n\r",g_test_stats.exp.enpmsdu);
PRINTK("err.erxqemp = %d\n\r",g_test_stats.exp.erxqemp);
PRINTK("err.emsaddr = %d\n\r",g_test_stats.exp.emsaddr);
PRINTK("err.etxsus1machang = %d\n\r",g_test_stats.exp.etxsus1machang);
PRINTK("err.etxsus1phyhang = %d\n\r",g_test_stats.exp.etxsus1phyhang);
PRINTK("err.etxsus3 = %d\n\r",g_test_stats.exp.etxsus3);
PRINTK("err.ebus = %d\n\r",g_test_stats.exp.ebus);
PRINTK("err.ebwrsig = %d\n\r",g_test_stats.exp.ebwrsig);
PRINTK("err.etxqempt = %d\n\r",g_test_stats.exp.etxqempt);
PRINTK("err.edmanoerr = %d\n\r",g_test_stats.exp.edmanoerr);
PRINTK("err.etxcenr = %d\n\r",g_test_stats.exp.etxcenr);
PRINTK("err.erxcenr = %d\n\r",g_test_stats.exp.erxcenr);
PRINTK("err.esgaf = %d\n\r",g_test_stats.exp.esgaf);
PRINTK("err.etxfifo = %d\n\r",g_test_stats.exp.etxfifo);
PRINTK("err.erxfifo = %d\n\r",g_test_stats.exp.erxfifo);
PRINTK("err.eother = %d\n\r",g_test_stats.exp.eother);
#endif /* MAC_HW_UNIT_TEST_MODE */
}
void print_build_flags(void)
{
#ifdef ETHERNET_HOST
PRINTK("ETHERNET_HOST\n\r");
#endif /* ETHERNET_HOST */
#ifdef GENERIC_HOST
PRINTK("GENERIC_HOST\n\r");
#endif /* GENERIC_HOST */
#ifdef PHY_802_11n
PRINTK("PHY_802_11n\n\r");
#endif /* PHY_802_11n */
#ifdef GENERIC_PHY
PRINTK("GENERIC_PHY\n\r");
#endif /* GENERIC_PHY */
#ifdef ITTIAM_PHY
PRINTK("ITTIAM_PHY\n\r");
#endif /* ITTIAM_PHY */
#ifdef BSS_ACCESS_POINT_MODE
PRINTK("BSS_ACCESS_POINT_MODE\n\r");
#endif /* BSS_ACCESS_POINT_MODE */
#ifdef IBSS_BSS_STATION_MODE
PRINTK("IBSS_BSS_STATION_MODE\n\r");
#endif /* IBSS_BSS_STATION_MODE */
#ifdef MAC_HW_UNIT_TEST_MODE
PRINTK("MAC_HW_UNIT_TEST_MODE \n\r");
#endif /* MAC_HW_UNIT_TEST_MODE */
#ifdef MAC_802_11I
PRINTK("MAC_802_11I \n\r");
#endif /* MAC_802_11I */
#ifdef SUPP_11I
PRINTK("SUPP_11I \n\r");
#endif /* SUPP_11I */
#ifdef MAC_WMM
PRINTK("MAC_WMM \n\r");
#endif /* MAC_WMM */
#ifdef MAC_802_11N
PRINTK("MAC_802_11N \n\r");
#endif /* MAC_802_11N */
#ifdef MAC_802_1X
PRINTK("MAC_802_1X \n\r");
#endif /* MAC_802_1X */
#ifdef MAC_802_11H
PRINTK("MAC_802_11H \n\r");
#endif /* MAC_802_11H */
#ifdef GENERIC_RF
PRINTK("GENERIC_RF\n\r");
#endif /* GENERIC_RF */
#ifdef RF_MAXIM_ITTIAM
PRINTK("RF_MAXIM_ITTIAM \n\r");
#endif /* RF_MAXIM_ITTIAM */
// 20120709 caisf masked, merged ittiam mac v1.2 code
#if 0
#ifdef RF_AIROHA_ITTIAM
PRINTK("RF_AIROHA_ITTIAM \n\r");
#endif /* RF_AIROHA_ITTIAM */
#endif
#ifdef MAX2829
PRINTK("MAX2829 \n\r");
#endif /* MAX2829 */
// 20120709 caisf masked, merged ittiam mac v1.2 code
#if 0
#ifdef MAX2830_32
PRINTK("MAX2830_32 \n\r");
#endif /* MAX2830_32 */
#ifdef AL2236
PRINTK("AL2236 \n\r");
#endif /* AL2236 */
#ifdef AL7230
PRINTK("AL7230 \n\r");
#endif /* AL7230 */
#endif
#ifdef MWLAN
PRINTK("MWLAN \n\r");
#endif /* MWLAN */
#ifdef OS_LINUX_CSL_TYPE
PRINTK("OS_LINUX_CSL_TYPE \n\r");
#endif /* OS_LINUX_CSL_TYPE */
#ifdef DEBUG_MODE
PRINTK("DEBUG_MODE \n\r");
#endif /* DEBUG_MODE */
#ifdef USE_PROCESSOR_DMA
PRINTK("USE_PROCESSOR_DMA \n\r");
#endif /* USE_PROCESSOR_DMA */
#ifdef EDCA_DEMO_KLUDGE
PRINTK("EDCA_DEMO_KLUDGE \n\r");
#endif /* EDCA_DEMO_KLUDGE */
#ifdef LOCALMEM_TX_DSCR
PRINTK("LOCALMEM_TX_DSCR \n\r");
#endif /* LOCALMEM_TX_DSCR */
#ifdef AUTORATE_FEATURE
PRINTK("AUTORATE_FEATURE \n\r");
#endif /* AUTORATE_FEATURE */
#ifdef DISABLE_MACHW_DEFRAG
PRINTK("DISABLE_MACHW_DEFRAG \n\r");
#endif /* DISABLE_MACHW_DEFRAG */
#ifdef DISABLE_MACHW_DEAGGR
PRINTK("DISABLE_MACHW_DEAGGR \n\r");
#endif /* DISABLE_MACHW_DEAGGR */
#ifdef PHY_TEST_MAX_PKT_RX
PRINTK("PHY_TEST_MAX_PKT_RX \n\r");
#endif /* PHY_TEST_MAX_PKT_RX */
#ifdef DEFAULT_SME
PRINTK("DEFAULT_SME \n\r");
#endif /* DEFAULT_SME */
#ifdef NO_ACTION_RESET
PRINTK("NO_ACTION_RESET \n\r");
#endif /* NO_ACTION_RESET */
#ifdef LITTLE_ENDIAN
PRINTK("LITTLE_ENDIAN \n\r");
#endif /* LITTLE_ENDIAN */
#ifdef DSCR_MACROS_NOT_DEFINED
PRINTK("DSCR_MACROS_NOT_DEFINED \n\r");
#endif /* DSCR_MACROS_NOT_DEFINED */
#ifdef PHY_CONTINUOUS_TX_MODE
PRINTK("PHY_CONTINUOUS_TX_MODE \n\r");
#endif /* PHY_CONTINUOUS_TX_MODE */
#ifdef HANDLE_ERROR_INTR
PRINTK("HANDLE_ERROR_INTR \n\r");
#endif /* HANDLE_ERROR_INTR */
#ifdef MEM_DEBUG_MODE
PRINTK("MEM_DEBUG_MODE \n\r");
#endif /* MEM_DEBUG_MODE */
#ifdef MEM_STRUCT_SIZES_INIT
PRINTK("MEM_STRUCT_SIZES_INIT \n\r");
#endif /* MEM_STRUCT_SIZES_INIT */
#ifdef TX_ABORT_FEATURE
PRINTK("TX_ABORT_FEATURE \n\r");
#endif /* TX_ABORT_FEATURE */
}
#endif /* DEBUG_MODE */
/*chenq add itm trace*/
/*flag of ShareMemInfo*/
int g_debug_print_tx_pkt_on = 0;
int g_debug_print_rx_ptk_on = 0;
int g_debug_print_tx_buf_on = 0;
int g_debug_print_rx_buf_on = 0;
int g_debug_buf_use_info_start = 0;
/*flag of MacTxRxStatistics*/
int g_debug_txrx_reg_info_start = 0;
int g_debug_txrx_frame_info_start = 0;
int g_debug_rx_size_info_start = 0;
int g_debug_isr_info_start = 0;
/*flag of SpiSdioDmaState*/
int g_debug_print_spisdio_bus_on = 0;
int g_debug_print_dma_do_on = 0;
int g_debug_spisdiodma_isr_info_start = 0;
/*flag of MacFsmMibState*/
int g_debug_print_fsm_on = 0;
int g_debug_print_assoc_on = 0;
int g_debug_print_Enc_auth_on = 0;
int g_debug_print_wps_on = 0;
int g_debug_print_ps_on = 0;//PowerSave
int g_debug_print_wd_on = 0;//WiFi-Direct
int g_debug_print_txrx_path_on = 0;
/*flag of Host6820Info*/
//no add
void Reset_itm_trace_flag(void)
{
/*flag of ShareMemInfo*/
g_debug_print_tx_pkt_on = 0;
g_debug_print_rx_ptk_on = 0;
g_debug_print_tx_buf_on = 0;
g_debug_print_rx_buf_on = 0;
g_debug_buf_use_info_start = 0;
/*flag of MacTxRxStatistics*/
g_debug_txrx_reg_info_start = 0;
g_debug_txrx_frame_info_start = 0;
g_debug_rx_size_info_start = 0;
g_debug_isr_info_start = 0;
/*flag of SpiSdioDmaState*/
g_debug_print_spisdio_bus_on = 0;
g_debug_print_dma_do_on = 0;
g_debug_spisdiodma_isr_info_start = 0;
/*flag of MacFsmMibState*/
g_debug_print_fsm_on = 0;
g_debug_print_assoc_on = 0;
g_debug_print_Enc_auth_on = 0;
g_debug_print_wps_on = 0;
g_debug_print_ps_on = 0;//PowerSave
g_debug_print_wd_on = 0;//WiFi-Direct
g_debug_print_txrx_path_on = 0;
/*flag of Host6820Info*/
//no add
}
void ShareMemInfo(int type,int flag,int value,char * reserved2ext)
{
if(type == itm_debug_plog_sharemem_tx_pkt)
{
g_debug_print_tx_pkt_on = value;
}
else if(type == itm_debug_plog_sharemem_rx_ptk)
{
g_debug_print_rx_ptk_on = value;
}
else if(type == itm_debug_plog_sharemem_tx_buf)
{
g_debug_print_tx_buf_on = value;
}
else if(type == itm_debug_plog_sharemem_rx_buf)
{
g_debug_print_rx_buf_on = value;
}
else if(type == itm_debug_plog_sharemem_buf_use)
{
if(flag == counter_start)
{
g_debug_buf_use_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_buf_use_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_buf_use_info_start = counter_end;
}
}
}
void MacTxRxStatistics(int type,int flag,char * reserved2ext)
{
if(type == itm_debug_plog_mactxrx_reg)
{
if(flag == counter_start)
{
g_debug_txrx_reg_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_txrx_reg_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_txrx_reg_info_start = counter_end;
}
}
else if(type == itm_debug_plog_mactxrx_frame)
{
if(flag == counter_start)
{
g_debug_txrx_frame_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_txrx_frame_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_txrx_frame_info_start = counter_end;
}
}
else if(type == itm_debug_plog_mactxrx_rx_size)
{
if(flag == counter_start)
{
g_debug_rx_size_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_rx_size_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_rx_size_info_start = counter_end;
}
}
else if(type == itm_debug_plog_mactxrx_isr)
{
if(flag == counter_start)
{
g_debug_isr_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_isr_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_isr_info_start = counter_end;
}
}
}
void SpiSdioDmaState(int type,int flag,int value,char * reserved2ext)
{
if(type == itm_debug_plog_spisdiodma_spisdio)
{
g_debug_print_spisdio_bus_on = value;
}
else if(type == itm_debug_plog_spisdiodma_dma)
{
g_debug_print_dma_do_on = value;
}
else if(type == itm_debug_plog_spisdiodma_isr)
{
if(flag == counter_start)
{
g_debug_spisdiodma_isr_info_start = counter_start;
}
else if( ( flag == counter_end ) && ( g_debug_spisdiodma_isr_info_start == counter_end ) )
{
/*printk("already in counter_end stat\n");*/
}
else if( flag == counter_end )
{
g_debug_spisdiodma_isr_info_start = counter_end;
}
}
}
void MacFsmMibState(int type,int value,char * reserved2ext)
{
if(type == itm_debug_plog_macfsm_mib_fsm)
{
g_debug_print_fsm_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_assoc)
{
g_debug_print_assoc_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_Enc_auth)
{
g_debug_print_Enc_auth_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_wps)
{
g_debug_print_wps_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_ps)//PowerSave
{
g_debug_print_ps_on = value;//PowerSave
}
else if(type == itm_debug_plog_macfsm_mib_wd)//WiFi-Direct
{
g_debug_print_wd_on = value;//WiFi-Direct
}
else if(type == itm_debug_plog_macfsm_mib_txrx_path)
{
g_debug_print_txrx_path_on = value;
}
else if(type == itm_debug_plog_macfsm_mib_mibapp)
{
/*print ...*/
}
else if(type == itm_debug_plog_macfsm_mib_mibprtcl)
{
/*print ...*/
}
else if(type == itm_debug_plog_macfsm_mib_mibmac)
{
/*print ...*/
}
}
void Host6820Info(int type,char * reserved2ext)
{
}
/*chenq add end*/
#ifdef TROUT_WIFI_POWER_SLEEP_ENABLE
/*
* Notify co-processor to handle Power Management event
* through interrupt.
* Author: Keguang
* Date: 20130321
*/
inline void notify_cp_with_handshake(uint msg, uint retry)
{
uint i = retry;
uint count = host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) + 1;
//#ifdef POWERSAVE_DEBUG
pr_info("rSYSREG_POWER_CTRL: %x\n", host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL));
//#endif
host_write_trout_reg((UWORD32)msg, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*load message*/
host_write_trout_reg((UWORD32)0x1, (UWORD32)rSYSREG_GEN_ISR_2_ARM7); /*interrupt CP*/
/*pr_info("command done!\n");*/
/*wait for CP*/
while((host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) != count) && i--) {
msleep(10);
//#ifdef POWERSAVE_DEBUG
pr_info("Done! rSYSREG_POWER_CTRL: %x\n", host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL));
//#endif
}
pr_info("!!! rSYSREG_POWER_CTRL: %x, retry %d, i %d\n", host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL), retry, i);
host_write_trout_reg(0x0, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*clear message*/
if(msg == PS_MSG_WIFI_SUSPEND_MAGIC)
g_done_wifi_suspend = 1;
else if(msg == PS_MSG_WIFI_RESUME_MAGIC)
g_done_wifi_suspend = 0;
}
EXPORT_SYMBOL(notify_cp_with_handshake);
extern int prepare_null_frame_for_cp(UWORD8 psm, BOOL_T is_qos, UWORD8 priority);
void check_and_retransmit(void)
{
uint which_frame = 0;
uint sta = 0;
uint vs;
uint retry = 0;
unsigned char tmp[200];
uint *pw = (uint *)&tmp[0];
which_frame = root_host_read_trout_reg((UWORD32)rSYSREG_HOST2ARM_INFO1);
if(which_frame)
sta = BEACON_MEM_BEGIN;
else
sta = BEACON_MEM_BEGIN + 200;
root_host_read_trout_ram((void *)tmp, (void *)sta, TX_DSCR_LEN);
if(((tmp[3] >> 5) & 0x3) == 0x3){
goto retx;
}
if((tmp[20] & 0x3) != 0x3){
printk("SF0-CASUED\n");
goto retx;
}
/* arrive here, means the last frame ARM7 sent was success(AP acked) do nothing*/
return;
retx:
tmp[3] &= 0x9F;
tmp[3] |= 0x20;
tmp[20] &= 0xFC;
vs = root_host_read_trout_reg((UWORD32)rMAC_TSF_TIMER_LO);
vs = (vs >> 10) & 0xFFFF;
pw[3] &= 0xFFFF0000;
pw[3] |= vs;
printk("RE-TX\n");
root_host_write_trout_ram((void *)sta, (void *)tmp, TX_DSCR_LEN);
root_host_write_trout_reg((UWORD32)sta, (UWORD32)rMAC_EDCA_PRI_HP_Q_PTR);
msleep(20);
return;
}
/*for internal use only*/
inline void root_notify_cp_with_handshake(uint msg, uint retry)
{
uint i = retry;
uint count = root_host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) + 1;
#ifdef POWERSAVE_DEBUG
pr_info("rSYSREG_POWER_CTRL: %x\n", root_host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL));
/*pr_info("command %x\n", msg);*/
#endif
root_host_write_trout_reg((UWORD32)msg, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*load message*/
root_host_write_trout_reg((UWORD32)0x1, (UWORD32)rSYSREG_GEN_ISR_2_ARM7); /*interrupt CP*/
/*pr_info("command done!\n");*/
if((msg & 0xFFFF) == PS_MSG_ARM7_EBEA_KC_MAGIC){
printk("EBEA.......\n");
msleep(75);
check_and_retransmit();
}
/*wait for CP*/
while((root_host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM) != count) && i--) {
msleep(10);
#ifdef POWERSAVE_DEBUG
pr_info("Done! rSYSREG_POWER_CTRL: %x\n", root_host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL));
/*pr_info("expected %x, SYSREG_INFO1_FROM_ARM = %x\n", count, root_host_read_trout_reg((UWORD32)rSYSREG_INFO1_FROM_ARM));*/
#endif
}
pr_info("@@@ rSYSREG_POWER_CTRL: %x, retry %d, i %d\n", root_host_read_trout_reg((UWORD32)rSYSREG_POWER_CTRL), retry, i);
root_host_write_trout_reg(0x0, (UWORD32)rSYSREG_HOST2ARM_INFO1); /*clear message*/
if(msg == PS_MSG_WIFI_SUSPEND_MAGIC)
g_done_wifi_suspend = 1;
else if(msg == PS_MSG_WIFI_RESUME_MAGIC)
g_done_wifi_suspend = 0;
}
#endif
| Java |
#include "stdafx.h"
#include "Emu/SysCalls/SysCalls.h"
#include "Emu/SysCalls/SC_FUNC.h"
#include "Emu/GS/GCM.h"
void cellGcmSys_init();
void cellGcmSys_load();
void cellGcmSys_unload();
Module cellGcmSys(0x0010, cellGcmSys_init, cellGcmSys_load, cellGcmSys_unload);
u32 local_size = 0;
u32 local_addr = 0;
enum
{
CELL_GCM_ERROR_FAILURE = 0x802100ff,
CELL_GCM_ERROR_NO_IO_PAGE_TABLE = 0x80210001,
CELL_GCM_ERROR_INVALID_ENUM = 0x80210002,
CELL_GCM_ERROR_INVALID_VALUE = 0x80210003,
CELL_GCM_ERROR_INVALID_ALIGNMENT = 0x80210004,
CELL_GCM_ERROR_ADDRESS_OVERWRAP = 0x80210005
};
// Function declaration
int cellGcmSetPrepareFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id);
//----------------------------------------------------------------------------
// Memory Mapping
//----------------------------------------------------------------------------
struct gcm_offset
{
u64 io;
u64 ea;
};
void InitOffsetTable();
int32_t cellGcmAddressToOffset(u64 address, mem32_t offset);
uint32_t cellGcmGetMaxIoMapSize();
void cellGcmGetOffsetTable(mem_ptr_t<gcm_offset> table);
int32_t cellGcmIoOffsetToAddress(u32 ioOffset, u64 address);
int32_t cellGcmMapEaIoAddress(const u32 ea, const u32 io, const u32 size);
int32_t cellGcmMapEaIoAddressWithFlags(const u32 ea, const u32 io, const u32 size, const u32 flags);
int32_t cellGcmMapMainMemory(u64 ea, u32 size, mem32_t offset);
int32_t cellGcmReserveIoMapSize(const u32 size);
int32_t cellGcmUnmapEaIoAddress(u64 ea);
int32_t cellGcmUnmapIoAddress(u64 io);
int32_t cellGcmUnreserveIoMapSize(u32 size);
//----------------------------------------------------------------------------
CellGcmConfig current_config;
CellGcmContextData current_context;
gcmInfo gcm_info;
u32 map_offset_addr = 0;
u32 map_offset_pos = 0;
//----------------------------------------------------------------------------
// Data Retrieval
//----------------------------------------------------------------------------
u32 cellGcmGetLabelAddress(u8 index)
{
cellGcmSys.Log("cellGcmGetLabelAddress(index=%d)", index);
return Memory.RSXCMDMem.GetStartAddr() + 0x10 * index;
}
u32 cellGcmGetReportDataAddressLocation(u8 location, u32 index)
{
ConLog.Warning("cellGcmGetReportDataAddressLocation(location=%d, index=%d)", location, index);
return Emu.GetGSManager().GetRender().m_report_main_addr;
}
u64 cellGcmGetTimeStamp(u32 index)
{
cellGcmSys.Log("cellGcmGetTimeStamp(index=%d)", index);
return Memory.Read64(Memory.RSXFBMem.GetStartAddr() + index * 0x10);
}
//----------------------------------------------------------------------------
// Command Buffer Control
//----------------------------------------------------------------------------
u32 cellGcmGetControlRegister()
{
cellGcmSys.Log("cellGcmGetControlRegister()");
return gcm_info.control_addr;
}
u32 cellGcmGetDefaultCommandWordSize()
{
cellGcmSys.Warning("cellGcmGetDefaultCommandWordSize()");
return 0x400;
}
u32 cellGcmGetDefaultSegmentWordSize()
{
cellGcmSys.Warning("cellGcmGetDefaultSegmentWordSize()");
return 0x100;
}
int cellGcmInitDefaultFifoMode(s32 mode)
{
cellGcmSys.Warning("cellGcmInitDefaultFifoMode(mode=%d)", mode);
return CELL_OK;
}
int cellGcmSetDefaultFifoSize(u32 bufferSize, u32 segmentSize)
{
cellGcmSys.Warning("cellGcmSetDefaultFifoSize(bufferSize=0x%x, segmentSize=0x%x)", bufferSize, segmentSize);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Hardware Resource Management
//----------------------------------------------------------------------------
int cellGcmBindTile(u8 index)
{
cellGcmSys.Warning("cellGcmBindTile(index=%d)", index);
if (index >= RSXThread::m_tiles_count)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_binded = true;
return CELL_OK;
}
int cellGcmBindZcull(u8 index)
{
cellGcmSys.Warning("TODO: cellGcmBindZcull(index=%d)", index);
return CELL_OK;
}
int cellGcmGetConfiguration(mem_ptr_t<CellGcmConfig> config)
{
cellGcmSys.Log("cellGcmGetConfiguration(config_addr=0x%x)", config.GetAddr());
if (!config.IsGood()) return CELL_EFAULT;
*config = current_config;
return CELL_OK;
}
int cellGcmGetFlipStatus()
{
return Emu.GetGSManager().GetRender().m_flip_status;
}
u32 cellGcmGetTiledPitchSize(u32 size)
{
//TODO
cellGcmSys.Warning("cellGcmGetTiledPitchSize(size=%d)", size);
return size;
}
int cellGcmInit(u32 context_addr, u32 cmdSize, u32 ioSize, u32 ioAddress)
{
cellGcmSys.Warning("cellGcmInit(context_addr=0x%x,cmdSize=0x%x,ioSize=0x%x,ioAddress=0x%x)", context_addr, cmdSize, ioSize, ioAddress);
if(!cellGcmSys.IsLoaded())
cellGcmSys.Load();
if(!local_size && !local_addr)
{
local_size = 0xf900000; //TODO
local_addr = Memory.RSXFBMem.GetStartAddr();
Memory.RSXFBMem.AllocAlign(local_size);
}
cellGcmSys.Warning("*** local memory(addr=0x%x, size=0x%x)", local_addr, local_size);
InitOffsetTable();
Memory.MemoryBlocks.push_back(Memory.RSXIOMem.SetRange(0x50000000, 0x10000000/*256MB*/));//TODO: implement allocateAdressSpace in memoryBase
if(cellGcmMapEaIoAddress(ioAddress, 0, ioSize) != CELL_OK)
{
Memory.MemoryBlocks.pop_back();
return CELL_GCM_ERROR_FAILURE;
}
map_offset_addr = 0;
map_offset_pos = 0;
current_config.ioSize = ioSize;
current_config.ioAddress = ioAddress;
current_config.localSize = local_size;
current_config.localAddress = local_addr;
current_config.memoryFrequency = 650000000;
current_config.coreFrequency = 500000000;
Memory.RSXCMDMem.AllocAlign(cmdSize);
u32 ctx_begin = ioAddress/* + 0x1000*/;
u32 ctx_size = 0x6ffc;
current_context.begin = ctx_begin;
current_context.end = ctx_begin + ctx_size;
current_context.current = current_context.begin;
current_context.callback = Emu.GetRSXCallback() - 4;
gcm_info.context_addr = Memory.MainMem.AllocAlign(0x1000);
gcm_info.control_addr = gcm_info.context_addr + 0x40;
Memory.WriteData(gcm_info.context_addr, current_context);
Memory.Write32(context_addr, gcm_info.context_addr);
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
ctrl.put = 0;
ctrl.get = 0;
ctrl.ref = -1;
auto& render = Emu.GetGSManager().GetRender();
render.m_ctxt_addr = context_addr;
render.m_gcm_buffers_addr = Memory.Alloc(sizeof(gcmBuffer) * 8, sizeof(gcmBuffer));
render.m_zculls_addr = Memory.Alloc(sizeof(CellGcmZcullInfo) * 8, sizeof(CellGcmZcullInfo));
render.m_tiles_addr = Memory.Alloc(sizeof(CellGcmTileInfo) * 15, sizeof(CellGcmTileInfo));
render.m_gcm_buffers_count = 0;
render.m_gcm_current_buffer = 0;
render.m_main_mem_addr = 0;
render.Init(ctx_begin, ctx_size, gcm_info.control_addr, local_addr);
return CELL_OK;
}
int cellGcmResetFlipStatus()
{
Emu.GetGSManager().GetRender().m_flip_status = 1;
return CELL_OK;
}
int cellGcmSetDebugOutputLevel(int level)
{
cellGcmSys.Warning("cellGcmSetDebugOutputLevel(level=%d)", level);
switch (level)
{
case CELL_GCM_DEBUG_LEVEL0:
case CELL_GCM_DEBUG_LEVEL1:
case CELL_GCM_DEBUG_LEVEL2:
Emu.GetGSManager().GetRender().m_debug_level = level;
break;
default: return CELL_EINVAL;
}
return CELL_OK;
}
int cellGcmSetDisplayBuffer(u32 id, u32 offset, u32 pitch, u32 width, u32 height)
{
cellGcmSys.Warning("cellGcmSetDisplayBuffer(id=0x%x,offset=0x%x,pitch=%d,width=%d,height=%d)",
id, offset, width ? pitch/width : pitch, width, height);
if(id > 7) return CELL_EINVAL;
gcmBuffer* buffers = (gcmBuffer*)Memory.GetMemFromAddr(Emu.GetGSManager().GetRender().m_gcm_buffers_addr);
buffers[id].offset = re(offset);
buffers[id].pitch = re(pitch);
buffers[id].width = re(width);
buffers[id].height = re(height);
if(id + 1 > Emu.GetGSManager().GetRender().m_gcm_buffers_count)
{
Emu.GetGSManager().GetRender().m_gcm_buffers_count = id + 1;
}
return CELL_OK;
}
int cellGcmSetFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id)
{
cellGcmSys.Log("cellGcmSetFlip(ctx=0x%x, id=0x%x)", ctxt.GetAddr(), id);
int res = cellGcmSetPrepareFlip(ctxt, id);
return res < 0 ? CELL_GCM_ERROR_FAILURE : CELL_OK;
}
int cellGcmSetFlipHandler(u32 handler_addr)
{
cellGcmSys.Warning("cellGcmSetFlipHandler(handler_addr=%d)", handler_addr);
if (handler_addr != 0 && !Memory.IsGoodAddr(handler_addr))
{
return CELL_EFAULT;
}
Emu.GetGSManager().GetRender().m_flip_handler.SetAddr(handler_addr);
return CELL_OK;
}
int cellGcmSetFlipMode(u32 mode)
{
cellGcmSys.Warning("cellGcmSetFlipMode(mode=%d)", mode);
switch (mode)
{
case CELL_GCM_DISPLAY_HSYNC:
case CELL_GCM_DISPLAY_VSYNC:
case CELL_GCM_DISPLAY_HSYNC_WITH_NOISE:
Emu.GetGSManager().GetRender().m_flip_mode = mode;
break;
default:
return CELL_EINVAL;
}
return CELL_OK;
}
void cellGcmSetFlipStatus()
{
cellGcmSys.Warning("cellGcmSetFlipStatus()");
Emu.GetGSManager().GetRender().m_flip_status = 0;
}
int cellGcmSetPrepareFlip(mem_ptr_t<CellGcmContextData> ctxt, u32 id)
{
cellGcmSys.Log("cellGcmSetPrepareFlip(ctx=0x%x, id=0x%x)", ctxt.GetAddr(), id);
if(id >= 8)
{
return CELL_GCM_ERROR_FAILURE;
}
GSLockCurrent gslock(GS_LOCK_WAIT_FLUSH); // could stall on exit
u32 current = ctxt->current;
u32 end = ctxt->end;
if(current + 8 >= end)
{
ConLog.Warning("bad flip!");
//cellGcmCallback(ctxt.GetAddr(), current + 8 - end);
//copied:
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
const s32 res = ctxt->current - ctxt->begin - ctrl.put;
if(res > 0) Memory.Copy(ctxt->begin, ctxt->current - res, res);
ctxt->current = ctxt->begin + res;
ctrl.put = res;
ctrl.get = 0;
}
current = ctxt->current;
Memory.Write32(current, 0x3fead | (1 << 18));
Memory.Write32(current + 4, id);
ctxt->current += 8;
if(ctxt.GetAddr() == gcm_info.context_addr)
{
CellGcmControl& ctrl = (CellGcmControl&)Memory[gcm_info.control_addr];
ctrl.put += 8;
}
return id;
}
int cellGcmSetSecondVFrequency(u32 freq)
{
cellGcmSys.Warning("cellGcmSetSecondVFrequency(level=%d)", freq);
switch (freq)
{
case CELL_GCM_DISPLAY_FREQUENCY_59_94HZ:
case CELL_GCM_DISPLAY_FREQUENCY_SCANOUT:
case CELL_GCM_DISPLAY_FREQUENCY_DISABLE:
Emu.GetGSManager().GetRender().m_frequency_mode = freq;
break;
default: return CELL_EINVAL;
}
return CELL_OK;
}
int cellGcmSetTileInfo(u8 index, u8 location, u32 offset, u32 size, u32 pitch, u8 comp, u16 base, u8 bank)
{
cellGcmSys.Warning("cellGcmSetTileInfo(index=%d, location=%d, offset=%d, size=%d, pitch=%d, comp=%d, base=%d, bank=%d)",
index, location, offset, size, pitch, comp, base, bank);
if (index >= RSXThread::m_tiles_count || base >= 800 || bank >= 4)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
if (offset & 0xffff || size & 0xffff || pitch & 0xf)
{
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
}
if (location >= 2 || (comp != 0 && (comp < 7 || comp > 12)))
{
return CELL_GCM_ERROR_INVALID_ENUM;
}
if (comp)
{
cellGcmSys.Error("cellGcmSetTileInfo: bad comp! (%d)", comp);
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_location = location;
tile.m_offset = offset;
tile.m_size = size;
tile.m_pitch = pitch;
tile.m_comp = comp;
tile.m_base = base;
tile.m_bank = bank;
Memory.WriteData(Emu.GetGSManager().GetRender().m_tiles_addr + sizeof(CellGcmTileInfo)* index, tile.Pack());
return CELL_OK;
}
u32 cellGcmSetUserHandler(u32 handler)
{
cellGcmSys.Warning("cellGcmSetUserHandler(handler=0x%x)", handler);
return handler;
}
int cellGcmSetVBlankHandler()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetWaitFlip(mem_ptr_t<CellGcmContextData> ctxt)
{
cellGcmSys.Log("cellGcmSetWaitFlip(ctx=0x%x)", ctxt.GetAddr());
GSLockCurrent lock(GS_LOCK_WAIT_FLIP);
return CELL_OK;
}
int cellGcmSetZcull(u8 index, u32 offset, u32 width, u32 height, u32 cullStart, u32 zFormat, u32 aaFormat, u32 zCullDir, u32 zCullFormat, u32 sFunc, u32 sRef, u32 sMask)
{
cellGcmSys.Warning("TODO: cellGcmSetZcull(index=%d, offset=0x%x, width=%d, height=%d, cullStart=0x%x, zFormat=0x%x, aaFormat=0x%x, zCullDir=0x%x, zCullFormat=0x%x, sFunc=0x%x, sRef=0x%x, sMask=0x%x)",
index, offset, width, height, cullStart, zFormat, aaFormat, zCullDir, zCullFormat, sFunc, sRef, sMask);
return CELL_OK;
}
int cellGcmUnbindTile(u8 index)
{
cellGcmSys.Warning("cellGcmUnbindTile(index=%d)", index);
if (index >= RSXThread::m_tiles_count)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_binded = false;
return CELL_OK;
}
int cellGcmUnbindZcull(u8 index)
{
cellGcmSys.Warning("cellGcmUnbindZcull(index=%d)", index);
if (index >= 8)
return CELL_EINVAL;
return CELL_OK;
}
u32 cellGcmGetTileInfo()
{
cellGcmSys.Warning("cellGcmGetTileInfo()");
return Emu.GetGSManager().GetRender().m_tiles_addr;
}
u32 cellGcmGetZcullInfo()
{
cellGcmSys.Warning("cellGcmGetZcullInfo()");
return Emu.GetGSManager().GetRender().m_zculls_addr;
}
u32 cellGcmGetDisplayInfo()
{
cellGcmSys.Warning("cellGcmGetDisplayInfo() = 0x%x", Emu.GetGSManager().GetRender().m_gcm_buffers_addr);
return Emu.GetGSManager().GetRender().m_gcm_buffers_addr;
}
int cellGcmGetCurrentDisplayBufferId(u32 id_addr)
{
cellGcmSys.Warning("cellGcmGetCurrentDisplayBufferId(id_addr=0x%x)", id_addr);
if (!Memory.IsGoodAddr(id_addr))
{
return CELL_EFAULT;
}
Memory.Write32(id_addr, Emu.GetGSManager().GetRender().m_gcm_current_buffer);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Memory Mapping
//----------------------------------------------------------------------------
gcm_offset offsetTable = { 0, 0 };
void InitOffsetTable()
{
offsetTable.io = Memory.Alloc(3072 * sizeof(u16), 1);
for (int i = 0; i<3072; i++)
{
Memory.Write16(offsetTable.io + sizeof(u16)*i, 0xFFFF);
}
offsetTable.ea = Memory.Alloc(256 * sizeof(u16), 1);//TODO: check flags
for (int i = 0; i<256; i++)
{
Memory.Write16(offsetTable.ea + sizeof(u16)*i, 0xFFFF);
}
}
int32_t cellGcmAddressToOffset(u64 address, mem32_t offset)
{
cellGcmSys.Log("cellGcmAddressToOffset(address=0x%x,offset_addr=0x%x)", address, offset.GetAddr());
if (address >= 0xD0000000/*not on main memory or local*/)
return CELL_GCM_ERROR_FAILURE;
u32 result;
// If address is in range of local memory
if (Memory.RSXFBMem.IsInMyRange(address))
{
result = address - Memory.RSXFBMem.GetStartAddr();
}
// else check if the adress (main memory) is mapped in IO
else
{
u16 upper12Bits = Memory.Read16(offsetTable.io + sizeof(u16)*(address >> 20));
if (upper12Bits != 0xFFFF)
{
result = (((u64)upper12Bits << 20) | (address & (0xFFFFF)));
}
// address is not mapped in IO
else
{
return CELL_GCM_ERROR_FAILURE;
}
}
offset = result;
return CELL_OK;
}
uint32_t cellGcmGetMaxIoMapSize()
{
return Memory.RSXIOMem.GetEndAddr() - Memory.RSXIOMem.GetStartAddr() - Memory.RSXIOMem.GetReservedAmount();
}
void cellGcmGetOffsetTable(mem_ptr_t<gcm_offset> table)
{
table->io = re(offsetTable.io);
table->ea = re(offsetTable.ea);
}
int32_t cellGcmIoOffsetToAddress(u32 ioOffset, u64 address)
{
u64 realAddr;
realAddr = Memory.RSXIOMem.getRealAddr(Memory.RSXIOMem.GetStartAddr() + ioOffset);
if (!realAddr)
return CELL_GCM_ERROR_FAILURE;
Memory.Write64(address, realAddr);
return CELL_OK;
}
int32_t cellGcmMapEaIoAddress(const u32 ea, const u32 io, const u32 size)
{
cellGcmSys.Warning("cellGcmMapEaIoAddress(ea=0x%x, io=0x%x, size=0x%x)", ea, io, size);
if ((ea & 0xFFFFF) || (io & 0xFFFFF) || (size & 0xFFFFF)) return CELL_GCM_ERROR_FAILURE;
//check if the mapping was successfull
if (Memory.RSXIOMem.Map(ea, size, Memory.RSXIOMem.GetStartAddr() + io))
{
//fill the offset table
for (u32 i = 0; i<(size >> 20); i++)
{
Memory.Write16(offsetTable.io + ((ea >> 20) + i)*sizeof(u16), (io >> 20) + i);
Memory.Write16(offsetTable.ea + ((io >> 20) + i)*sizeof(u16), (ea >> 20) + i);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmMapEaIoAddressWithFlags(const u32 ea, const u32 io, const u32 size, const u32 flags)
{
cellGcmSys.Warning("cellGcmMapEaIoAddressWithFlags(ea=0x%x, io=0x%x, size=0x%x, flags=0x%x)", ea, io, size, flags);
return cellGcmMapEaIoAddress(ea, io, size); // TODO: strict ordering
}
int32_t cellGcmMapLocalMemory(u64 address, u64 size)
{
if (!local_size && !local_addr)
{
local_size = 0xf900000; //TODO
local_addr = Memory.RSXFBMem.GetStartAddr();
Memory.RSXFBMem.AllocAlign(local_size);
Memory.Write32(address, local_addr);
Memory.Write32(size, local_size);
}
else
{
cellGcmSys.Error("RSX local memory already mapped");
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmMapMainMemory(u64 ea, u32 size, mem32_t offset)
{
cellGcmSys.Warning("cellGcmMapMainMemory(ea=0x%x,size=0x%x,offset_addr=0x%x)", ea, size, offset.GetAddr());
u64 io;
if ((ea & 0xFFFFF) || (size & 0xFFFFF)) return CELL_GCM_ERROR_FAILURE;
//check if the mapping was successfull
if (io = Memory.RSXIOMem.Map(ea, size, 0))
{
// convert to offset
io = io - Memory.RSXIOMem.GetStartAddr();
//fill the offset table
for (u32 i = 0; i<(size >> 20); i++)
{
Memory.Write16(offsetTable.io + ((ea >> 20) + i)*sizeof(u16), (io >> 20) + i);
Memory.Write16(offsetTable.ea + ((io >> 20) + i)*sizeof(u16), (ea >> 20) + i);
}
offset = io;
}
else
{
return CELL_GCM_ERROR_NO_IO_PAGE_TABLE;
}
Emu.GetGSManager().GetRender().m_main_mem_addr = Emu.GetGSManager().GetRender().m_ioAddress;
return CELL_OK;
}
int32_t cellGcmReserveIoMapSize(const u32 size)
{
if (size & 0xFFFFF)
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
if (size > cellGcmGetMaxIoMapSize())
return CELL_GCM_ERROR_INVALID_VALUE;
Memory.RSXIOMem.Reserve(size);
return CELL_OK;
}
int32_t cellGcmUnmapEaIoAddress(u64 ea)
{
u32 size = Memory.RSXIOMem.UnmapRealAddress(ea);
if (size)
{
u64 io;
ea = ea >> 20;
io = Memory.Read16(offsetTable.io + (ea*sizeof(u16)));
for (u32 i = 0; i<size; i++)
{
Memory.Write16(offsetTable.io + ((ea + i)*sizeof(u16)), 0xFFFF);
Memory.Write16(offsetTable.ea + ((io + i)*sizeof(u16)), 0xFFFF);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmUnmapIoAddress(u64 io)
{
u32 size = Memory.RSXIOMem.UnmapAddress(io);
if (size)
{
u64 ea;
io = io >> 20;
ea = Memory.Read16(offsetTable.ea + (io*sizeof(u16)));
for (u32 i = 0; i<size; i++)
{
Memory.Write16(offsetTable.io + ((ea + i)*sizeof(u16)), 0xFFFF);
Memory.Write16(offsetTable.ea + ((io + i)*sizeof(u16)), 0xFFFF);
}
}
else
{
return CELL_GCM_ERROR_FAILURE;
}
return CELL_OK;
}
int32_t cellGcmUnreserveIoMapSize(u32 size)
{
if (size & 0xFFFFF)
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
if (size > Memory.RSXIOMem.GetReservedAmount())
return CELL_GCM_ERROR_INVALID_VALUE;
Memory.RSXIOMem.Unreserve(size);
return CELL_OK;
}
//----------------------------------------------------------------------------
// Cursor
//----------------------------------------------------------------------------
int cellGcmInitCursor()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorPosition(s32 x, s32 y)
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorDisable()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmUpdateCursor()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorEnable()
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
int cellGcmSetCursorImageOffset(u32 offset)
{
UNIMPLEMENTED_FUNC(cellGcmSys);
return CELL_OK;
}
//------------------------------------------------------------------------
// Functions for Maintaining Compatibility
//------------------------------------------------------------------------
void cellGcmSetDefaultCommandBuffer()
{
cellGcmSys.Warning("cellGcmSetDefaultCommandBuffer()");
Memory.Write32(Emu.GetGSManager().GetRender().m_ctxt_addr, gcm_info.context_addr);
}
//------------------------------------------------------------------------
// Other
//------------------------------------------------------------------------
int cellGcmSetFlipCommand(u32 ctx, u32 id)
{
return cellGcmSetPrepareFlip(ctx, id);
}
s64 cellGcmFunc15()
{
cellGcmSys.Error("cellGcmFunc15()");
return 0;
}
int cellGcmSetFlipCommandWithWaitLabel(u32 ctx, u32 id, u32 label_index, u32 label_value)
{
int res = cellGcmSetPrepareFlip(ctx, id);
Memory.Write32(Memory.RSXCMDMem.GetStartAddr() + 0x10 * label_index, label_value);
return res < 0 ? CELL_GCM_ERROR_FAILURE : CELL_OK;
}
int cellGcmSetTile(u8 index, u8 location, u32 offset, u32 size, u32 pitch, u8 comp, u16 base, u8 bank)
{
cellGcmSys.Warning("cellGcmSetTile(index=%d, location=%d, offset=%d, size=%d, pitch=%d, comp=%d, base=%d, bank=%d)",
index, location, offset, size, pitch, comp, base, bank);
// Copied form cellGcmSetTileInfo
if(index >= RSXThread::m_tiles_count || base >= 800 || bank >= 4)
{
return CELL_GCM_ERROR_INVALID_VALUE;
}
if(offset & 0xffff || size & 0xffff || pitch & 0xf)
{
return CELL_GCM_ERROR_INVALID_ALIGNMENT;
}
if(location >= 2 || (comp != 0 && (comp < 7 || comp > 12)))
{
return CELL_GCM_ERROR_INVALID_ENUM;
}
if(comp)
{
cellGcmSys.Error("cellGcmSetTile: bad comp! (%d)", comp);
}
auto& tile = Emu.GetGSManager().GetRender().m_tiles[index];
tile.m_location = location;
tile.m_offset = offset;
tile.m_size = size;
tile.m_pitch = pitch;
tile.m_comp = comp;
tile.m_base = base;
tile.m_bank = bank;
Memory.WriteData(Emu.GetGSManager().GetRender().m_tiles_addr + sizeof(CellGcmTileInfo) * index, tile.Pack());
return CELL_OK;
}
//----------------------------------------------------------------------------
void cellGcmSys_init()
{
// Data Retrieval
//cellGcmSys.AddFunc(0xc8f3bd09, cellGcmGetCurrentField);
cellGcmSys.AddFunc(0xf80196c1, cellGcmGetLabelAddress);
//cellGcmSys.AddFunc(0x21cee035, cellGcmGetNotifyDataAddress);
//cellGcmSys.AddFunc(0x99d397ac, cellGcmGetReport);
//cellGcmSys.AddFunc(0x9a0159af, cellGcmGetReportDataAddress);
cellGcmSys.AddFunc(0x8572bce2, cellGcmGetReportDataAddressLocation);
//cellGcmSys.AddFunc(0xa6b180ac, cellGcmGetReportDataLocation);
cellGcmSys.AddFunc(0x5a41c10f, cellGcmGetTimeStamp);
//cellGcmSys.AddFunc(0x2ad4951b, cellGcmGetTimeStampLocation);
// Command Buffer Control
//cellGcmSys.AddFunc(, cellGcmCallbackForSnc);
//cellGcmSys.AddFunc(, cellGcmFinish);
//cellGcmSys.AddFunc(, cellGcmFlush);
cellGcmSys.AddFunc(0xa547adde, cellGcmGetControlRegister);
cellGcmSys.AddFunc(0x5e2ee0f0, cellGcmGetDefaultCommandWordSize);
cellGcmSys.AddFunc(0x8cdf8c70, cellGcmGetDefaultSegmentWordSize);
cellGcmSys.AddFunc(0xcaabd992, cellGcmInitDefaultFifoMode);
//cellGcmSys.AddFunc(, cellGcmReserveMethodSize);
//cellGcmSys.AddFunc(, cellGcmResetDefaultCommandBuffer);
cellGcmSys.AddFunc(0x9ba451e4, cellGcmSetDefaultFifoSize);
//cellGcmSys.AddFunc(, cellGcmSetupContextData);
// Hardware Resource Management
cellGcmSys.AddFunc(0x4524cccd, cellGcmBindTile);
cellGcmSys.AddFunc(0x9dc04436, cellGcmBindZcull);
//cellGcmSys.AddFunc(0x1f61b3ff, cellGcmDumpGraphicsError);
cellGcmSys.AddFunc(0xe315a0b2, cellGcmGetConfiguration);
//cellGcmSys.AddFunc(0x371674cf, cellGcmGetDisplayBufferByFlipIndex);
cellGcmSys.AddFunc(0x72a577ce, cellGcmGetFlipStatus);
//cellGcmSys.AddFunc(0x63387071, cellGcmgetLastFlipTime);
//cellGcmSys.AddFunc(0x23ae55a3, cellGcmGetLastSecondVTime);
cellGcmSys.AddFunc(0x055bd74d, cellGcmGetTiledPitchSize);
//cellGcmSys.AddFunc(0x723bbc7e, cellGcmGetVBlankCount);
cellGcmSys.AddFunc(0x15bae46b, cellGcmInit);
//cellGcmSys.AddFunc(0xfce9e764, cellGcmInitSystemMode);
cellGcmSys.AddFunc(0xb2e761d4, cellGcmResetFlipStatus);
cellGcmSys.AddFunc(0x51c9d62b, cellGcmSetDebugOutputLevel);
cellGcmSys.AddFunc(0xa53d12ae, cellGcmSetDisplayBuffer);
cellGcmSys.AddFunc(0xdc09357e, cellGcmSetFlip);
cellGcmSys.AddFunc(0xa41ef7e8, cellGcmSetFlipHandler);
//cellGcmSys.AddFunc(0xacee8542, cellGcmSetFlipImmediate);
cellGcmSys.AddFunc(0x4ae8d215, cellGcmSetFlipMode);
cellGcmSys.AddFunc(0xa47c09ff, cellGcmSetFlipStatus);
//cellGcmSys.AddFunc(, cellGcmSetFlipWithWaitLabel);
//cellGcmSys.AddFunc(0xd01b570d, cellGcmSetGraphicsHandler);
cellGcmSys.AddFunc(0x0b4b62d5, cellGcmSetPrepareFlip);
//cellGcmSys.AddFunc(0x0a862772, cellGcmSetQueueHandler);
cellGcmSys.AddFunc(0x4d7ce993, cellGcmSetSecondVFrequency);
//cellGcmSys.AddFunc(0xdc494430, cellGcmSetSecondVHandler);
cellGcmSys.AddFunc(0xbd100dbc, cellGcmSetTileInfo);
cellGcmSys.AddFunc(0x06edea9e, cellGcmSetUserHandler);
//cellGcmSys.AddFunc(0xffe0160e, cellGcmSetVBlankFrequency);
cellGcmSys.AddFunc(0xa91b0402, cellGcmSetVBlankHandler);
cellGcmSys.AddFunc(0x983fb9aa, cellGcmSetWaitFlip);
cellGcmSys.AddFunc(0xd34a420d, cellGcmSetZcull);
//cellGcmSys.AddFunc(0x25b40ab4, cellGcmSortRemapEaIoAddress);
cellGcmSys.AddFunc(0xd9b7653e, cellGcmUnbindTile);
cellGcmSys.AddFunc(0xa75640e8, cellGcmUnbindZcull);
cellGcmSys.AddFunc(0x657571f7, cellGcmGetTileInfo);
cellGcmSys.AddFunc(0xd9a0a879, cellGcmGetZcullInfo);
cellGcmSys.AddFunc(0x0e6b0dae, cellGcmGetDisplayInfo);
cellGcmSys.AddFunc(0x93806525, cellGcmGetCurrentDisplayBufferId);
// Memory Mapping
cellGcmSys.AddFunc(0x21ac3697, cellGcmAddressToOffset);
cellGcmSys.AddFunc(0xfb81c03e, cellGcmGetMaxIoMapSize);
cellGcmSys.AddFunc(0x2922aed0, cellGcmGetOffsetTable);
cellGcmSys.AddFunc(0x2a6fba9c, cellGcmIoOffsetToAddress);
cellGcmSys.AddFunc(0x63441cb4, cellGcmMapEaIoAddress);
cellGcmSys.AddFunc(0x626e8518, cellGcmMapEaIoAddressWithFlags);
cellGcmSys.AddFunc(0xdb769b32, cellGcmMapLocalMemory);
cellGcmSys.AddFunc(0xa114ec67, cellGcmMapMainMemory);
cellGcmSys.AddFunc(0xa7ede268, cellGcmReserveIoMapSize);
cellGcmSys.AddFunc(0xefd00f54, cellGcmUnmapEaIoAddress);
cellGcmSys.AddFunc(0xdb23e867, cellGcmUnmapIoAddress);
cellGcmSys.AddFunc(0x3b9bd5bd, cellGcmUnreserveIoMapSize);
// Cursor
cellGcmSys.AddFunc(0x107bf3a1, cellGcmInitCursor);
cellGcmSys.AddFunc(0xc47d0812, cellGcmSetCursorEnable);
cellGcmSys.AddFunc(0x69c6cc82, cellGcmSetCursorDisable);
cellGcmSys.AddFunc(0xf9bfdc72, cellGcmSetCursorImageOffset);
cellGcmSys.AddFunc(0x1a0de550, cellGcmSetCursorPosition);
cellGcmSys.AddFunc(0xbd2fa0a7, cellGcmUpdateCursor);
// Functions for Maintaining Compatibility
//cellGcmSys.AddFunc(, cellGcmGetCurrentBuffer);
//cellGcmSys.AddFunc(, cellGcmSetCurrentBuffer);
cellGcmSys.AddFunc(0xbc982946, cellGcmSetDefaultCommandBuffer);
//cellGcmSys.AddFunc(, cellGcmSetDefaultCommandBufferAndSegmentWordSize);
//cellGcmSys.AddFunc(, cellGcmSetUserCallback);
// Other
cellGcmSys.AddFunc(0x21397818, cellGcmSetFlipCommand);
cellGcmSys.AddFunc(0x3a33c1fd, cellGcmFunc15);
cellGcmSys.AddFunc(0xd8f88e1a, cellGcmSetFlipCommandWithWaitLabel);
cellGcmSys.AddFunc(0xd0b1d189, cellGcmSetTile);
}
void cellGcmSys_load()
{
current_config.ioAddress = 0;
current_config.localAddress = 0;
local_size = 0;
local_addr = 0;
}
void cellGcmSys_unload()
{
}
| Java |
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2021 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
use Glpi\Toolbox\VersionParser;
/**
* Update class
**/
class Update {
private $args = [];
private $DB;
private $migration;
private $version;
private $dbversion;
private $language;
/**
* Constructor
*
* @param object $DB Database instance
* @param array $args Command line arguments; default to empty array
*/
public function __construct($DB, $args = []) {
$this->DB = $DB;
$this->args = $args;
}
/**
* Initialize session for update
*
* @return void
*/
public function initSession() {
if (is_writable(GLPI_SESSION_DIR)) {
Session::setPath();
} else {
if (isCommandLine()) {
die("Can't write in ".GLPI_SESSION_DIR."\n");
}
}
Session::start();
if (isCommandLine()) {
// Init debug variable
$_SESSION = ['glpilanguage' => (isset($this->args['lang']) ? $this->args['lang'] : 'en_GB')];
$_SESSION["glpi_currenttime"] = date("Y-m-d H:i:s");
}
// Init debug variable
// Only show errors
Toolbox::setDebugMode(Session::DEBUG_MODE, 0, 0, 1);
}
/**
* Get current values (versions, lang, ...)
*
* @return array
*/
public function getCurrents() {
$currents = [];
$DB = $this->DB;
if (!$DB->tableExists('glpi_config') && !$DB->tableExists('glpi_configs')) {
//very, very old version!
$currents = [
'version' => '0.1',
'dbversion' => '0.1',
'language' => 'en_GB'
];
} else if (!$DB->tableExists("glpi_configs")) {
// < 0.78
// Get current version
$result = $DB->request([
'SELECT' => ['version', 'language'],
'FROM' => 'glpi_config'
])->current();
$currents['version'] = trim($result['version']);
$currents['dbversion'] = $currents['version'];
$currents['language'] = trim($result['language']);
} else if ($DB->fieldExists('glpi_configs', 'version')) {
// < 0.85
// Get current version and language
$result = $DB->request([
'SELECT' => ['version', 'language'],
'FROM' => 'glpi_configs'
])->current();
$currents['version'] = trim($result['version']);
$currents['dbversion'] = $currents['version'];
$currents['language'] = trim($result['language']);
} else {
$currents = Config::getConfigurationValues(
'core',
['version', 'dbversion', 'language']
);
if (!isset($currents['dbversion'])) {
$currents['dbversion'] = $currents['version'];
}
}
$this->version = $currents['version'];
$this->dbversion = $currents['dbversion'];
$this->language = $currents['language'];
return $currents;
}
/**
* Run updates
*
* @param string $current_version Current version
* @param bool $force_latest Force replay of latest migration
*
* @return void
*/
public function doUpdates($current_version = null, bool $force_latest = false) {
if ($current_version === null) {
if ($this->version === null) {
throw new \RuntimeException('Cannot process updates without any version specified!');
}
$current_version = $this->version;
}
$DB = $this->DB;
// To prevent problem of execution time
ini_set("max_execution_time", "0");
if (version_compare($current_version, '0.80', 'lt')) {
die('Upgrade is not supported before 0.80!');
die(1);
}
// Update process desactivate all plugins
$plugin = new Plugin();
$plugin->unactivateAll();
if (version_compare($current_version, '0.80', '<') || version_compare($current_version, GLPI_VERSION, '>')) {
$message = sprintf(
__('Unsupported version (%1$s)'),
$current_version
);
if (isCommandLine()) {
echo "$message\n";
die(1);
} else {
$this->migration->displayWarning($message, true);
die(1);
}
}
$migrations = $this->getMigrationsToDo($current_version, $force_latest);
foreach ($migrations as $file => $function) {
include_once($file);
$function();
}
if (($myisam_count = $DB->getMyIsamTables()->count()) > 0) {
$message = sprintf(__('%d tables are using the deprecated MyISAM storage engine.'), $myisam_count)
. ' '
. sprintf(__('Run the "php bin/console %1$s" command to migrate them.'), 'glpi:migration:myisam_to_innodb');
$this->migration->displayError($message);
}
if (($datetime_count = $DB->getTzIncompatibleTables()->count()) > 0) {
$message = sprintf(__('%1$s columns are using the deprecated datetime storage field type.'), $datetime_count)
. ' '
. sprintf(__('Run the "php bin/console %1$s" command to migrate them.'), 'glpi:migration:timestamps');
$this->migration->displayError($message);
}
/*
* FIXME: Remove `$DB->use_utf8mb4` condition GLPI 10.1.
* This condition is here only to prevent having this message on every migration GLPI 10.0.
* Indeed, as migration command was not available in previous versions, users may not understand
* why this is considered as an error.
*/
if ($DB->use_utf8mb4 && ($non_utf8mb4_count = $DB->getNonUtf8mb4Tables()->count()) > 0) {
$message = sprintf(__('%1$s tables are using the deprecated utf8mb3 storage charset.'), $non_utf8mb4_count)
. ' '
. sprintf(__('Run the "php bin/console %1$s" command to migrate them.'), 'glpi:migration:utf8mb4');
$this->migration->displayError($message);
}
// Update version number and default langage and new version_founded ---- LEAVE AT THE END
Config::setConfigurationValues('core', ['version' => GLPI_VERSION,
'dbversion' => GLPI_SCHEMA_VERSION,
'language' => $this->language,
'founded_new_version' => '']);
if (defined('GLPI_SYSTEM_CRON')) {
// Downstream packages may provide a good system cron
$DB->updateOrDie(
'glpi_crontasks', [
'mode' => 2
], [
'name' => ['!=', 'watcher'],
'allowmode' => ['&', 2]
]
);
}
// Reset telemetry if its state is running, assuming it remained stuck due to telemetry service issue (see #7492).
$crontask_telemetry = new CronTask();
$crontask_telemetry->getFromDBbyName("Telemetry", "telemetry");
if ($crontask_telemetry->fields['state'] === CronTask::STATE_RUNNING) {
$crontask_telemetry->resetDate();
$crontask_telemetry->resetState();
}
//generate security key if missing, and update db
$glpikey = new GLPIKey();
if (!$glpikey->keyExists() && !$glpikey->generate()) {
$this->migration->displayWarning(__('Unable to create security key file! You have to run "php bin/console glpi:security:change_key" command to manually create this file.'), true);
}
}
/**
* Set migration
*
* @param Migration $migration Migration instance
*
* @return Update
*/
public function setMigration(Migration $migration) {
$this->migration = $migration;
return $this;
}
/**
* Check if expected security key file is missing.
*
* @return bool
*/
public function isExpectedSecurityKeyFileMissing(): bool {
$expected_key_path = $this->getExpectedSecurityKeyFilePath();
if ($expected_key_path === null) {
return false;
}
return !file_exists($expected_key_path);
}
/**
* Returns expected security key file path.
* Will return null for GLPI versions that was not yet handling a custom security key.
*
* @return string|null
*/
public function getExpectedSecurityKeyFilePath(): ?string {
$glpikey = new GLPIKey();
return $glpikey->getExpectedKeyPath($this->getCurrents()['version']);
}
/**
* Get migrations that have to be ran.
*
* @param string $current_version
* @param bool $force_latest
*
* @return array
*/
public function getMigrationsToDo(string $current_version, bool $force_latest = false): array {
$migrations = [];
$current_version = VersionParser::getNormalizedVersion($current_version);
$pattern = '/^update_(?<source_version>\d+\.\d+\.(?:\d+|x))_to_(?<target_version>\d+\.\d+\.(?:\d+|x))\.php$/';
$migration_iterator = new DirectoryIterator(GLPI_ROOT . '/install/migrations/');
foreach ($migration_iterator as $file) {
$versions_matches = [];
if ($file->isDir() || $file->isDot() || preg_match($pattern, $file->getFilename(), $versions_matches) !== 1) {
continue;
}
$force_migration = false;
if ($current_version === '9.2.2' && $versions_matches['target_version'] === '9.2.2') {
//9.2.2 upgrade script was not run from the release, see https://github.com/glpi-project/glpi/issues/3659
$force_migration = true;
} else if ($force_latest && version_compare($versions_matches['target_version'], $current_version, '=')) {
$force_migration = true;
}
if (version_compare($versions_matches['target_version'], $current_version, '>') || $force_migration) {
$migrations[$file->getRealPath()] = preg_replace(
'/^update_(\d+)\.(\d+)\.(\d+|x)_to_(\d+)\.(\d+)\.(\d+|x)\.php$/',
'update$1$2$3to$4$5$6',
$file->getBasename()
);
}
}
ksort($migrations);
return $migrations;
}
}
| Java |
#!/bin/sh
source /etc/scripts/functions.sh
case $1 in
deconfig)
net_if_reset $interface dhcp
;;
bound|renew)
net_if_config $interface dhcp "$ip" "$subnet" "$router" "$dns"
;;
esac
| Java |
#!/usr/bin/env rspec
require_relative "../../../test_helper"
require "yaml"
require "users/clients/auto"
require "y2users/autoinst/reader"
require "y2issues"
Yast.import "Report"
# defines exported users
require_relative "../../../fixtures/users_export"
describe Y2Users::Clients::Auto do
let(:mode) { "autoinstallation" }
let(:args) { [func] }
before do
allow(Yast).to receive(:import).and_call_original
allow(Yast).to receive(:import).with("Ldap")
allow(Yast).to receive(:import).with("LdapPopup")
allow(Yast::Mode).to receive(:mode).and_return(mode)
allow(Yast::Stage).to receive(:initial).and_return(true)
allow(Yast::WFM).to receive(:Args).and_return(args)
end
describe "#run" do
context "Import" do
let(:func) { "Import" }
let(:args) { [func, users] }
context "when double users have been given in the profile" do
let(:mode) { "normal" }
let(:users) { YAML.load_file(FIXTURES_PATH.join("users_error.yml")) }
it "report error" do
allow(Yast::Stage).to receive(:initial).and_return(false)
expect(Yast::Report).to receive(:Error)
.with(_("Found users in profile with equal <username>."))
expect(Yast::Report).to receive(:Error)
.with(_("Found users in profile with equal <uid>."))
expect(subject.run).to eq(true)
end
end
context "when users without any UID are defined in the profile" do
let(:users) { YAML.load_file(FIXTURES_PATH.join("users_no_error.yml")) }
it "will not be checked for double UIDs" do
expect(Yast::Report).not_to receive(:Error)
.with(_("Found users in profile with equal <username>."))
expect(Yast::Report).not_to receive(:Error)
.with(_("Found users in profile with equal <uid>."))
expect(subject.run).to eq(true)
end
end
context "when root password linuxrc attribute is set" do
before do
allow(Yast::Linuxrc).to receive(:InstallInf).with("RootPassword").and_return("test")
end
context "when profile contain root password" do
let(:users) { USERS_EXPORT }
it "keeps root password from profile" do
allow(Y2Issues).to receive(:report).and_return(true) # fixture contain dup uids
expect(subject.run).to eq(true)
config = Y2Users::ConfigManager.instance.target
root_user = config.users.root
expect(root_user.password.value.encrypted?).to eq true
expect(root_user.password.value.content).to match(/^\$6\$AS/)
end
end
context "when profile does not contain root password" do
let(:users) { {} }
it "sets root password to linuxrc value" do
expect(subject.run).to eq(true)
config = Y2Users::ConfigManager.instance.target
root_user = config.users.root
expect(root_user.password.value.encrypted?).to eq false
expect(root_user.password.value.content).to eq "test"
end
end
end
context "when some issue is registered" do
let(:users) { { "users" => [] } }
let(:reader) { Y2Users::Autoinst::Reader.new(users) }
let(:issues) { Y2Issues::List.new }
let(:continue?) { true }
let(:result) do
Y2Users::ReadResult.new(Y2Users::Config.new, issues)
end
before do
allow(Y2Users::Autoinst::Reader).to receive(:new).and_return(reader)
allow(reader).to receive(:read).and_return(result)
issues << Y2Issues::InvalidValue.new("dummy", location: nil)
allow(Y2Issues).to receive(:report).and_return(continue?)
end
it "reports the issues" do
expect(Y2Issues).to receive(:report).with(issues)
subject.run
end
context "and the user wants to continue" do
let(:continue?) { true }
it "returns true" do
expect(subject.run).to eq(true)
end
end
context "and the user does not want to continue" do
let(:continue?) { false }
it "returns false" do
expect(subject.run).to eq(false)
end
end
end
end
context "Change" do
let(:func) { "Change" }
it "returns the 'summary' autosequence result" do
expect(subject).to receive(:AutoSequence).and_return(:next)
expect(subject.run).to eq(:next)
end
end
context "Summary" do
let(:func) { "Summary" }
before do
allow(Yast::Users).to receive(:Summary).and_return("summary")
end
it "returns the users summary" do
expect(subject.run).to eq("summary")
end
end
context "Export" do
let(:func) { "Export" }
let(:args) { [func] }
let(:local_users) { double("local_users") }
let(:all_users) { double("all_users") }
before do
allow(Yast::WFM).to receive(:Args).and_return(args)
allow(Yast::Users).to receive(:Export).with("default")
.and_return(all_users)
allow(Yast::Users).to receive(:Export).with("compact")
.and_return(local_users)
end
it "exports all users and groups" do
expect(subject.run).to eq(all_users)
end
context "when 'compact' export is wanted" do
let(:args) { [func, "target" => "compact"] }
it "it exports only local users and groups" do
expect(subject.run).to eq(local_users)
end
end
end
context "Modified" do
let(:func) { "GetModified" }
before do
allow(Yast::Users).to receive(:Modified).and_return(true)
end
it "returns whether the data in Users module has been modified" do
expect(subject.run).to eq(true)
end
end
context "SetModified" do
let(:func) { "SetModified" }
it "sets the Users module as modified" do
expect(Yast::Users).to receive(:SetModified).with(true)
subject.run
end
end
context "Reset" do
let(:func) { "Reset" }
it "removes the configuration object" do
# reset is not called during installation
allow(Yast::Stage).to receive(:initial).and_return(false)
expect(Yast::Users).to receive(:Import).with({})
subject.run
end
end
end
end
| Java |
=head1 NAME
POSIX - Perl interface to IEEE Std 1003.1
=head1 SYNOPSIS
use POSIX ();
use POSIX qw(setsid);
use POSIX qw(:errno_h :fcntl_h);
printf "EINTR is %d\n", EINTR;
$sess_id = POSIX::setsid();
$fd = POSIX::open($path, O_CREAT|O_EXCL|O_WRONLY, 0644);
# note: that's a filedescriptor, *NOT* a filehandle
=head1 DESCRIPTION
The POSIX module permits you to access all (or nearly all) the standard
POSIX 1003.1 identifiers. Many of these identifiers have been given Perl-ish
interfaces.
I<Everything is exported by default> with the exception of any POSIX
functions with the same name as a built-in Perl function, such as
C<abs>, C<alarm>, C<rmdir>, C<write>, etc.., which will be exported
only if you ask for them explicitly. This is an unfortunate backwards
compatibility feature. You can stop the exporting by saying S<C<use
POSIX ()>> and then use the fully qualified names (I<e.g.>, C<POSIX::SEEK_END>),
or by giving an explicit import list. If you do neither, and opt for the
default, S<C<use POSIX;>> has to import I<553 symbols>.
This document gives a condensed list of the features available in the POSIX
module. Consult your operating system's manpages for general information on
most features. Consult L<perlfunc> for functions which are noted as being
identical to Perl's builtin functions.
The first section describes POSIX functions from the 1003.1 specification.
The second section describes some classes for signal objects, TTY objects,
and other miscellaneous objects. The remaining sections list various
constants and macros in an organization which roughly follows IEEE Std
1003.1b-1993.
=head1 CAVEATS
A few functions are not implemented because they are C specific. If you
attempt to call these, they will print a message telling you that they
aren't implemented, and suggest using the Perl equivalent, should one
exist. For example, trying to access the C<setjmp()> call will elicit the
message "C<setjmp() is C-specific: use eval {} instead>".
Furthermore, some evil vendors will claim 1003.1 compliance, but in fact
are not so: they will not pass the PCTS (POSIX Compliance Test Suites).
For example, one vendor may not define C<EDEADLK>, or the semantics of the
errno values set by C<open(2)> might not be quite right. Perl does not
attempt to verify POSIX compliance. That means you can currently
successfully say "use POSIX", and then later in your program you find
that your vendor has been lax and there's no usable C<ICANON> macro after
all. This could be construed to be a bug.
=head1 FUNCTIONS
=over 8
=item C<_exit>
This is identical to the C function C<_exit()>. It exits the program
immediately which means among other things buffered I/O is B<not> flushed.
Note that when using threads and in Linux this is B<not> a good way to
exit a thread because in Linux processes and threads are kind of the
same thing (Note: while this is the situation in early 2003 there are
projects under way to have threads with more POSIXly semantics in Linux).
If you want not to return from a thread, detach the thread.
=item C<abort>
This is identical to the C function C<abort()>. It terminates the
process with a C<SIGABRT> signal unless caught by a signal handler or
if the handler does not return normally (it e.g. does a C<longjmp>).
=item C<abs>
This is identical to Perl's builtin C<abs()> function, returning
the absolute value of its numerical argument.
=item C<access>
Determines the accessibility of a file.
if( POSIX::access( "/", &POSIX::R_OK ) ){
print "have read permission\n";
}
Returns C<undef> on failure. Note: do not use C<access()> for
security purposes. Between the C<access()> call and the operation
you are preparing for the permissions might change: a classic
I<race condition>.
=item C<acos>
This is identical to the C function C<acos()>, returning
the arcus cosine of its numerical argument. See also L<Math::Trig>.
=item C<alarm>
This is identical to Perl's builtin C<alarm()> function,
either for arming or disarming the C<SIGARLM> timer.
=item C<asctime>
This is identical to the C function C<asctime()>. It returns
a string of the form
"Fri Jun 2 18:22:13 2000\n\0"
and it is called thusly
$asctime = asctime($sec, $min, $hour, $mday, $mon,
$year, $wday, $yday, $isdst);
The C<$mon> is zero-based: January equals C<0>. The C<$year> is
1900-based: 2001 equals C<101>. C<$wday> and C<$yday> default to zero
(and are usually ignored anyway), and C<$isdst> defaults to -1.
=item C<asin>
This is identical to the C function C<asin()>, returning
the arcus sine of its numerical argument. See also L<Math::Trig>.
=item C<assert>
Unimplemented, but you can use L<perlfunc/die> and the L<Carp> module
to achieve similar things.
=item C<atan>
This is identical to the C function C<atan()>, returning the
arcus tangent of its numerical argument. See also L<Math::Trig>.
=item C<atan2>
This is identical to Perl's builtin C<atan2()> function, returning
the arcus tangent defined by its two numerical arguments, the I<y>
coordinate and the I<x> coordinate. See also L<Math::Trig>.
=item C<atexit>
C<atexit()> is C-specific: use C<END {}> instead, see L<perlsub>.
=item C<atof>
C<atof()> is C-specific. Perl converts strings to numbers transparently.
If you need to force a scalar to a number, add a zero to it.
=item C<atoi>
C<atoi()> is C-specific. Perl converts strings to numbers transparently.
If you need to force a scalar to a number, add a zero to it.
If you need to have just the integer part, see L<perlfunc/int>.
=item C<atol>
C<atol()> is C-specific. Perl converts strings to numbers transparently.
If you need to force a scalar to a number, add a zero to it.
If you need to have just the integer part, see L<perlfunc/int>.
=item C<bsearch>
C<bsearch()> not supplied. For doing binary search on wordlists,
see L<Search::Dict>.
=item C<calloc>
C<calloc()> is C-specific. Perl does memory management transparently.
=item C<ceil>
This is identical to the C function C<ceil()>, returning the smallest
integer value greater than or equal to the given numerical argument.
=item C<chdir>
This is identical to Perl's builtin C<chdir()> function, allowing
one to change the working (default) directory, see L<perlfunc/chdir>.
=item C<chmod>
This is identical to Perl's builtin C<chmod()> function, allowing
one to change file and directory permissions, see L<perlfunc/chmod>.
=item C<chown>
This is identical to Perl's builtin C<chown()> function, allowing one
to change file and directory owners and groups, see L<perlfunc/chown>.
=item C<clearerr>
Use the method C<IO::Handle::clearerr()> instead, to reset the error
state (if any) and EOF state (if any) of the given stream.
=item C<clock>
This is identical to the C function C<clock()>, returning the
amount of spent processor time in microseconds.
=item C<close>
Close the file. This uses file descriptors such as those obtained by calling
C<POSIX::open>.
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
POSIX::close( $fd );
Returns C<undef> on failure.
See also L<perlfunc/close>.
=item C<closedir>
This is identical to Perl's builtin C<closedir()> function for closing
a directory handle, see L<perlfunc/closedir>.
=item C<cos>
This is identical to Perl's builtin C<cos()> function, for returning
the cosine of its numerical argument, see L<perlfunc/cos>.
See also L<Math::Trig>.
=item C<cosh>
This is identical to the C function C<cosh()>, for returning
the hyperbolic cosine of its numeric argument. See also L<Math::Trig>.
=item C<creat>
Create a new file. This returns a file descriptor like the ones returned by
C<POSIX::open>. Use C<POSIX::close> to close the file.
$fd = POSIX::creat( "foo", 0611 );
POSIX::close( $fd );
See also L<perlfunc/sysopen> and its C<O_CREAT> flag.
=item C<ctermid>
Generates the path name for the controlling terminal.
$path = POSIX::ctermid();
=item C<ctime>
This is identical to the C function C<ctime()> and equivalent
to C<asctime(localtime(...))>, see L</asctime> and L</localtime>.
=item C<cuserid>
Get the login name of the owner of the current process.
$name = POSIX::cuserid();
=item C<difftime>
This is identical to the C function C<difftime()>, for returning
the time difference (in seconds) between two times (as returned
by C<time()>), see L</time>.
=item C<div>
C<div()> is C-specific, use L<perlfunc/int> on the usual C</> division and
the modulus C<%>.
=item C<dup>
This is similar to the C function C<dup()>, for duplicating a file
descriptor.
This uses file descriptors such as those obtained by calling
C<POSIX::open>.
Returns C<undef> on failure.
=item C<dup2>
This is similar to the C function C<dup2()>, for duplicating a file
descriptor to an another known file descriptor.
This uses file descriptors such as those obtained by calling
C<POSIX::open>.
Returns C<undef> on failure.
=item C<errno>
Returns the value of errno.
$errno = POSIX::errno();
This identical to the numerical values of the C<$!>, see L<perlvar/$ERRNO>.
=item C<execl>
C<execl()> is C-specific, see L<perlfunc/exec>.
=item C<execle>
C<execle()> is C-specific, see L<perlfunc/exec>.
=item C<execlp>
C<execlp()> is C-specific, see L<perlfunc/exec>.
=item C<execv>
C<execv()> is C-specific, see L<perlfunc/exec>.
=item C<execve>
C<execve()> is C-specific, see L<perlfunc/exec>.
=item C<execvp>
C<execvp()> is C-specific, see L<perlfunc/exec>.
=item C<exit>
This is identical to Perl's builtin C<exit()> function for exiting the
program, see L<perlfunc/exit>.
=item C<exp>
This is identical to Perl's builtin C<exp()> function for
returning the exponent (I<e>-based) of the numerical argument,
see L<perlfunc/exp>.
=item C<fabs>
This is identical to Perl's builtin C<abs()> function for returning
the absolute value of the numerical argument, see L<perlfunc/abs>.
=item C<fclose>
Use method C<IO::Handle::close()> instead, or see L<perlfunc/close>.
=item C<fcntl>
This is identical to Perl's builtin C<fcntl()> function,
see L<perlfunc/fcntl>.
=item C<fdopen>
Use method C<IO::Handle::new_from_fd()> instead, or see L<perlfunc/open>.
=item C<feof>
Use method C<IO::Handle::eof()> instead, or see L<perlfunc/eof>.
=item C<ferror>
Use method C<IO::Handle::error()> instead.
=item C<fflush>
Use method C<IO::Handle::flush()> instead.
See also C<L<perlvar/$OUTPUT_AUTOFLUSH>>.
=item C<fgetc>
Use method C<IO::Handle::getc()> instead, or see L<perlfunc/read>.
=item C<fgetpos>
Use method C<IO::Seekable::getpos()> instead, or see L<perlfunc/seek>.
=item C<fgets>
Use method C<IO::Handle::gets()> instead. Similar to E<lt>E<gt>, also known
as L<perlfunc/readline>.
=item C<fileno>
Use method C<IO::Handle::fileno()> instead, or see L<perlfunc/fileno>.
=item C<floor>
This is identical to the C function C<floor()>, returning the largest
integer value less than or equal to the numerical argument.
=item C<fmod>
This is identical to the C function C<fmod()>.
$r = fmod($x, $y);
It returns the remainder C<$r = $x - $n*$y>, where C<$n = trunc($x/$y)>.
The C<$r> has the same sign as C<$x> and magnitude (absolute value)
less than the magnitude of C<$y>.
=item C<fopen>
Use method C<IO::File::open()> instead, or see L<perlfunc/open>.
=item C<fork>
This is identical to Perl's builtin C<fork()> function
for duplicating the current process, see L<perlfunc/fork>
and L<perlfork> if you are in Windows.
=item C<fpathconf>
Retrieves the value of a configurable limit on a file or directory. This
uses file descriptors such as those obtained by calling C<POSIX::open>.
The following will determine the maximum length of the longest allowable
pathname on the filesystem which holds F</var/foo>.
$fd = POSIX::open( "/var/foo", &POSIX::O_RDONLY );
$path_max = POSIX::fpathconf($fd, &POSIX::_PC_PATH_MAX);
Returns C<undef> on failure.
=item C<fprintf>
C<fprintf()> is C-specific, see L<perlfunc/printf> instead.
=item C<fputc>
C<fputc()> is C-specific, see L<perlfunc/print> instead.
=item C<fputs>
C<fputs()> is C-specific, see L<perlfunc/print> instead.
=item C<fread>
C<fread()> is C-specific, see L<perlfunc/read> instead.
=item C<free>
C<free()> is C-specific. Perl does memory management transparently.
=item C<freopen>
C<freopen()> is C-specific, see L<perlfunc/open> instead.
=item C<frexp>
Return the mantissa and exponent of a floating-point number.
($mantissa, $exponent) = POSIX::frexp( 1.234e56 );
=item C<fscanf>
C<fscanf()> is C-specific, use E<lt>E<gt> and regular expressions instead.
=item C<fseek>
Use method C<IO::Seekable::seek()> instead, or see L<perlfunc/seek>.
=item C<fsetpos>
Use method C<IO::Seekable::setpos()> instead, or seek L<perlfunc/seek>.
=item C<fstat>
Get file status. This uses file descriptors such as those obtained by
calling C<POSIX::open>. The data returned is identical to the data from
Perl's builtin C<stat> function.
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
@stats = POSIX::fstat( $fd );
=item C<fsync>
Use method C<IO::Handle::sync()> instead.
=item C<ftell>
Use method C<IO::Seekable::tell()> instead, or see L<perlfunc/tell>.
=item C<fwrite>
C<fwrite()> is C-specific, see L<perlfunc/print> instead.
=item C<getc>
This is identical to Perl's builtin C<getc()> function,
see L<perlfunc/getc>.
=item C<getchar>
Returns one character from STDIN. Identical to Perl's C<getc()>,
see L<perlfunc/getc>.
=item C<getcwd>
Returns the name of the current working directory.
See also L<Cwd>.
=item C<getegid>
Returns the effective group identifier. Similar to Perl' s builtin
variable C<$(>, see L<perlvar/$EGID>.
=item C<getenv>
Returns the value of the specified environment variable.
The same information is available through the C<%ENV> array.
=item C<geteuid>
Returns the effective user identifier. Identical to Perl's builtin C<$E<gt>>
variable, see L<perlvar/$EUID>.
=item C<getgid>
Returns the user's real group identifier. Similar to Perl's builtin
variable C<$)>, see L<perlvar/$GID>.
=item C<getgrgid>
This is identical to Perl's builtin C<getgrgid()> function for
returning group entries by group identifiers, see
L<perlfunc/getgrgid>.
=item C<getgrnam>
This is identical to Perl's builtin C<getgrnam()> function for
returning group entries by group names, see L<perlfunc/getgrnam>.
=item C<getgroups>
Returns the ids of the user's supplementary groups. Similar to Perl's
builtin variable C<$)>, see L<perlvar/$GID>.
=item C<getlogin>
This is identical to Perl's builtin C<getlogin()> function for
returning the user name associated with the current session, see
L<perlfunc/getlogin>.
=item C<getpgrp>
This is identical to Perl's builtin C<getpgrp()> function for
returning the process group identifier of the current process, see
L<perlfunc/getpgrp>.
=item C<getpid>
Returns the process identifier. Identical to Perl's builtin
variable C<$$>, see L<perlvar/$PID>.
=item C<getppid>
This is identical to Perl's builtin C<getppid()> function for
returning the process identifier of the parent process of the current
process , see L<perlfunc/getppid>.
=item C<getpwnam>
This is identical to Perl's builtin C<getpwnam()> function for
returning user entries by user names, see L<perlfunc/getpwnam>.
=item C<getpwuid>
This is identical to Perl's builtin C<getpwuid()> function for
returning user entries by user identifiers, see L<perlfunc/getpwuid>.
=item C<gets>
Returns one line from C<STDIN>, similar to E<lt>E<gt>, also known
as the C<readline()> function, see L<perlfunc/readline>.
B<NOTE>: if you have C programs that still use C<gets()>, be very
afraid. The C<gets()> function is a source of endless grief because
it has no buffer overrun checks. It should B<never> be used. The
C<fgets()> function should be preferred instead.
=item C<getuid>
Returns the user's identifier. Identical to Perl's builtin C<$E<lt>> variable,
see L<perlvar/$UID>.
=item C<gmtime>
This is identical to Perl's builtin C<gmtime()> function for
converting seconds since the epoch to a date in Greenwich Mean Time,
see L<perlfunc/gmtime>.
=item C<isalnum>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:alnum:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
You may want to use the C<L<E<sol>\wE<sol>|perlrecharclass/Word
characters>> construct instead.
=item C<isalpha>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:alpha:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<isatty>
Returns a boolean indicating whether the specified filehandle is connected
to a tty. Similar to the C<-t> operator, see L<perlfunc/-X>.
=item C<iscntrl>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:cntrl:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<isdigit>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:digit:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
You may want to use the C<L<E<sol>\dE<sol>|perlrecharclass/Digits>>
construct instead.
=item C<isgraph>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:graph:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<islower>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:lower:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
Do B<not> use C</[a-z]/> unless you don't care about the current locale.
=item C<isprint>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:print:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<ispunct>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:punct:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<isspace>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:space:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
You may want to use the C<L<E<sol>\sE<sol>|perlrecharclass/Whitespace>>
construct instead.
=item C<isupper>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:upper:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
Do B<not> use C</[A-Z]/> unless you don't care about the current locale.
=item C<isxdigit>
Deprecated function whose use raises a warning, and which is slated to
be removed in a future Perl version. It is very similar to matching
against S<C<qr/ ^ [[:xdigit:]]+ $ /x>>, which you should convert to use
instead. The function is deprecated because 1) it doesn't handle UTF-8
encoded strings properly; and 2) it returns C<TRUE> even if the input is
the empty string. The function return is always based on the current
locale, whereas using locale rules is optional with the regular
expression, based on pragmas in effect and pattern modifiers (see
L<perlre/Character set modifiers> and L<perlre/Which character set
modifier is in effect?>).
The function returns C<TRUE> if the input string is empty, or if the
corresponding C function returns C<TRUE> for every byte in the string.
=item C<kill>
This is identical to Perl's builtin C<kill()> function for sending
signals to processes (often to terminate them), see L<perlfunc/kill>.
=item C<labs>
(For returning absolute values of long integers.)
C<labs()> is C-specific, see L<perlfunc/abs> instead.
=item C<lchown>
This is identical to the C function, except the order of arguments is
consistent with Perl's builtin C<chown()> with the added restriction
of only one path, not an list of paths. Does the same thing as the
C<chown()> function but changes the owner of a symbolic link instead
of the file the symbolic link points to.
=item C<ldexp>
This is identical to the C function C<ldexp()>
for multiplying floating point numbers with powers of two.
$x_quadrupled = POSIX::ldexp($x, 2);
=item C<ldiv>
(For computing dividends of long integers.)
C<ldiv()> is C-specific, use C</> and C<int()> instead.
=item C<link>
This is identical to Perl's builtin C<link()> function
for creating hard links into files, see L<perlfunc/link>.
=item C<localeconv>
Get numeric formatting information. Returns a reference to a hash
containing the current locale formatting values. Users of this function
should also read L<perllocale>, which provides a comprehensive
discussion of Perl locale handling, including
L<a section devoted to this function|perllocale/The localeconv function>.
Here is how to query the database for the B<de> (Deutsch or German) locale.
my $loc = POSIX::setlocale( &POSIX::LC_ALL, "de" );
print "Locale: \"$loc\"\n";
my $lconv = POSIX::localeconv();
foreach my $property (qw(
decimal_point
thousands_sep
grouping
int_curr_symbol
currency_symbol
mon_decimal_point
mon_thousands_sep
mon_grouping
positive_sign
negative_sign
int_frac_digits
frac_digits
p_cs_precedes
p_sep_by_space
n_cs_precedes
n_sep_by_space
p_sign_posn
n_sign_posn
))
{
printf qq(%s: "%s",\n),
$property, $lconv->{$property};
}
=item C<localtime>
This is identical to Perl's builtin C<localtime()> function for
converting seconds since the epoch to a date see L<perlfunc/localtime>.
=item C<log>
This is identical to Perl's builtin C<log()> function,
returning the natural (I<e>-based) logarithm of the numerical argument,
see L<perlfunc/log>.
=item C<log10>
This is identical to the C function C<log10()>,
returning the 10-base logarithm of the numerical argument.
You can also use
sub log10 { log($_[0]) / log(10) }
or
sub log10 { log($_[0]) / 2.30258509299405 }
or
sub log10 { log($_[0]) * 0.434294481903252 }
=item C<longjmp>
C<longjmp()> is C-specific: use L<perlfunc/die> instead.
=item C<lseek>
Move the file's read/write position. This uses file descriptors such as
those obtained by calling C<POSIX::open>.
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
$off_t = POSIX::lseek( $fd, 0, &POSIX::SEEK_SET );
Returns C<undef> on failure.
=item C<malloc>
C<malloc()> is C-specific. Perl does memory management transparently.
=item C<mblen>
This is identical to the C function C<mblen()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<mbstowcs>
This is identical to the C function C<mbstowcs()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<mbtowc>
This is identical to the C function C<mbtowc()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<memchr>
C<memchr()> is C-specific, see L<perlfunc/index> instead.
=item C<memcmp>
C<memcmp()> is C-specific, use C<eq> instead, see L<perlop>.
=item C<memcpy>
C<memcpy()> is C-specific, use C<=>, see L<perlop>, or see L<perlfunc/substr>.
=item C<memmove>
C<memmove()> is C-specific, use C<=>, see L<perlop>, or see L<perlfunc/substr>.
=item C<memset>
C<memset()> is C-specific, use C<x> instead, see L<perlop>.
=item C<mkdir>
This is identical to Perl's builtin C<mkdir()> function
for creating directories, see L<perlfunc/mkdir>.
=item C<mkfifo>
This is similar to the C function C<mkfifo()> for creating
FIFO special files.
if (mkfifo($path, $mode)) { ....
Returns C<undef> on failure. The C<$mode> is similar to the
mode of C<mkdir()>, see L<perlfunc/mkdir>, though for C<mkfifo>
you B<must> specify the C<$mode>.
=item C<mktime>
Convert date/time info to a calendar time.
Synopsis:
mktime(sec, min, hour, mday, mon, year, wday = 0,
yday = 0, isdst = -1)
The month (C<mon>), weekday (C<wday>), and yearday (C<yday>) begin at zero.
I.e. January is 0, not 1; Sunday is 0, not 1; January 1st is 0, not 1. The
year (C<year>) is given in years since 1900. I.e. The year 1995 is 95; the
year 2001 is 101. Consult your system's C<mktime()> manpage for details
about these and the other arguments.
Calendar time for December 12, 1995, at 10:30 am.
$time_t = POSIX::mktime( 0, 30, 10, 12, 11, 95 );
print "Date = ", POSIX::ctime($time_t);
Returns C<undef> on failure.
=item C<modf>
Return the integral and fractional parts of a floating-point number.
($fractional, $integral) = POSIX::modf( 3.14 );
=item C<nice>
This is similar to the C function C<nice()>, for changing
the scheduling preference of the current process. Positive
arguments mean more polite process, negative values more
needy process. Normal user processes can only be more polite.
Returns C<undef> on failure.
=item C<offsetof>
C<offsetof()> is C-specific, you probably want to see L<perlfunc/pack> instead.
=item C<open>
Open a file for reading for writing. This returns file descriptors, not
Perl filehandles. Use C<POSIX::close> to close the file.
Open a file read-only with mode 0666.
$fd = POSIX::open( "foo" );
Open a file for read and write.
$fd = POSIX::open( "foo", &POSIX::O_RDWR );
Open a file for write, with truncation.
$fd = POSIX::open(
"foo", &POSIX::O_WRONLY | &POSIX::O_TRUNC
);
Create a new file with mode 0640. Set up the file for writing.
$fd = POSIX::open(
"foo", &POSIX::O_CREAT | &POSIX::O_WRONLY, 0640
);
Returns C<undef> on failure.
See also L<perlfunc/sysopen>.
=item C<opendir>
Open a directory for reading.
$dir = POSIX::opendir( "/var" );
@files = POSIX::readdir( $dir );
POSIX::closedir( $dir );
Returns C<undef> on failure.
=item C<pathconf>
Retrieves the value of a configurable limit on a file or directory.
The following will determine the maximum length of the longest allowable
pathname on the filesystem which holds C</var>.
$path_max = POSIX::pathconf( "/var",
&POSIX::_PC_PATH_MAX );
Returns C<undef> on failure.
=item C<pause>
This is similar to the C function C<pause()>, which suspends
the execution of the current process until a signal is received.
Returns C<undef> on failure.
=item C<perror>
This is identical to the C function C<perror()>, which outputs to the
standard error stream the specified message followed by C<": "> and the
current error string. Use the C<warn()> function and the C<$!>
variable instead, see L<perlfunc/warn> and L<perlvar/$ERRNO>.
=item C<pipe>
Create an interprocess channel. This returns file descriptors like those
returned by C<POSIX::open>.
my ($read, $write) = POSIX::pipe();
POSIX::write( $write, "hello", 5 );
POSIX::read( $read, $buf, 5 );
See also L<perlfunc/pipe>.
=item C<pow>
Computes C<$x> raised to the power C<$exponent>.
$ret = POSIX::pow( $x, $exponent );
You can also use the C<**> operator, see L<perlop>.
=item C<printf>
Formats and prints the specified arguments to STDOUT.
See also L<perlfunc/printf>.
=item C<putc>
C<putc()> is C-specific, see L<perlfunc/print> instead.
=item C<putchar>
C<putchar()> is C-specific, see L<perlfunc/print> instead.
=item C<puts>
C<puts()> is C-specific, see L<perlfunc/print> instead.
=item C<qsort>
C<qsort()> is C-specific, see L<perlfunc/sort> instead.
=item C<raise>
Sends the specified signal to the current process.
See also L<perlfunc/kill> and the C<$$> in L<perlvar/$PID>.
=item C<rand>
C<rand()> is non-portable, see L<perlfunc/rand> instead.
=item C<read>
Read from a file. This uses file descriptors such as those obtained by
calling C<POSIX::open>. If the buffer C<$buf> is not large enough for the
read then Perl will extend it to make room for the request.
$fd = POSIX::open( "foo", &POSIX::O_RDONLY );
$bytes = POSIX::read( $fd, $buf, 3 );
Returns C<undef> on failure.
See also L<perlfunc/sysread>.
=item C<readdir>
This is identical to Perl's builtin C<readdir()> function
for reading directory entries, see L<perlfunc/readdir>.
=item C<realloc>
C<realloc()> is C-specific. Perl does memory management transparently.
=item C<remove>
This is identical to Perl's builtin C<unlink()> function
for removing files, see L<perlfunc/unlink>.
=item C<rename>
This is identical to Perl's builtin C<rename()> function
for renaming files, see L<perlfunc/rename>.
=item C<rewind>
Seeks to the beginning of the file.
=item C<rewinddir>
This is identical to Perl's builtin C<rewinddir()> function for
rewinding directory entry streams, see L<perlfunc/rewinddir>.
=item C<rmdir>
This is identical to Perl's builtin C<rmdir()> function
for removing (empty) directories, see L<perlfunc/rmdir>.
=item C<scanf>
C<scanf()> is C-specific, use E<lt>E<gt> and regular expressions instead,
see L<perlre>.
=item C<setgid>
Sets the real group identifier and the effective group identifier for
this process. Similar to assigning a value to the Perl's builtin
C<$)> variable, see L<perlvar/$EGID>, except that the latter
will change only the real user identifier, and that the setgid()
uses only a single numeric argument, as opposed to a space-separated
list of numbers.
=item C<setjmp>
C<setjmp()> is C-specific: use C<eval {}> instead,
see L<perlfunc/eval>.
=item C<setlocale>
Modifies and queries the program's underlying locale. Users of this
function should read L<perllocale>, whch provides a comprehensive
discussion of Perl locale handling, knowledge of which is necessary to
properly use this function. It contains
L<a section devoted to this function|perllocale/The setlocale function>.
The discussion here is merely a summary reference for C<setlocale()>.
Note that Perl itself is almost entirely unaffected by the locale
except within the scope of S<C<"use locale">>. (Exceptions are listed
in L<perllocale/Not within the scope of any "use locale" variant>.)
The following examples assume
use POSIX qw(setlocale LC_ALL LC_CTYPE);
has been issued.
The following will set the traditional UNIX system locale behavior
(the second argument C<"C">).
$loc = setlocale( LC_ALL, "C" );
The following will query the current C<LC_CTYPE> category. (No second
argument means 'query'.)
$loc = setlocale( LC_CTYPE );
The following will set the C<LC_CTYPE> behaviour according to the locale
environment variables (the second argument C<"">).
Please see your system's C<setlocale(3)> documentation for the locale
environment variables' meaning or consult L<perllocale>.
$loc = setlocale( LC_CTYPE, "" );
The following will set the C<LC_COLLATE> behaviour to Argentinian
Spanish. B<NOTE>: The naming and availability of locales depends on
your operating system. Please consult L<perllocale> for how to find
out which locales are available in your system.
$loc = setlocale( LC_COLLATE, "es_AR.ISO8859-1" );
=item C<setpgid>
This is similar to the C function C<setpgid()> for
setting the process group identifier of the current process.
Returns C<undef> on failure.
=item C<setsid>
This is identical to the C function C<setsid()> for
setting the session identifier of the current process.
=item C<setuid>
Sets the real user identifier and the effective user identifier for
this process. Similar to assigning a value to the Perl's builtin
C<$E<lt>> variable, see L<perlvar/$UID>, except that the latter
will change only the real user identifier.
=item C<sigaction>
Detailed signal management. This uses C<POSIX::SigAction> objects for
the C<action> and C<oldaction> arguments (the oldaction can also be
just a hash reference). Consult your system's C<sigaction> manpage
for details, see also C<POSIX::SigRt>.
Synopsis:
sigaction(signal, action, oldaction = 0)
Returns C<undef> on failure. The C<signal> must be a number (like
C<SIGHUP>), not a string (like C<"SIGHUP">), though Perl does try hard
to understand you.
If you use the C<SA_SIGINFO> flag, the signal handler will in addition to
the first argument, the signal name, also receive a second argument, a
hash reference, inside which are the following keys with the following
semantics, as defined by POSIX/SUSv3:
signo the signal number
errno the error number
code if this is zero or less, the signal was sent by
a user process and the uid and pid make sense,
otherwise the signal was sent by the kernel
The following are also defined by POSIX/SUSv3, but unfortunately
not very widely implemented:
pid the process id generating the signal
uid the uid of the process id generating the signal
status exit value or signal for SIGCHLD
band band event for SIGPOLL
A third argument is also passed to the handler, which contains a copy
of the raw binary contents of the C<siginfo> structure: if a system has
some non-POSIX fields, this third argument is where to C<unpack()> them
from.
Note that not all C<siginfo> values make sense simultaneously (some are
valid only for certain signals, for example), and not all values make
sense from Perl perspective, you should to consult your system's
C<sigaction> and possibly also C<siginfo> documentation.
=item C<siglongjmp>
C<siglongjmp()> is C-specific: use L<perlfunc/die> instead.
=item C<sigpending>
Examine signals that are blocked and pending. This uses C<POSIX::SigSet>
objects for the C<sigset> argument. Consult your system's C<sigpending>
manpage for details.
Synopsis:
sigpending(sigset)
Returns C<undef> on failure.
=item C<sigprocmask>
Change and/or examine calling process's signal mask. This uses
C<POSIX::SigSet> objects for the C<sigset> and C<oldsigset> arguments.
Consult your system's C<sigprocmask> manpage for details.
Synopsis:
sigprocmask(how, sigset, oldsigset = 0)
Returns C<undef> on failure.
Note that you can't reliably block or unblock a signal from its own signal
handler if you're using safe signals. Other signals can be blocked or unblocked
reliably.
=item C<sigsetjmp>
C<sigsetjmp()> is C-specific: use C<eval {}> instead,
see L<perlfunc/eval>.
=item C<sigsuspend>
Install a signal mask and suspend process until signal arrives. This uses
C<POSIX::SigSet> objects for the C<signal_mask> argument. Consult your
system's C<sigsuspend> manpage for details.
Synopsis:
sigsuspend(signal_mask)
Returns C<undef> on failure.
=item C<sin>
This is identical to Perl's builtin C<sin()> function
for returning the sine of the numerical argument,
see L<perlfunc/sin>. See also L<Math::Trig>.
=item C<sinh>
This is identical to the C function C<sinh()>
for returning the hyperbolic sine of the numerical argument.
See also L<Math::Trig>.
=item C<sleep>
This is functionally identical to Perl's builtin C<sleep()> function
for suspending the execution of the current for process for certain
number of seconds, see L<perlfunc/sleep>. There is one significant
difference, however: C<POSIX::sleep()> returns the number of
B<unslept> seconds, while the C<CORE::sleep()> returns the
number of slept seconds.
=item C<sprintf>
This is similar to Perl's builtin C<sprintf()> function
for returning a string that has the arguments formatted as requested,
see L<perlfunc/sprintf>.
=item C<sqrt>
This is identical to Perl's builtin C<sqrt()> function.
for returning the square root of the numerical argument,
see L<perlfunc/sqrt>.
=item C<srand>
Give a seed the pseudorandom number generator, see L<perlfunc/srand>.
=item C<sscanf>
C<sscanf()> is C-specific, use regular expressions instead,
see L<perlre>.
=item C<stat>
This is identical to Perl's builtin C<stat()> function
for returning information about files and directories.
=item C<strcat>
C<strcat()> is C-specific, use C<.=> instead, see L<perlop>.
=item C<strchr>
C<strchr()> is C-specific, see L<perlfunc/index> instead.
=item C<strcmp>
C<strcmp()> is C-specific, use C<eq> or C<cmp> instead, see L<perlop>.
=item C<strcoll>
This is identical to the C function C<strcoll()>
for collating (comparing) strings transformed using
the C<strxfrm()> function. Not really needed since
Perl can do this transparently, see L<perllocale>.
=item C<strcpy>
C<strcpy()> is C-specific, use C<=> instead, see L<perlop>.
=item C<strcspn>
C<strcspn()> is C-specific, use regular expressions instead,
see L<perlre>.
=item C<strerror>
Returns the error string for the specified errno.
Identical to the string form of the C<$!>, see L<perlvar/$ERRNO>.
=item C<strftime>
Convert date and time information to string. Returns the string.
Synopsis:
strftime(fmt, sec, min, hour, mday, mon, year,
wday = -1, yday = -1, isdst = -1)
The month (C<mon>), weekday (C<wday>), and yearday (C<yday>) begin at zero.
I.e. January is 0, not 1; Sunday is 0, not 1; January 1st is 0, not 1. The
year (C<year>) is given in years since 1900. I.e., the year 1995 is 95; the
year 2001 is 101. Consult your system's C<strftime()> manpage for details
about these and the other arguments.
If you want your code to be portable, your format (C<fmt>) argument
should use only the conversion specifiers defined by the ANSI C
standard (C89, to play safe). These are C<aAbBcdHIjmMpSUwWxXyYZ%>.
But even then, the B<results> of some of the conversion specifiers are
non-portable. For example, the specifiers C<aAbBcpZ> change according
to the locale settings of the user, and both how to set locales (the
locale names) and what output to expect are non-standard.
The specifier C<c> changes according to the timezone settings of the
user and the timezone computation rules of the operating system.
The C<Z> specifier is notoriously unportable since the names of
timezones are non-standard. Sticking to the numeric specifiers is the
safest route.
The given arguments are made consistent as though by calling
C<mktime()> before calling your system's C<strftime()> function,
except that the C<isdst> value is not affected.
The string for Tuesday, December 12, 1995.
$str = POSIX::strftime( "%A, %B %d, %Y",
0, 0, 0, 12, 11, 95, 2 );
print "$str\n";
=item C<strlen>
C<strlen()> is C-specific, use C<length()> instead, see L<perlfunc/length>.
=item C<strncat>
C<strncat()> is C-specific, use C<.=> instead, see L<perlop>.
=item C<strncmp>
C<strncmp()> is C-specific, use C<eq> instead, see L<perlop>.
=item C<strncpy>
C<strncpy()> is C-specific, use C<=> instead, see L<perlop>.
=item C<strpbrk>
C<strpbrk()> is C-specific, use regular expressions instead,
see L<perlre>.
=item C<strrchr>
C<strrchr()> is C-specific, see L<perlfunc/rindex> instead.
=item C<strspn>
C<strspn()> is C-specific, use regular expressions instead,
see L<perlre>.
=item C<strstr>
This is identical to Perl's builtin C<index()> function,
see L<perlfunc/index>.
=item C<strtod>
String to double translation. Returns the parsed number and the number
of characters in the unparsed portion of the string. Truly
POSIX-compliant systems set C<$!> (C<$ERRNO>) to indicate a translation
error, so clear C<$!> before calling strtod. However, non-POSIX systems
may not check for overflow, and therefore will never set C<$!>.
strtod respects any POSIX I<setlocale()> C<LC_TIME> settings,
regardless of whether or not it is called from Perl code that is within
the scope of S<C<use locale>>.
To parse a string C<$str> as a floating point number use
$! = 0;
($num, $n_unparsed) = POSIX::strtod($str);
The second returned item and C<$!> can be used to check for valid input:
if (($str eq '') || ($n_unparsed != 0) || $!) {
die "Non-numeric input $str" . ($! ? ": $!\n" : "\n");
}
When called in a scalar context strtod returns the parsed number.
=item C<strtok>
C<strtok()> is C-specific, use regular expressions instead, see
L<perlre>, or L<perlfunc/split>.
=item C<strtol>
String to (long) integer translation. Returns the parsed number and
the number of characters in the unparsed portion of the string. Truly
POSIX-compliant systems set C<$!> (C<$ERRNO>) to indicate a translation
error, so clear C<$!> before calling C<strtol>. However, non-POSIX systems
may not check for overflow, and therefore will never set C<$!>.
C<strtol> should respect any POSIX I<setlocale()> settings.
To parse a string C<$str> as a number in some base C<$base> use
$! = 0;
($num, $n_unparsed) = POSIX::strtol($str, $base);
The base should be zero or between 2 and 36, inclusive. When the base
is zero or omitted strtol will use the string itself to determine the
base: a leading "0x" or "0X" means hexadecimal; a leading "0" means
octal; any other leading characters mean decimal. Thus, "1234" is
parsed as a decimal number, "01234" as an octal number, and "0x1234"
as a hexadecimal number.
The second returned item and C<$!> can be used to check for valid input:
if (($str eq '') || ($n_unparsed != 0) || !$!) {
die "Non-numeric input $str" . $! ? ": $!\n" : "\n";
}
When called in a scalar context strtol returns the parsed number.
=item C<strtoul>
String to unsigned (long) integer translation. C<strtoul()> is identical
to C<strtol()> except that C<strtoul()> only parses unsigned integers. See
L</strtol> for details.
Note: Some vendors supply C<strtod()> and C<strtol()> but not C<strtoul()>.
Other vendors that do supply C<strtoul()> parse "-1" as a valid value.
=item C<strxfrm>
String transformation. Returns the transformed string.
$dst = POSIX::strxfrm( $src );
Used in conjunction with the C<strcoll()> function, see L</strcoll>.
Not really needed since Perl can do this transparently, see
L<perllocale>.
=item C<sysconf>
Retrieves values of system configurable variables.
The following will get the machine's clock speed.
$clock_ticks = POSIX::sysconf( &POSIX::_SC_CLK_TCK );
Returns C<undef> on failure.
=item C<system>
This is identical to Perl's builtin C<system()> function, see
L<perlfunc/system>.
=item C<tan>
This is identical to the C function C<tan()>, returning the
tangent of the numerical argument. See also L<Math::Trig>.
=item C<tanh>
This is identical to the C function C<tanh()>, returning the
hyperbolic tangent of the numerical argument. See also L<Math::Trig>.
=item C<tcdrain>
This is similar to the C function C<tcdrain()> for draining
the output queue of its argument stream.
Returns C<undef> on failure.
=item C<tcflow>
This is similar to the C function C<tcflow()> for controlling
the flow of its argument stream.
Returns C<undef> on failure.
=item C<tcflush>
This is similar to the C function C<tcflush()> for flushing
the I/O buffers of its argument stream.
Returns C<undef> on failure.
=item C<tcgetpgrp>
This is identical to the C function C<tcgetpgrp()> for returning the
process group identifier of the foreground process group of the controlling
terminal.
=item C<tcsendbreak>
This is similar to the C function C<tcsendbreak()> for sending
a break on its argument stream.
Returns C<undef> on failure.
=item C<tcsetpgrp>
This is similar to the C function C<tcsetpgrp()> for setting the
process group identifier of the foreground process group of the controlling
terminal.
Returns C<undef> on failure.
=item C<time>
This is identical to Perl's builtin C<time()> function
for returning the number of seconds since the epoch
(whatever it is for the system), see L<perlfunc/time>.
=item C<times>
The C<times()> function returns elapsed realtime since some point in the past
(such as system startup), user and system times for this process, and user
and system times used by child processes. All times are returned in clock
ticks.
($realtime, $user, $system, $cuser, $csystem)
= POSIX::times();
Note: Perl's builtin C<times()> function returns four values, measured in
seconds.
=item C<tmpfile>
Use method C<IO::File::new_tmpfile()> instead, or see L<File::Temp>.
=item C<tmpnam>
Returns a name for a temporary file.
$tmpfile = POSIX::tmpnam();
For security reasons, which are probably detailed in your system's
documentation for the C library C<tmpnam()> function, this interface
should not be used; instead see L<File::Temp>.
=item C<tolower>
This is identical to the C function, except that it can apply to a single
character or to a whole string. Consider using the C<lc()> function,
see L<perlfunc/lc>, or the equivalent C<\L> operator inside doublequotish
strings.
=item C<toupper>
This is identical to the C function, except that it can apply to a single
character or to a whole string. Consider using the C<uc()> function,
see L<perlfunc/uc>, or the equivalent C<\U> operator inside doublequotish
strings.
=item C<ttyname>
This is identical to the C function C<ttyname()> for returning the
name of the current terminal.
=item C<tzname>
Retrieves the time conversion information from the C<tzname> variable.
POSIX::tzset();
($std, $dst) = POSIX::tzname();
=item C<tzset>
This is identical to the C function C<tzset()> for setting
the current timezone based on the environment variable C<TZ>,
to be used by C<ctime()>, C<localtime()>, C<mktime()>, and C<strftime()>
functions.
=item C<umask>
This is identical to Perl's builtin C<umask()> function
for setting (and querying) the file creation permission mask,
see L<perlfunc/umask>.
=item C<uname>
Get name of current operating system.
($sysname, $nodename, $release, $version, $machine)
= POSIX::uname();
Note that the actual meanings of the various fields are not
that well standardized, do not expect any great portability.
The C<$sysname> might be the name of the operating system,
the C<$nodename> might be the name of the host, the C<$release>
might be the (major) release number of the operating system,
the C<$version> might be the (minor) release number of the
operating system, and the C<$machine> might be a hardware identifier.
Maybe.
=item C<ungetc>
Use method C<IO::Handle::ungetc()> instead.
=item C<unlink>
This is identical to Perl's builtin C<unlink()> function
for removing files, see L<perlfunc/unlink>.
=item C<utime>
This is identical to Perl's builtin C<utime()> function
for changing the time stamps of files and directories,
see L<perlfunc/utime>.
=item C<vfprintf>
C<vfprintf()> is C-specific, see L<perlfunc/printf> instead.
=item C<vprintf>
C<vprintf()> is C-specific, see L<perlfunc/printf> instead.
=item C<vsprintf>
C<vsprintf()> is C-specific, see L<perlfunc/sprintf> instead.
=item C<wait>
This is identical to Perl's builtin C<wait()> function,
see L<perlfunc/wait>.
=item C<waitpid>
Wait for a child process to change state. This is identical to Perl's
builtin C<waitpid()> function, see L<perlfunc/waitpid>.
$pid = POSIX::waitpid( -1, POSIX::WNOHANG );
print "status = ", ($? / 256), "\n";
=item C<wcstombs>
This is identical to the C function C<wcstombs()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<wctomb>
This is identical to the C function C<wctomb()>.
Perl does not have any support for the wide and multibyte
characters of the C standards, so this might be a rather
useless function.
=item C<write>
Write to a file. This uses file descriptors such as those obtained by
calling C<POSIX::open>.
$fd = POSIX::open( "foo", &POSIX::O_WRONLY );
$buf = "hello";
$bytes = POSIX::write( $fd, $buf, 5 );
Returns C<undef> on failure.
See also L<perlfunc/syswrite>.
=back
=head1 CLASSES
=head2 C<POSIX::SigAction>
=over 8
=item C<new>
Creates a new C<POSIX::SigAction> object which corresponds to the C
C<struct sigaction>. This object will be destroyed automatically when
it is no longer needed. The first parameter is the handler, a sub
reference. The second parameter is a C<POSIX::SigSet> object, it
defaults to the empty set. The third parameter contains the
C<sa_flags>, it defaults to 0.
$sigset = POSIX::SigSet->new(SIGINT, SIGQUIT);
$sigaction = POSIX::SigAction->new(
\&handler, $sigset, &POSIX::SA_NOCLDSTOP
);
This C<POSIX::SigAction> object is intended for use with the C<POSIX::sigaction()>
function.
=back
=over 8
=item C<handler>
=item C<mask>
=item C<flags>
accessor functions to get/set the values of a SigAction object.
$sigset = $sigaction->mask;
$sigaction->flags(&POSIX::SA_RESTART);
=item C<safe>
accessor function for the "safe signals" flag of a SigAction object; see
L<perlipc> for general information on safe (a.k.a. "deferred") signals. If
you wish to handle a signal safely, use this accessor to set the "safe" flag
in the C<POSIX::SigAction> object:
$sigaction->safe(1);
You may also examine the "safe" flag on the output action object which is
filled in when given as the third parameter to C<POSIX::sigaction()>:
sigaction(SIGINT, $new_action, $old_action);
if ($old_action->safe) {
# previous SIGINT handler used safe signals
}
=back
=head2 C<POSIX::SigRt>
=over 8
=item C<%SIGRT>
A hash of the POSIX realtime signal handlers. It is an extension of
the standard C<%SIG>, the C<$POSIX::SIGRT{SIGRTMIN}> is roughly equivalent
to C<$SIG{SIGRTMIN}>, but the right POSIX moves (see below) are made with
the C<POSIX::SigSet> and C<POSIX::sigaction> instead of accessing the C<%SIG>.
You can set the C<%POSIX::SIGRT> elements to set the POSIX realtime
signal handlers, use C<delete> and C<exists> on the elements, and use
C<scalar> on the C<%POSIX::SIGRT> to find out how many POSIX realtime
signals there are available S<C<(SIGRTMAX - SIGRTMIN + 1>>, the C<SIGRTMAX> is
a valid POSIX realtime signal).
Setting the C<%SIGRT> elements is equivalent to calling this:
sub new {
my ($rtsig, $handler, $flags) = @_;
my $sigset = POSIX::SigSet($rtsig);
my $sigact = POSIX::SigAction->new($handler,$sigset,$flags);
sigaction($rtsig, $sigact);
}
The flags default to zero, if you want something different you can
either use C<local> on C<$POSIX::SigRt::SIGACTION_FLAGS>, or you can
derive from POSIX::SigRt and define your own C<new()> (the tied hash
STORE method of the C<%SIGRT> calls C<new($rtsig, $handler, $SIGACTION_FLAGS)>,
where the C<$rtsig> ranges from zero to S<C<SIGRTMAX - SIGRTMIN + 1)>>.
Just as with any signal, you can use C<sigaction($rtsig, undef, $oa)> to
retrieve the installed signal handler (or, rather, the signal action).
B<NOTE:> whether POSIX realtime signals really work in your system, or
whether Perl has been compiled so that it works with them, is outside
of this discussion.
=item C<SIGRTMIN>
Return the minimum POSIX realtime signal number available, or C<undef>
if no POSIX realtime signals are available.
=item C<SIGRTMAX>
Return the maximum POSIX realtime signal number available, or C<undef>
if no POSIX realtime signals are available.
=back
=head2 C<POSIX::SigSet>
=over 8
=item C<new>
Create a new SigSet object. This object will be destroyed automatically
when it is no longer needed. Arguments may be supplied to initialize the
set.
Create an empty set.
$sigset = POSIX::SigSet->new;
Create a set with C<SIGUSR1>.
$sigset = POSIX::SigSet->new( &POSIX::SIGUSR1 );
=item C<addset>
Add a signal to a SigSet object.
$sigset->addset( &POSIX::SIGUSR2 );
Returns C<undef> on failure.
=item C<delset>
Remove a signal from the SigSet object.
$sigset->delset( &POSIX::SIGUSR2 );
Returns C<undef> on failure.
=item C<emptyset>
Initialize the SigSet object to be empty.
$sigset->emptyset();
Returns C<undef> on failure.
=item C<fillset>
Initialize the SigSet object to include all signals.
$sigset->fillset();
Returns C<undef> on failure.
=item C<ismember>
Tests the SigSet object to see if it contains a specific signal.
if( $sigset->ismember( &POSIX::SIGUSR1 ) ){
print "contains SIGUSR1\n";
}
=back
=head2 C<POSIX::Termios>
=over 8
=item C<new>
Create a new Termios object. This object will be destroyed automatically
when it is no longer needed. A Termios object corresponds to the termios
C struct. C<new()> mallocs a new one, C<getattr()> fills it from a file descriptor,
and C<setattr()> sets a file descriptor's parameters to match Termios' contents.
$termios = POSIX::Termios->new;
=item C<getattr>
Get terminal control attributes.
Obtain the attributes for stdin.
$termios->getattr( 0 ) # Recommended for clarity.
$termios->getattr()
Obtain the attributes for stdout.
$termios->getattr( 1 )
Returns C<undef> on failure.
=item C<getcc>
Retrieve a value from the c_cc field of a termios object. The c_cc field is
an array so an index must be specified.
$c_cc[1] = $termios->getcc(1);
=item C<getcflag>
Retrieve the c_cflag field of a termios object.
$c_cflag = $termios->getcflag;
=item C<getiflag>
Retrieve the c_iflag field of a termios object.
$c_iflag = $termios->getiflag;
=item C<getispeed>
Retrieve the input baud rate.
$ispeed = $termios->getispeed;
=item C<getlflag>
Retrieve the c_lflag field of a termios object.
$c_lflag = $termios->getlflag;
=item C<getoflag>
Retrieve the c_oflag field of a termios object.
$c_oflag = $termios->getoflag;
=item C<getospeed>
Retrieve the output baud rate.
$ospeed = $termios->getospeed;
=item C<setattr>
Set terminal control attributes.
Set attributes immediately for stdout.
$termios->setattr( 1, &POSIX::TCSANOW );
Returns C<undef> on failure.
=item C<setcc>
Set a value in the c_cc field of a termios object. The c_cc field is an
array so an index must be specified.
$termios->setcc( &POSIX::VEOF, 1 );
=item C<setcflag>
Set the c_cflag field of a termios object.
$termios->setcflag( $c_cflag | &POSIX::CLOCAL );
=item C<setiflag>
Set the c_iflag field of a termios object.
$termios->setiflag( $c_iflag | &POSIX::BRKINT );
=item C<setispeed>
Set the input baud rate.
$termios->setispeed( &POSIX::B9600 );
Returns C<undef> on failure.
=item C<setlflag>
Set the c_lflag field of a termios object.
$termios->setlflag( $c_lflag | &POSIX::ECHO );
=item C<setoflag>
Set the c_oflag field of a termios object.
$termios->setoflag( $c_oflag | &POSIX::OPOST );
=item C<setospeed>
Set the output baud rate.
$termios->setospeed( &POSIX::B9600 );
Returns C<undef> on failure.
=item Baud rate values
C<B38400> C<B75> C<B200> C<B134> C<B300> C<B1800> C<B150> C<B0> C<B19200> C<B1200> C<B9600> C<B600> C<B4800> C<B50> C<B2400> C<B110>
=item Terminal interface values
C<TCSADRAIN> C<TCSANOW> C<TCOON> C<TCIOFLUSH> C<TCOFLUSH> C<TCION> C<TCIFLUSH> C<TCSAFLUSH> C<TCIOFF> C<TCOOFF>
=item C<c_cc> field values
C<VEOF> C<VEOL> C<VERASE> C<VINTR> C<VKILL> C<VQUIT> C<VSUSP> C<VSTART> C<VSTOP> C<VMIN> C<VTIME> C<NCCS>
=item C<c_cflag> field values
C<CLOCAL> C<CREAD> C<CSIZE> C<CS5> C<CS6> C<CS7> C<CS8> C<CSTOPB> C<HUPCL> C<PARENB> C<PARODD>
=item C<c_iflag> field values
C<BRKINT> C<ICRNL> C<IGNBRK> C<IGNCR> C<IGNPAR> C<INLCR> C<INPCK> C<ISTRIP> C<IXOFF> C<IXON> C<PARMRK>
=item C<c_lflag> field values
C<ECHO> C<ECHOE> C<ECHOK> C<ECHONL> C<ICANON> C<IEXTEN> C<ISIG> C<NOFLSH> C<TOSTOP>
=item C<c_oflag> field values
C<OPOST>
=back
=head1 PATHNAME CONSTANTS
=over 8
=item Constants
C<_PC_CHOWN_RESTRICTED> C<_PC_LINK_MAX> C<_PC_MAX_CANON> C<_PC_MAX_INPUT> C<_PC_NAME_MAX>
C<_PC_NO_TRUNC> C<_PC_PATH_MAX> C<_PC_PIPE_BUF> C<_PC_VDISABLE>
=back
=head1 POSIX CONSTANTS
=over 8
=item Constants
C<_POSIX_ARG_MAX> C<_POSIX_CHILD_MAX> C<_POSIX_CHOWN_RESTRICTED> C<_POSIX_JOB_CONTROL>
C<_POSIX_LINK_MAX> C<_POSIX_MAX_CANON> C<_POSIX_MAX_INPUT> C<_POSIX_NAME_MAX>
C<_POSIX_NGROUPS_MAX> C<_POSIX_NO_TRUNC> C<_POSIX_OPEN_MAX> C<_POSIX_PATH_MAX>
C<_POSIX_PIPE_BUF> C<_POSIX_SAVED_IDS> C<_POSIX_SSIZE_MAX> C<_POSIX_STREAM_MAX>
C<_POSIX_TZNAME_MAX> C<_POSIX_VDISABLE> C<_POSIX_VERSION>
=back
=head1 SYSTEM CONFIGURATION
=over 8
=item Constants
C<_SC_ARG_MAX> C<_SC_CHILD_MAX> C<_SC_CLK_TCK> C<_SC_JOB_CONTROL> C<_SC_NGROUPS_MAX>
C<_SC_OPEN_MAX> C<_SC_PAGESIZE> C<_SC_SAVED_IDS> C<_SC_STREAM_MAX> C<_SC_TZNAME_MAX>
C<_SC_VERSION>
=back
=head1 ERRNO
=over 8
=item Constants
C<E2BIG> C<EACCES> C<EADDRINUSE> C<EADDRNOTAVAIL> C<EAFNOSUPPORT> C<EAGAIN> C<EALREADY> C<EBADF> C<EBADMSG>
C<EBUSY> C<ECANCELED> C<ECHILD> C<ECONNABORTED> C<ECONNREFUSED> C<ECONNRESET> C<EDEADLK> C<EDESTADDRREQ>
C<EDOM> C<EDQUOT> C<EEXIST> C<EFAULT> C<EFBIG> C<EHOSTDOWN> C<EHOSTUNREACH> C<EIDRM> C<EILSEQ> C<EINPROGRESS>
C<EINTR> C<EINVAL> C<EIO> C<EISCONN> C<EISDIR> C<ELOOP> C<EMFILE> C<EMLINK> C<EMSGSIZE> C<ENAMETOOLONG>
C<ENETDOWN> C<ENETRESET> C<ENETUNREACH> C<ENFILE> C<ENOBUFS> C<ENODATA> C<ENODEV> C<ENOENT> C<ENOEXEC>
C<ENOLCK> C<ENOLINK> C<ENOMEM> C<ENOMSG> C<ENOPROTOOPT> C<ENOSPC> C<ENOSR> C<ENOSTR> C<ENOSYS> C<ENOTBLK>
C<ENOTCONN> C<ENOTDIR> C<ENOTEMPTY> C<ENOTRECOVERABLE> C<ENOTSOCK> C<ENOTSUP> C<ENOTTY> C<ENXIO>
C<EOPNOTSUPP> C<EOTHER> C<EOVERFLOW> C<EOWNERDEAD> C<EPERM> C<EPFNOSUPPORT> C<EPIPE> C<EPROCLIM> C<EPROTO>
C<EPROTONOSUPPORT> C<EPROTOTYPE> C<ERANGE> C<EREMOTE> C<ERESTART> C<EROFS> C<ESHUTDOWN>
C<ESOCKTNOSUPPORT> C<ESPIPE> C<ESRCH> C<ESTALE> C<ETIME> C<ETIMEDOUT> C<ETOOMANYREFS> C<ETXTBSY> C<EUSERS>
C<EWOULDBLOCK> C<EXDEV>
=back
=head1 FCNTL
=over 8
=item Constants
C<FD_CLOEXEC> C<F_DUPFD> C<F_GETFD> C<F_GETFL> C<F_GETLK> C<F_OK> C<F_RDLCK> C<F_SETFD> C<F_SETFL> C<F_SETLK>
C<F_SETLKW> C<F_UNLCK> C<F_WRLCK> C<O_ACCMODE> C<O_APPEND> C<O_CREAT> C<O_EXCL> C<O_NOCTTY> C<O_NONBLOCK>
C<O_RDONLY> C<O_RDWR> C<O_TRUNC> C<O_WRONLY>
=back
=head1 FLOAT
=over 8
=item Constants
C<DBL_DIG> C<DBL_EPSILON> C<DBL_MANT_DIG> C<DBL_MAX> C<DBL_MAX_10_EXP> C<DBL_MAX_EXP> C<DBL_MIN>
C<DBL_MIN_10_EXP> C<DBL_MIN_EXP> C<FLT_DIG> C<FLT_EPSILON> C<FLT_MANT_DIG> C<FLT_MAX>
C<FLT_MAX_10_EXP> C<FLT_MAX_EXP> C<FLT_MIN> C<FLT_MIN_10_EXP> C<FLT_MIN_EXP> C<FLT_RADIX>
C<FLT_ROUNDS> C<LDBL_DIG> C<LDBL_EPSILON> C<LDBL_MANT_DIG> C<LDBL_MAX> C<LDBL_MAX_10_EXP>
C<LDBL_MAX_EXP> C<LDBL_MIN> C<LDBL_MIN_10_EXP> C<LDBL_MIN_EXP>
=back
=head1 LIMITS
=over 8
=item Constants
C<ARG_MAX> C<CHAR_BIT> C<CHAR_MAX> C<CHAR_MIN> C<CHILD_MAX> C<INT_MAX> C<INT_MIN> C<LINK_MAX> C<LONG_MAX>
C<LONG_MIN> C<MAX_CANON> C<MAX_INPUT> C<MB_LEN_MAX> C<NAME_MAX> C<NGROUPS_MAX> C<OPEN_MAX> C<PATH_MAX>
C<PIPE_BUF> C<SCHAR_MAX> C<SCHAR_MIN> C<SHRT_MAX> C<SHRT_MIN> C<SSIZE_MAX> C<STREAM_MAX> C<TZNAME_MAX>
C<UCHAR_MAX> C<UINT_MAX> C<ULONG_MAX> C<USHRT_MAX>
=back
=head1 LOCALE
=over 8
=item Constants
C<LC_ALL> C<LC_COLLATE> C<LC_CTYPE> C<LC_MONETARY> C<LC_NUMERIC> C<LC_TIME>
=back
=head1 MATH
=over 8
=item Constants
C<HUGE_VAL>
=back
=head1 SIGNAL
=over 8
=item Constants
C<SA_NOCLDSTOP> C<SA_NOCLDWAIT> C<SA_NODEFER> C<SA_ONSTACK> C<SA_RESETHAND> C<SA_RESTART>
C<SA_SIGINFO> C<SIGABRT> C<SIGALRM> C<SIGCHLD> C<SIGCONT> C<SIGFPE> C<SIGHUP> C<SIGILL> C<SIGINT>
C<SIGKILL> C<SIGPIPE> C<SIGQUIT> C<SIGSEGV> C<SIGSTOP> C<SIGTERM> C<SIGTSTP> C<SIGTTIN> C<SIGTTOU>
C<SIGUSR1> C<SIGUSR2> C<SIG_BLOCK> C<SIG_DFL> C<SIG_ERR> C<SIG_IGN> C<SIG_SETMASK>
C<SIG_UNBLOCK>
=back
=head1 STAT
=over 8
=item Constants
C<S_IRGRP> C<S_IROTH> C<S_IRUSR> C<S_IRWXG> C<S_IRWXO> C<S_IRWXU> C<S_ISGID> C<S_ISUID> C<S_IWGRP> C<S_IWOTH>
C<S_IWUSR> C<S_IXGRP> C<S_IXOTH> C<S_IXUSR>
=item Macros
C<S_ISBLK> C<S_ISCHR> C<S_ISDIR> C<S_ISFIFO> C<S_ISREG>
=back
=head1 STDLIB
=over 8
=item Constants
C<EXIT_FAILURE> C<EXIT_SUCCESS> C<MB_CUR_MAX> C<RAND_MAX>
=back
=head1 STDIO
=over 8
=item Constants
C<BUFSIZ> C<EOF> C<FILENAME_MAX> C<L_ctermid> C<L_cuserid> C<L_tmpname> C<TMP_MAX>
=back
=head1 TIME
=over 8
=item Constants
C<CLK_TCK> C<CLOCKS_PER_SEC>
=back
=head1 UNISTD
=over 8
=item Constants
C<R_OK> C<SEEK_CUR> C<SEEK_END> C<SEEK_SET> C<STDIN_FILENO> C<STDOUT_FILENO> C<STDERR_FILENO> C<W_OK> C<X_OK>
=back
=head1 WAIT
=over 8
=item Constants
C<WNOHANG> C<WUNTRACED>
=over 16
=item C<WNOHANG>
Do not suspend the calling process until a child process
changes state but instead return immediately.
=item C<WUNTRACED>
Catch stopped child processes.
=back
=item Macros
C<WIFEXITED> C<WEXITSTATUS> C<WIFSIGNALED> C<WTERMSIG> C<WIFSTOPPED> C<WSTOPSIG>
=over 16
=item C<WIFEXITED>
C<WIFEXITED(${^CHILD_ERROR_NATIVE})> returns true if the child process
exited normally (C<exit()> or by falling off the end of C<main()>)
=item C<WEXITSTATUS>
C<WEXITSTATUS(${^CHILD_ERROR_NATIVE})> returns the normal exit status of
the child process (only meaningful if C<WIFEXITED(${^CHILD_ERROR_NATIVE})>
is true)
=item C<WIFSIGNALED>
C<WIFSIGNALED(${^CHILD_ERROR_NATIVE})> returns true if the child process
terminated because of a signal
=item C<WTERMSIG>
C<WTERMSIG(${^CHILD_ERROR_NATIVE})> returns the signal the child process
terminated for (only meaningful if
C<WIFSIGNALED(${^CHILD_ERROR_NATIVE})>
is true)
=item C<WIFSTOPPED>
C<WIFSTOPPED(${^CHILD_ERROR_NATIVE})> returns true if the child process is
currently stopped (can happen only if you specified the WUNTRACED flag
to C<waitpid()>)
=item C<WSTOPSIG>
C<WSTOPSIG(${^CHILD_ERROR_NATIVE})> returns the signal the child process
was stopped for (only meaningful if
C<WIFSTOPPED(${^CHILD_ERROR_NATIVE})>
is true)
=back
=back
| Java |
cmd_kernel/sys_ni.o := /pub/CIS520/usr/arm/bin/arm-angstrom-linux-gnueabi-gcc -Wp,-MD,kernel/.sys_ni.o.d -nostdinc -isystem /net/files.cis.ksu.edu/exports/public/CIS520/usr/arm/bin/../lib/gcc/arm-angstrom-linux-gnueabi/4.3.3/include -Iinclude -I/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include -include include/linux/autoconf.h -D__KERNEL__ -mlittle-endian -Iarch/arm/mach-goldfish/include -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -Werror-implicit-function-declaration -Os -marm -fno-omit-frame-pointer -mapcs -mno-sched-prolog -mabi=aapcs-linux -mno-thumb-interwork -D__LINUX_ARM_ARCH__=7 -march=armv7-a -msoft-float -Uarm -fno-stack-protector -fno-omit-frame-pointer -fno-optimize-sibling-calls -Wdeclaration-after-statement -Wno-pointer-sign -fwrapv -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(sys_ni)" -D"KBUILD_MODNAME=KBUILD_STR(sys_ni)" -c -o kernel/sys_ni.o kernel/sys_ni.c
deps_kernel/sys_ni.o := \
kernel/sys_ni.c \
include/linux/linkage.h \
include/linux/compiler.h \
$(wildcard include/config/trace/branch/profiling.h) \
$(wildcard include/config/profile/all/branches.h) \
$(wildcard include/config/enable/must/check.h) \
$(wildcard include/config/enable/warn/deprecated.h) \
include/linux/compiler-gcc.h \
$(wildcard include/config/arch/supports/optimized/inlining.h) \
$(wildcard include/config/optimize/inlining.h) \
include/linux/compiler-gcc4.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/linkage.h \
include/linux/errno.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/errno.h \
include/asm-generic/errno.h \
include/asm-generic/errno-base.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/unistd.h \
$(wildcard include/config/aeabi.h) \
$(wildcard include/config/oabi/compat.h) \
kernel/sys_ni.o: $(deps_kernel/sys_ni.o)
$(deps_kernel/sys_ni.o):
| Java |
using System;
using Server.Engines.Craft;
namespace Server.Items
{
public abstract class BaseRing : BaseJewel
{
public BaseRing(int itemID)
: base(itemID, Layer.Ring)
{
}
public BaseRing(Serial serial)
: base(serial)
{
}
public override int BaseGemTypeNumber
{
get
{
return 1044176;
}
}// star sapphire ring
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class GoldRing : BaseRing
{
[Constructable]
public GoldRing()
: base(0x108a)
{
this.Weight = 0.1;
}
public GoldRing(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class SilverRing : BaseRing, IRepairable
{
public CraftSystem RepairSystem { get { return DefTinkering.CraftSystem; } }
[Constructable]
public SilverRing()
: base(0x1F09)
{
this.Weight = 0.1;
}
public SilverRing(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
} | Java |
# plugins module for amsn2
"""
Plugins with amsn2 will be a subclass of the aMSNPlugin() class.
When this module is initially imported it should load the plugins from the last session. Done in the init() proc.
Then the GUI should call plugins.loadPlugin(name) or plugins.unLoadPlugin(name) in order to deal with plugins.
"""
# init()
# Called when the plugins module is imported (only for the first time).
# Should find plugins and populate a list ready for getPlugins().
# Should also auto-update all plugins.
def init(): pass
# loadPlugin(plugin_name)
# Called (by the GUI or from init()) to load a plugin. plugin_name as set in plugin's XML (or from getPlugins()).
# This loads the module for the plugin. The module is then responsible for calling plugins.registerPlugin(instance).
def loadPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass
# unLoadPlugin(plugin_name)
# Called to unload a plugin. Name is name as set in plugin's XML.
def unLoadPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass
# registerPlugin(plugin_instance)
# Saves the instance of the plugin, and registers it in the loaded list.
def registerPlugin(plugin_instance):
"""
@type plugin_instance: L{amsn2.plugins.developers.aMSNPlugin}
"""
pass
# getPlugins()
# Returns a list of all available plugins, as in ['Plugin 1', 'Plugin 2']
def getPlugins(): pass
# getPluginsWithStatus()
# Returns a list with a list item for each plugin with the plugin's name, and Loaded or NotLoaded either way.
# IE: [['Plugin 1', 'Loaded'], ['Plugin 2', 'NotLoaded']]
def getPluginsWithStatus(): pass
# getLoadedPlugins()
# Returns a list of loaded plugins. as in ['Plugin 1', 'Plugin N']
def getLoadedPlugins(): pass
# findPlugin(plugin_name)
# Retruns the running instance of the plugin with name plugin_name, or None if not found.
def findPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass
# saveConfig(plugin_name, data)
def saveConfig(plugin_name, data):
"""
@type plugin_name: str
@type data: object
"""
pass
# Calls the init procedure.
# Will only be called on the first import (thanks to python).
init()
| Java |
<?php
/*
Plugin Name: PoP CDN WordPress
Description: Implementation of the CDN for PoP
Plugin URI: https://getpop.org
Version: 0.1
Author: Leonardo Losovizen/u/leo/
*/
//-------------------------------------------------------------------------------------
// Constants Definition
//-------------------------------------------------------------------------------------
define('POP_CDNWP_VERSION', 0.157);
define('POP_CDNWP_DIR', dirname(__FILE__));
class PoP_CDNWP
{
public function __construct()
{
// Priority: after PoP Engine Web Platform
\PoP\Root\App::addAction('plugins_loaded', array($this, 'init'), 888412);
}
public function init()
{
define('POP_CDNWP_URL', plugins_url('', __FILE__));
if ($this->validate()) {
$this->initialize();
define('POP_CDNWP_INITIALIZED', true);
}
}
public function validate()
{
return true;
include_once 'validation.php';
$validation = new PoP_CDNWP_Validation();
return $validation->validate();
}
public function initialize()
{
include_once 'initialization.php';
$initialization = new PoP_CDNWP_Initialization();
return $initialization->initialize();
}
}
/**
* Initialization
*/
new PoP_CDNWP();
| Java |
#
# Copyright 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the implied warranties of MERCHANTABILITY,
# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
# have received a copy of GPLv2 along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
# The Errata module contains methods that are common for supporting errata
# in several controllers (e.g. SystemErrataController and SystemGroupErrataController)
module Katello
module Util
module Errata
def filter_by_type(errata_list, filter_type)
filtered_list = []
if filter_type != "All"
pulp_filter_type = get_pulp_filter_type(filter_type)
errata_list.each do |erratum|
if erratum.respond_to?(:type)
if erratum.type == pulp_filter_type
filtered_list << erratum
end
else
if erratum["type"] == pulp_filter_type
filtered_list << erratum
end
end
end
else
filtered_list = errata_list
end
return filtered_list
end
def get_pulp_filter_type(type)
filter_type = type.downcase
if filter_type == "bugfix"
return Glue::Pulp::Errata::BUGZILLA
elsif filter_type == "enhancement"
return Glue::Pulp::Errata::ENHANCEMENT
elsif filter_type == "security"
return Glue::Pulp::Errata::SECURITY
end
end
def filter_by_state(errata_list, errata_state)
if errata_state == "applied"
return []
else
return errata_list
end
end
end
end
end
| Java |
define(["require", "exports"], function (require, exports) {
"use strict";
exports.ZaOverviewPanelController = ZaOverviewPanelController;
});
| Java |
// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - | FileCheck %s
// CHECK: ; ModuleID
struct A {
template<typename T>
A(T);
};
template<typename T> A::A(T) {}
struct B {
template<typename T>
B(T);
};
template<typename T> B::B(T) {}
// CHECK: define void @_ZN1BC1IiEET_(%struct.B* %this, i32)
// CHECK: define void @_ZN1BC2IiEET_(%struct.B* %this, i32)
template B::B(int);
template<typename T>
struct C {
void f() {
int a[] = { 1, 2, 3 };
}
};
void f(C<int>& c) {
c.f();
}
| Java |
/* Copyright (c) 2012-2015, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/firmware.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/printk.h>
#include <linux/ratelimit.h>
#include <linux/debugfs.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/mfd/wcd9xxx/core.h>
#include <linux/mfd/wcd9xxx/wcd9xxx_registers.h>
#include <linux/mfd/wcd9xxx/wcd9330_registers.h>
#include <linux/mfd/wcd9xxx/pdata.h>
#include <linux/regulator/consumer.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/tlv.h>
#include <linux/delay.h>
#include <linux/pm_runtime.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/clk.h>
#include "wcd9330.h"
#include "wcd9xxx-resmgr.h"
#include "wcd9xxx-common.h"
#include "wcdcal-hwdep.h"
#include "wcd_cpe_core.h"
enum {
VI_SENSE_1,
VI_SENSE_2,
VI_SENSE_MAX,
BUS_DOWN,
ADC1_TXFE,
ADC2_TXFE,
ADC3_TXFE,
ADC4_TXFE,
ADC5_TXFE,
ADC6_TXFE,
};
#define TOMTOM_MAD_SLIMBUS_TX_PORT 12
#define TOMTOM_MAD_AUDIO_FIRMWARE_PATH "wcd9320/wcd9320_mad_audio.bin"
#define TOMTOM_VALIDATE_RX_SBPORT_RANGE(port) ((port >= 16) && (port <= 23))
#define TOMTOM_VALIDATE_TX_SBPORT_RANGE(port) ((port >= 0) && (port <= 15))
#define TOMTOM_CONVERT_RX_SBPORT_ID(port) (port - 16) /* RX1 port ID = 0 */
#define TOMTOM_BIT_ADJ_SHIFT_PORT1_6 4
#define TOMTOM_BIT_ADJ_SHIFT_PORT7_10 5
#define TOMTOM_HPH_PA_SETTLE_COMP_ON 5000
#define TOMTOM_HPH_PA_SETTLE_COMP_OFF 13000
#define TOMTOM_HPH_PA_RAMP_DELAY 30000
#define TOMTOM_SVASS_INT_STATUS_RCO_WDOG 0x20
#define TOMTOM_SVASS_INT_STATUS_WDOG_BITE 0x02
/* Add any SVA IRQs that are to be treated as FATAL */
#define TOMTOM_CPE_FATAL_IRQS \
(TOMTOM_SVASS_INT_STATUS_RCO_WDOG | \
TOMTOM_SVASS_INT_STATUS_WDOG_BITE)
#define DAPM_MICBIAS2_EXTERNAL_STANDALONE "MIC BIAS2 External Standalone"
/* RX_HPH_CNP_WG_TIME increases by 0.24ms */
#define TOMTOM_WG_TIME_FACTOR_US 240
#define MAX_ON_DEMAND_SUPPLY_NAME_LENGTH 64
#define RX8_PATH 8
#define HPH_PA_ENABLE true
#define HPH_PA_DISABLE false
#define SLIM_BW_CLK_GEAR_9 6200000
#define SLIM_BW_UNVOTE 0
static int cpe_debug_mode;
module_param(cpe_debug_mode, int,
S_IRUGO | S_IWUSR | S_IWGRP);
MODULE_PARM_DESC(cpe_debug_mode, "boot cpe in debug mode");
static atomic_t kp_tomtom_priv;
static int high_perf_mode = 1;
module_param(high_perf_mode, int,
S_IRUGO | S_IWUSR | S_IWGRP);
MODULE_PARM_DESC(high_perf_mode, "enable/disable class AB config for hph");
static struct afe_param_slimbus_slave_port_cfg tomtom_slimbus_slave_port_cfg = {
.minor_version = 1,
.slimbus_dev_id = AFE_SLIMBUS_DEVICE_1,
.slave_dev_pgd_la = 0,
.slave_dev_intfdev_la = 0,
.bit_width = 16,
.data_format = 0,
.num_channels = 1
};
static struct afe_param_cdc_reg_cfg audio_reg_cfg[] = {
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_MAD_MAIN_CTL_1),
HW_MAD_AUDIO_ENABLE, 0x1, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_MAD_AUDIO_CTL_3),
HW_MAD_AUDIO_SLEEP_TIME, 0xF, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_MAD_AUDIO_CTL_4),
HW_MAD_TX_AUDIO_SWITCH_OFF, 0x1, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR_MODE),
MAD_AUDIO_INT_DEST_SELECT_REG, 0x4, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_MASK0),
MAD_AUDIO_INT_MASK_REG, 0x2, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_STATUS0),
MAD_AUDIO_INT_STATUS_REG, 0x2, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_CLEAR0),
MAD_AUDIO_INT_CLEAR_REG, 0x2, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_SB_PGD_PORT_TX_BASE),
SB_PGD_PORT_TX_WATERMARK_N, 0x1E, 8, 0x1
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_SB_PGD_PORT_TX_BASE),
SB_PGD_PORT_TX_ENABLE_N, 0x1, 8, 0x1
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_SB_PGD_PORT_RX_BASE),
SB_PGD_PORT_RX_WATERMARK_N, 0x1E, 8, 0x1
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_SB_PGD_PORT_RX_BASE),
SB_PGD_PORT_RX_ENABLE_N, 0x1, 8, 0x1
},
{ 1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_ANC1_IIR_B1_CTL),
AANC_FF_GAIN_ADAPTIVE, 0x4, 8, 0
},
{ 1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_ANC1_IIR_B1_CTL),
AANC_FFGAIN_ADAPTIVE_EN, 0x8, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_CDC_ANC1_GAIN_CTL),
AANC_GAIN_CONTROL, 0xFF, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_MASK0),
MAD_CLIP_INT_MASK_REG, 0x10, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_MASK0),
MAD2_CLIP_INT_MASK_REG, 0x20, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_STATUS0),
MAD_CLIP_INT_STATUS_REG, 0x10, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_STATUS0),
MAD2_CLIP_INT_STATUS_REG, 0x20, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_CLEAR0),
MAD_CLIP_INT_CLEAR_REG, 0x10, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET + TOMTOM_A_INTR2_CLEAR0),
MAD2_CLIP_INT_CLEAR_REG, 0x20, 8, 0
},
};
static struct afe_param_cdc_reg_cfg clip_reg_cfg[] = {
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_B1_CTL),
SPKR_CLIP_PIPE_BANK_SEL, 0x3, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL0),
SPKR_CLIPDET_VAL0, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL1),
SPKR_CLIPDET_VAL1, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL2),
SPKR_CLIPDET_VAL2, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL3),
SPKR_CLIPDET_VAL3, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL4),
SPKR_CLIPDET_VAL4, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL5),
SPKR_CLIPDET_VAL5, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL6),
SPKR_CLIPDET_VAL6, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR_CLIPDET_VAL7),
SPKR_CLIPDET_VAL7, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_B1_CTL),
SPKR2_CLIP_PIPE_BANK_SEL, 0x3, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL0),
SPKR2_CLIPDET_VAL0, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL1),
SPKR2_CLIPDET_VAL1, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL2),
SPKR2_CLIPDET_VAL2, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL3),
SPKR2_CLIPDET_VAL3, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL4),
SPKR2_CLIPDET_VAL4, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL5),
SPKR2_CLIPDET_VAL5, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL6),
SPKR2_CLIPDET_VAL6, 0xff, 8, 0
},
{
1,
(TOMTOM_REGISTER_START_OFFSET +
TOMTOM_A_CDC_SPKR2_CLIPDET_VAL7),
SPKR2_CLIPDET_VAL7, 0xff, 8, 0
},
};
static struct afe_param_cdc_reg_cfg_data tomtom_audio_reg_cfg = {
.num_registers = ARRAY_SIZE(audio_reg_cfg),
.reg_data = audio_reg_cfg,
};
static struct afe_param_cdc_reg_cfg_data tomtom_clip_reg_cfg = {
.num_registers = ARRAY_SIZE(clip_reg_cfg),
.reg_data = clip_reg_cfg,
};
static struct afe_param_id_cdc_aanc_version tomtom_cdc_aanc_version = {
.cdc_aanc_minor_version = AFE_API_VERSION_CDC_AANC_VERSION,
.aanc_hw_version = AANC_HW_BLOCK_VERSION_2,
};
static struct afe_param_id_clip_bank_sel clip_bank_sel = {
.minor_version = AFE_API_VERSION_CLIP_BANK_SEL_CFG,
.num_banks = AFE_CLIP_MAX_BANKS,
.bank_map = {0, 1, 2, 3},
};
#define WCD9330_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_16000 |\
SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_48000 |\
SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_192000)
#define NUM_DECIMATORS 10
#define NUM_INTERPOLATORS 8
#define BITS_PER_REG 8
#define TOMTOM_TX_PORT_NUMBER 16
#define TOMTOM_RX_PORT_START_NUMBER 16
#define TOMTOM_I2S_MASTER_MODE_MASK 0x08
#define TOMTOM_SLIM_CLOSE_TIMEOUT 1000
#define TOMTOM_SLIM_IRQ_OVERFLOW (1 << 0)
#define TOMTOM_SLIM_IRQ_UNDERFLOW (1 << 1)
#define TOMTOM_SLIM_IRQ_PORT_CLOSED (1 << 2)
#define TOMTOM_MCLK_CLK_12P288MHZ 12288000
#define TOMTOM_MCLK_CLK_9P6MHZ 9600000
#define TOMTOM_FORMATS_S16_S24_LE (SNDRV_PCM_FMTBIT_S16_LE | \
SNDRV_PCM_FMTBIT_S24_LE)
#define TOMTOM_FORMATS (SNDRV_PCM_FMTBIT_S16_LE)
#define TOMTOM_SLIM_PGD_PORT_INT_TX_EN0 (TOMTOM_SLIM_PGD_PORT_INT_EN0 + 2)
#define TOMTOM_ZDET_BOX_CAR_AVG_LOOP_COUNT 1
#define TOMTOM_ZDET_MUL_FACTOR_1X 7218
#define TOMTOM_ZDET_MUL_FACTOR_10X (TOMTOM_ZDET_MUL_FACTOR_1X * 10)
#define TOMTOM_ZDET_MUL_FACTOR_100X (TOMTOM_ZDET_MUL_FACTOR_1X * 100)
#define TOMTOM_ZDET_ERROR_APPROX_MUL_FACTOR 655
#define TOMTOM_ZDET_ERROR_APPROX_SHIFT 16
#define TOMTOM_ZDET_ZONE_3_DEFAULT_VAL 1000000
enum {
AIF1_PB = 0,
AIF1_CAP,
AIF2_PB,
AIF2_CAP,
AIF3_PB,
AIF3_CAP,
AIF4_VIFEED,
AIF4_MAD_TX,
NUM_CODEC_DAIS,
};
enum {
RX_MIX1_INP_SEL_ZERO = 0,
RX_MIX1_INP_SEL_SRC1,
RX_MIX1_INP_SEL_SRC2,
RX_MIX1_INP_SEL_IIR1,
RX_MIX1_INP_SEL_IIR2,
RX_MIX1_INP_SEL_RX1,
RX_MIX1_INP_SEL_RX2,
RX_MIX1_INP_SEL_RX3,
RX_MIX1_INP_SEL_RX4,
RX_MIX1_INP_SEL_RX5,
RX_MIX1_INP_SEL_RX6,
RX_MIX1_INP_SEL_RX7,
RX_MIX1_INP_SEL_AUXRX,
};
enum {
RX8_MIX1_INP_SEL_ZERO = 0,
RX8_MIX1_INP_SEL_IIR1,
RX8_MIX1_INP_SEL_IIR2,
RX8_MIX1_INP_SEL_RX1,
RX8_MIX1_INP_SEL_RX2,
RX8_MIX1_INP_SEL_RX3,
RX8_MIX1_INP_SEL_RX4,
RX8_MIX1_INP_SEL_RX5,
RX8_MIX1_INP_SEL_RX6,
RX8_MIX1_INP_SEL_RX7,
RX8_MIX1_INP_SEL_RX8,
};
enum {
ON_DEMAND_MICBIAS = 0,
ON_DEMAND_SUPPLIES_MAX,
};
#define TOMTOM_COMP_DIGITAL_GAIN_OFFSET 3
static const DECLARE_TLV_DB_SCALE(digital_gain, 0, 1, 0);
static const DECLARE_TLV_DB_SCALE(line_gain, 0, 7, 1);
static const DECLARE_TLV_DB_SCALE(analog_gain, 0, 25, 1);
static struct snd_soc_dai_driver tomtom_dai[];
static const DECLARE_TLV_DB_SCALE(aux_pga_gain, 0, 2, 0);
/* Codec supports 2 IIR filters */
enum {
IIR1 = 0,
IIR2,
IIR_MAX,
};
/* Codec supports 5 bands */
enum {
BAND1 = 0,
BAND2,
BAND3,
BAND4,
BAND5,
BAND_MAX,
};
enum {
COMPANDER_0,
COMPANDER_1,
COMPANDER_2,
COMPANDER_MAX,
};
enum {
COMPANDER_FS_8KHZ = 0,
COMPANDER_FS_16KHZ,
COMPANDER_FS_32KHZ,
COMPANDER_FS_48KHZ,
COMPANDER_FS_96KHZ,
COMPANDER_FS_192KHZ,
COMPANDER_FS_MAX,
};
struct comp_sample_dependent_params {
u32 peak_det_timeout;
u32 rms_meter_div_fact;
u32 rms_meter_resamp_fact;
};
struct hpf_work {
struct tomtom_priv *tomtom;
u32 decimator;
u8 tx_hpf_cut_of_freq;
bool tx_hpf_bypass;
struct delayed_work dwork;
};
static struct hpf_work tx_hpf_work[NUM_DECIMATORS];
static const struct wcd9xxx_ch tomtom_rx_chs[TOMTOM_RX_MAX] = {
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER, 0),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 1, 1),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 2, 2),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 3, 3),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 4, 4),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 5, 5),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 6, 6),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 7, 7),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 8, 8),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 9, 9),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 10, 10),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 11, 11),
WCD9XXX_CH(TOMTOM_RX_PORT_START_NUMBER + 12, 12),
};
static const struct wcd9xxx_ch tomtom_tx_chs[TOMTOM_TX_MAX] = {
WCD9XXX_CH(0, 0),
WCD9XXX_CH(1, 1),
WCD9XXX_CH(2, 2),
WCD9XXX_CH(3, 3),
WCD9XXX_CH(4, 4),
WCD9XXX_CH(5, 5),
WCD9XXX_CH(6, 6),
WCD9XXX_CH(7, 7),
WCD9XXX_CH(8, 8),
WCD9XXX_CH(9, 9),
WCD9XXX_CH(10, 10),
WCD9XXX_CH(11, 11),
WCD9XXX_CH(12, 12),
WCD9XXX_CH(13, 13),
WCD9XXX_CH(14, 14),
WCD9XXX_CH(15, 15),
};
static const u32 vport_check_table[NUM_CODEC_DAIS] = {
0, /* AIF1_PB */
(1 << AIF2_CAP) | (1 << AIF3_CAP), /* AIF1_CAP */
0, /* AIF2_PB */
(1 << AIF1_CAP) | (1 << AIF3_CAP), /* AIF2_CAP */
0, /* AIF3_PB */
(1 << AIF1_CAP) | (1 << AIF2_CAP), /* AIF3_CAP */
};
static const u32 vport_i2s_check_table[NUM_CODEC_DAIS] = {
0, /* AIF1_PB */
0, /* AIF1_CAP */
0, /* AIF2_PB */
0, /* AIF2_CAP */
};
static char on_demand_supply_name[][MAX_ON_DEMAND_SUPPLY_NAME_LENGTH] = {
"cdc-vdd-mic-bias",
};
struct tomtom_priv {
struct snd_soc_codec *codec;
u32 adc_count;
u32 rx_bias_count;
s32 dmic_1_2_clk_cnt;
s32 dmic_3_4_clk_cnt;
s32 dmic_5_6_clk_cnt;
s32 ldo_h_users;
s32 micb_2_users;
s32 micb_3_users;
u32 anc_slot;
bool anc_func;
/* cal info for codec */
struct fw_info *fw_data;
/*track tomtom interface type*/
u8 intf_type;
/* num of slim ports required */
struct wcd9xxx_codec_dai_data dai[NUM_CODEC_DAIS];
/*compander*/
int comp_enabled[COMPANDER_MAX];
u32 comp_fs[COMPANDER_MAX];
/* Maintain the status of AUX PGA */
int aux_pga_cnt;
u8 aux_l_gain;
u8 aux_r_gain;
bool spkr_pa_widget_on;
struct regulator *spkdrv_reg;
struct regulator *spkdrv2_reg;
struct regulator *micbias_reg;
bool mbhc_started;
struct afe_param_cdc_slimbus_slave_cfg slimbus_slave_cfg;
/* resmgr module */
struct wcd9xxx_resmgr resmgr;
/* mbhc module */
struct wcd9xxx_mbhc mbhc;
/* class h specific data */
struct wcd9xxx_clsh_cdc_data clsh_d;
int (*machine_codec_event_cb)(struct snd_soc_codec *codec,
enum wcd9xxx_codec_event);
int (*codec_ext_clk_en_cb)(struct snd_soc_codec *codec,
int enable, bool dapm);
int (*codec_get_ext_clk_cnt) (void);
/*
* list used to save/restore registers at start and
* end of impedance measurement
*/
struct list_head reg_save_restore;
/* handle to cpe core */
struct wcd_cpe_core *cpe_core;
/* UHQA (class AB) mode */
u8 uhqa_mode;
/* Multiplication factor used for impedance detection */
int zdet_gain_mul_fact;
/* to track the status */
unsigned long status_mask;
int ext_clk_users;
struct clk *wcd_ext_clk;
};
static const u32 comp_shift[] = {
4, /* Compander 0's clock source is on interpolator 7 */
0,
2,
};
static const int comp_rx_path[] = {
COMPANDER_1,
COMPANDER_1,
COMPANDER_2,
COMPANDER_2,
COMPANDER_2,
COMPANDER_2,
COMPANDER_0,
COMPANDER_0,
COMPANDER_MAX,
};
static const struct comp_sample_dependent_params comp_samp_params[] = {
{
/* 8 Khz */
.peak_det_timeout = 0x06,
.rms_meter_div_fact = 0x09,
.rms_meter_resamp_fact = 0x06,
},
{
/* 16 Khz */
.peak_det_timeout = 0x07,
.rms_meter_div_fact = 0x0A,
.rms_meter_resamp_fact = 0x0C,
},
{
/* 32 Khz */
.peak_det_timeout = 0x08,
.rms_meter_div_fact = 0x0B,
.rms_meter_resamp_fact = 0x1E,
},
{
/* 48 Khz */
.peak_det_timeout = 0x09,
.rms_meter_div_fact = 0x0B,
.rms_meter_resamp_fact = 0x28,
},
{
/* 96 Khz */
.peak_det_timeout = 0x0A,
.rms_meter_div_fact = 0x0C,
.rms_meter_resamp_fact = 0x50,
},
{
/* 192 Khz */
.peak_det_timeout = 0x0B,
.rms_meter_div_fact = 0xC,
.rms_meter_resamp_fact = 0xA0,
},
};
static unsigned short rx_digital_gain_reg[] = {
TOMTOM_A_CDC_RX1_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX2_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX3_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX4_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX5_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX6_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX7_VOL_CTL_B2_CTL,
TOMTOM_A_CDC_RX8_VOL_CTL_B2_CTL,
};
static unsigned short tx_digital_gain_reg[] = {
TOMTOM_A_CDC_TX1_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX2_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX3_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX4_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX5_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX6_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX7_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX8_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX9_VOL_CTL_GAIN,
TOMTOM_A_CDC_TX10_VOL_CTL_GAIN,
};
int tomtom_enable_qfuse_sensing(struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
if (tomtom->wcd_ext_clk)
tomtom_codec_mclk_enable(codec, true, false);
snd_soc_write(codec, TOMTOM_A_QFUSE_CTL, 0x03);
/*
* 5ms sleep required after enabling qfuse control
* before checking the status.
*/
usleep_range(5000, 5500);
if ((snd_soc_read(codec, TOMTOM_A_QFUSE_STATUS) & (0x03)) != 0x03)
WARN(1, "%s: Qfuse sense is not complete\n", __func__);
if (tomtom->wcd_ext_clk)
tomtom_codec_mclk_enable(codec, false, false);
return 0;
}
EXPORT_SYMBOL(tomtom_enable_qfuse_sensing);
static int tomtom_get_sample_rate(struct snd_soc_codec *codec, int path)
{
if (path == RX8_PATH)
return snd_soc_read(codec, TOMTOM_A_CDC_RX8_B5_CTL);
else
return snd_soc_read(codec,
(TOMTOM_A_CDC_RX1_B5_CTL + 8 * (path - 1)));
}
static int tomtom_compare_bit_format(struct snd_soc_codec *codec,
int bit_format)
{
int i = 0;
int ret = 0;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
for (i = 0; i < NUM_CODEC_DAIS; i++) {
if (tomtom_p->dai[i].bit_width == bit_format) {
ret = 1;
break;
}
}
return ret;
}
static int tomtom_update_uhqa_mode(struct snd_soc_codec *codec, int path)
{
int ret = 0;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
/* UHQA path has fs=192KHz & bit=24 bit */
if (((tomtom_get_sample_rate(codec, path) & 0xE0) == 0xA0) &&
(tomtom_compare_bit_format(codec, 24))) {
tomtom_p->uhqa_mode = 1;
} else {
tomtom_p->uhqa_mode = 0;
}
dev_dbg(codec->dev, "%s: uhqa_mode=%d", __func__, tomtom_p->uhqa_mode);
return ret;
}
static int tomtom_get_anc_slot(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = tomtom->anc_slot;
return 0;
}
static int tomtom_put_anc_slot(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
tomtom->anc_slot = ucontrol->value.integer.value[0];
return 0;
}
static int tomtom_get_anc_func(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = (tomtom->anc_func == true ? 1 : 0);
return 0;
}
static int tomtom_put_anc_func(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct snd_soc_dapm_context *dapm = &codec->dapm;
mutex_lock(&dapm->codec->mutex);
tomtom->anc_func = (!ucontrol->value.integer.value[0] ? false : true);
dev_dbg(codec->dev, "%s: anc_func %x", __func__, tomtom->anc_func);
if (tomtom->anc_func == true) {
snd_soc_dapm_enable_pin(dapm, "ANC HPHR");
snd_soc_dapm_enable_pin(dapm, "ANC HPHL");
snd_soc_dapm_enable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_enable_pin(dapm, "ANC EAR PA");
snd_soc_dapm_enable_pin(dapm, "ANC EAR");
snd_soc_dapm_disable_pin(dapm, "HPHR");
snd_soc_dapm_disable_pin(dapm, "HPHL");
snd_soc_dapm_disable_pin(dapm, "HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "EAR PA");
snd_soc_dapm_disable_pin(dapm, "EAR");
} else {
snd_soc_dapm_disable_pin(dapm, "ANC HPHR");
snd_soc_dapm_disable_pin(dapm, "ANC HPHL");
snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "ANC EAR PA");
snd_soc_dapm_disable_pin(dapm, "ANC EAR");
snd_soc_dapm_enable_pin(dapm, "HPHR");
snd_soc_dapm_enable_pin(dapm, "HPHL");
snd_soc_dapm_enable_pin(dapm, "HEADPHONE");
snd_soc_dapm_enable_pin(dapm, "EAR PA");
snd_soc_dapm_enable_pin(dapm, "EAR");
}
mutex_unlock(&dapm->codec->mutex);
snd_soc_dapm_sync(dapm);
return 0;
}
static int tomtom_get_iir_enable_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
ucontrol->value.integer.value[0] =
(snd_soc_read(codec, (TOMTOM_A_CDC_IIR1_CTL + 16 * iir_idx)) &
(1 << band_idx)) != 0;
pr_debug("%s: IIR #%d band #%d enable %d\n", __func__,
iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[0]);
return 0;
}
static int tomtom_put_iir_enable_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
int value = ucontrol->value.integer.value[0];
/* Mask first 5 bits, 6-8 are reserved */
snd_soc_update_bits(codec, (TOMTOM_A_CDC_IIR1_CTL + 16 * iir_idx),
(1 << band_idx), (value << band_idx));
pr_debug("%s: IIR #%d band #%d enable %d\n", __func__,
iir_idx, band_idx,
((snd_soc_read(codec, (TOMTOM_A_CDC_IIR1_CTL + 16 * iir_idx)) &
(1 << band_idx)) != 0));
return 0;
}
static uint32_t get_iir_band_coeff(struct snd_soc_codec *codec,
int iir_idx, int band_idx,
int coeff_idx)
{
uint32_t value = 0;
/* Address does not automatically update if reading */
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t)) & 0x7F);
value |= snd_soc_read(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx));
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t) + 1) & 0x7F);
value |= (snd_soc_read(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) << 8);
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t) + 2) & 0x7F);
value |= (snd_soc_read(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) << 16);
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
((band_idx * BAND_MAX + coeff_idx)
* sizeof(uint32_t) + 3) & 0x7F);
/* Mask bits top 2 bits since they are reserved */
value |= ((snd_soc_read(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx)) & 0x3F) << 24);
return value;
}
static int tomtom_get_iir_band_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
ucontrol->value.integer.value[0] =
get_iir_band_coeff(codec, iir_idx, band_idx, 0);
ucontrol->value.integer.value[1] =
get_iir_band_coeff(codec, iir_idx, band_idx, 1);
ucontrol->value.integer.value[2] =
get_iir_band_coeff(codec, iir_idx, band_idx, 2);
ucontrol->value.integer.value[3] =
get_iir_band_coeff(codec, iir_idx, band_idx, 3);
ucontrol->value.integer.value[4] =
get_iir_band_coeff(codec, iir_idx, band_idx, 4);
pr_debug("%s: IIR #%d band #%d b0 = 0x%x\n"
"%s: IIR #%d band #%d b1 = 0x%x\n"
"%s: IIR #%d band #%d b2 = 0x%x\n"
"%s: IIR #%d band #%d a1 = 0x%x\n"
"%s: IIR #%d band #%d a2 = 0x%x\n",
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[0],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[1],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[2],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[3],
__func__, iir_idx, band_idx,
(uint32_t)ucontrol->value.integer.value[4]);
return 0;
}
static void set_iir_band_coeff(struct snd_soc_codec *codec,
int iir_idx, int band_idx,
uint32_t value)
{
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value & 0xFF));
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 8) & 0xFF);
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 16) & 0xFF);
/* Mask top 2 bits, 7-8 are reserved */
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B2_CTL + 16 * iir_idx),
(value >> 24) & 0x3F);
}
static int tomtom_put_iir_band_audio_mixer(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int iir_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->reg;
int band_idx = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
/* Mask top bit it is reserved */
/* Updates addr automatically for each B2 write */
snd_soc_write(codec,
(TOMTOM_A_CDC_IIR1_COEF_B1_CTL + 16 * iir_idx),
(band_idx * BAND_MAX * sizeof(uint32_t)) & 0x7F);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[0]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[1]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[2]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[3]);
set_iir_band_coeff(codec, iir_idx, band_idx,
ucontrol->value.integer.value[4]);
pr_debug("%s: IIR #%d band #%d b0 = 0x%x\n"
"%s: IIR #%d band #%d b1 = 0x%x\n"
"%s: IIR #%d band #%d b2 = 0x%x\n"
"%s: IIR #%d band #%d a1 = 0x%x\n"
"%s: IIR #%d band #%d a2 = 0x%x\n",
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 0),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 1),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 2),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 3),
__func__, iir_idx, band_idx,
get_iir_band_coeff(codec, iir_idx, band_idx, 4));
return 0;
}
static int tomtom_get_compander(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
int comp = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
ucontrol->value.integer.value[0] = tomtom->comp_enabled[comp];
return 0;
}
static int tomtom_set_compander(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int comp = ((struct soc_multi_mixer_control *)
kcontrol->private_value)->shift;
int value = ucontrol->value.integer.value[0];
pr_debug("%s: Compander %d enable current %d, new %d\n",
__func__, comp, tomtom->comp_enabled[comp], value);
tomtom->comp_enabled[comp] = value;
if (comp == COMPANDER_1 &&
tomtom->comp_enabled[comp] == 1) {
/* Wavegen to 5 msec */
snd_soc_write(codec, TOMTOM_A_RX_HPH_CNP_WG_CTL, 0xDB);
snd_soc_write(codec, TOMTOM_A_RX_HPH_CNP_WG_TIME, 0x2A);
snd_soc_write(codec, TOMTOM_A_RX_HPH_BIAS_WG_OCP, 0x2A);
/* Enable Chopper */
snd_soc_update_bits(codec,
TOMTOM_A_RX_HPH_CHOP_CTL, 0x80, 0x80);
snd_soc_write(codec, TOMTOM_A_NCP_DTEST, 0x20);
pr_debug("%s: Enabled Chopper and set wavegen to 5 msec\n",
__func__);
} else if (comp == COMPANDER_1 &&
tomtom->comp_enabled[comp] == 0) {
/* Wavegen to 20 msec */
snd_soc_write(codec, TOMTOM_A_RX_HPH_CNP_WG_CTL, 0xDB);
snd_soc_write(codec, TOMTOM_A_RX_HPH_CNP_WG_TIME, 0x58);
snd_soc_write(codec, TOMTOM_A_RX_HPH_BIAS_WG_OCP, 0x1A);
/* Disable CHOPPER block */
snd_soc_update_bits(codec,
TOMTOM_A_RX_HPH_CHOP_CTL, 0x80, 0x00);
snd_soc_write(codec, TOMTOM_A_NCP_DTEST, 0x10);
pr_debug("%s: Disabled Chopper and set wavegen to 20 msec\n",
__func__);
}
return 0;
}
static int tomtom_config_gain_compander(struct snd_soc_codec *codec,
int comp, bool enable)
{
int ret = 0;
switch (comp) {
case COMPANDER_0:
snd_soc_update_bits(codec, TOMTOM_A_SPKR_DRV1_GAIN,
1 << 2, !enable << 2);
snd_soc_update_bits(codec, TOMTOM_A_SPKR_DRV2_GAIN,
1 << 2, !enable << 2);
break;
case COMPANDER_1:
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_L_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_R_GAIN,
1 << 5, !enable << 5);
break;
case COMPANDER_2:
snd_soc_update_bits(codec, TOMTOM_A_RX_LINE_1_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TOMTOM_A_RX_LINE_3_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TOMTOM_A_RX_LINE_2_GAIN,
1 << 5, !enable << 5);
snd_soc_update_bits(codec, TOMTOM_A_RX_LINE_4_GAIN,
1 << 5, !enable << 5);
break;
default:
WARN_ON(1);
ret = -EINVAL;
}
return ret;
}
static void tomtom_discharge_comp(struct snd_soc_codec *codec, int comp)
{
/* Level meter DIV Factor to 5*/
snd_soc_update_bits(codec, TOMTOM_A_CDC_COMP0_B2_CTL + (comp * 8), 0xF0,
0x05 << 4);
/* RMS meter Sampling to 0x01 */
snd_soc_write(codec, TOMTOM_A_CDC_COMP0_B3_CTL + (comp * 8), 0x01);
/* Worst case timeout for compander CnP sleep timeout */
usleep_range(3000, 3100);
}
static enum wcd9xxx_buck_volt tomtom_codec_get_buck_mv(
struct snd_soc_codec *codec)
{
int buck_volt = WCD9XXX_CDC_BUCK_UNSUPPORTED;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_pdata *pdata = tomtom->resmgr.pdata;
int i;
for (i = 0; i < ARRAY_SIZE(pdata->regulator); i++) {
if (!strcmp(pdata->regulator[i].name,
WCD9XXX_SUPPLY_BUCK_NAME)) {
if ((pdata->regulator[i].min_uV ==
WCD9XXX_CDC_BUCK_MV_1P8) ||
(pdata->regulator[i].min_uV ==
WCD9XXX_CDC_BUCK_MV_2P15))
buck_volt = pdata->regulator[i].min_uV;
break;
}
}
return buck_volt;
}
static int tomtom_config_compander(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int mask, enable_mask;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
const int comp = w->shift;
const u32 rate = tomtom->comp_fs[comp];
const struct comp_sample_dependent_params *comp_params =
&comp_samp_params[rate];
enum wcd9xxx_buck_volt buck_mv;
pr_debug("%s: %s event %d compander %d, enabled %d", __func__,
w->name, event, comp, tomtom->comp_enabled[comp]);
if (!tomtom->comp_enabled[comp])
return 0;
/* Compander 0 has two channels */
mask = enable_mask = 0x03;
buck_mv = tomtom_codec_get_buck_mv(codec);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Set compander Sample rate */
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_FS_CFG + (comp * 8),
0x07, rate);
/* Set the static gain offset for HPH Path */
if (comp == COMPANDER_1) {
if (buck_mv == WCD9XXX_CDC_BUCK_MV_2P15) {
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B4_CTL + (comp * 8),
0x80, 0x00);
} else {
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B4_CTL + (comp * 8),
0x80, 0x80);
}
}
/* Enable RX interpolation path compander clocks */
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_B2_CTL,
mask << comp_shift[comp],
mask << comp_shift[comp]);
/* Toggle compander reset bits */
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp],
mask << comp_shift[comp]);
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp], 0);
/* Set gain source to compander */
tomtom_config_gain_compander(codec, comp, true);
/* Compander enable */
snd_soc_update_bits(codec, TOMTOM_A_CDC_COMP0_B1_CTL +
(comp * 8), enable_mask, enable_mask);
tomtom_discharge_comp(codec, comp);
/* Set sample rate dependent paramater */
snd_soc_write(codec, TOMTOM_A_CDC_COMP0_B3_CTL + (comp * 8),
comp_params->rms_meter_resamp_fact);
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B2_CTL + (comp * 8),
0xF0, comp_params->rms_meter_div_fact << 4);
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B2_CTL + (comp * 8),
0x0F, comp_params->peak_det_timeout);
break;
case SND_SOC_DAPM_PRE_PMD:
/* Disable compander */
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B1_CTL + (comp * 8),
enable_mask, 0x00);
/* Toggle compander reset bits */
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp],
mask << comp_shift[comp]);
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_OTHR_RESET_B2_CTL,
mask << comp_shift[comp], 0);
/* Turn off the clock for compander in pair */
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_B2_CTL,
mask << comp_shift[comp], 0);
/* Set gain source to register */
tomtom_config_gain_compander(codec, comp, false);
if (comp == COMPANDER_1)
snd_soc_update_bits(codec,
TOMTOM_A_CDC_COMP0_B4_CTL + (comp * 8),
0x80, 0x00);
break;
}
return 0;
}
static const char *const tomtom_anc_func_text[] = {"OFF", "ON"};
static const struct soc_enum tomtom_anc_func_enum =
SOC_ENUM_SINGLE_EXT(2, tomtom_anc_func_text);
static const char *const tabla_ear_pa_gain_text[] = {"POS_6_DB", "POS_2_DB"};
static const struct soc_enum tabla_ear_pa_gain_enum[] = {
SOC_ENUM_SINGLE_EXT(2, tabla_ear_pa_gain_text),
};
/*cut of frequency for high pass filter*/
static const char * const cf_text[] = {
"MIN_3DB_4Hz", "MIN_3DB_75Hz", "MIN_3DB_150Hz"
};
static const char * const rx_cf_text[] = {
"MIN_3DB_4Hz", "MIN_3DB_75Hz", "MIN_3DB_150Hz",
"MIN_3DB_0P48Hz"
};
static const struct soc_enum cf_dec1_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX1_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec2_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX2_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec3_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX3_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec4_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX4_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec5_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX5_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec6_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX6_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec7_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX7_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec8_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX8_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec9_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX9_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_dec10_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_TX10_MUX_CTL, 4, 3, cf_text);
static const struct soc_enum cf_rxmix1_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX1_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix2_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX2_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix3_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX3_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix4_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX4_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix5_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX5_B4_CTL, 0, 4, rx_cf_text)
;
static const struct soc_enum cf_rxmix6_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX6_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix7_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX7_B4_CTL, 0, 4, rx_cf_text);
static const struct soc_enum cf_rxmix8_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_RX8_B4_CTL, 0, 4, rx_cf_text);
static const char * const class_h_dsm_text[] = {
"ZERO", "DSM_HPHL_RX1", "DSM_SPKR_RX7"
};
static const struct soc_enum class_h_dsm_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_CLSH_CTL, 4, 3, class_h_dsm_text);
static const struct snd_kcontrol_new class_h_dsm_mux =
SOC_DAPM_ENUM("CLASS_H_DSM MUX Mux", class_h_dsm_enum);
static const char * const rx1_interp_text[] = {
"ZERO", "RX1 MIX2"
};
static const struct soc_enum rx1_interp_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CLK_RX_B1_CTL, 0, 2, rx1_interp_text);
static const struct snd_kcontrol_new rx1_interp_mux =
SOC_DAPM_ENUM("RX1 INTERP MUX Mux", rx1_interp_enum);
static const char * const rx2_interp_text[] = {
"ZERO", "RX2 MIX2"
};
static const struct soc_enum rx2_interp_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CLK_RX_B1_CTL, 1, 2, rx2_interp_text);
static const struct snd_kcontrol_new rx2_interp_mux =
SOC_DAPM_ENUM("RX2 INTERP MUX Mux", rx2_interp_enum);
static const char *const tomtom_conn_mad_text[] = {
"ADC_MB", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "ADC6", "NOTUSED1",
"DMIC1", "DMIC2", "DMIC3", "DMIC4", "DMIC5", "DMIC6", "NOTUSED2",
"NOTUSED3"};
static const struct soc_enum tomtom_conn_mad_enum =
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(tomtom_conn_mad_text),
tomtom_conn_mad_text);
static int tomtom_mad_input_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 tomtom_mad_input;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
tomtom_mad_input = snd_soc_read(codec, TOMTOM_A_CDC_MAD_INP_SEL);
tomtom_mad_input = tomtom_mad_input & 0x0F;
ucontrol->value.integer.value[0] = tomtom_mad_input;
pr_debug("%s: tomtom_mad_input = %s\n", __func__,
tomtom_conn_mad_text[tomtom_mad_input]);
return 0;
}
static int tomtom_mad_input_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 tomtom_mad_input;
u16 micb_int_reg, micb_4_int_reg;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct snd_soc_card *card = codec->card;
char mad_amic_input_widget[6];
u32 adc;
const char *mad_input_widget;
const char *source_widget = NULL;
u32 mic_bias_found = 0;
u32 i;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int ret = 0;
char *mad_input;
tomtom_mad_input = ucontrol->value.integer.value[0];
micb_4_int_reg = tomtom->resmgr.reg_addr->micb_4_int_rbias;
pr_debug("%s: tomtom_mad_input = %s\n", __func__,
tomtom_conn_mad_text[tomtom_mad_input]);
if (!strcmp(tomtom_conn_mad_text[tomtom_mad_input], "NOTUSED1") ||
!strcmp(tomtom_conn_mad_text[tomtom_mad_input], "NOTUSED2") ||
!strcmp(tomtom_conn_mad_text[tomtom_mad_input], "NOTUSED3") ||
!strcmp(tomtom_conn_mad_text[tomtom_mad_input], "ADC_MB")) {
pr_info("%s: tomtom mad input is set to unsupported input = %s\n",
__func__, tomtom_conn_mad_text[tomtom_mad_input]);
return -EINVAL;
}
if (strnstr(tomtom_conn_mad_text[tomtom_mad_input],
"ADC", sizeof("ADC"))) {
mad_input = strpbrk(tomtom_conn_mad_text[tomtom_mad_input],
"123456");
if (!mad_input) {
dev_err(codec->dev, "%s: Invalid MAD input %s\n",
__func__, tomtom_conn_mad_text[tomtom_mad_input]);
return -EINVAL;
}
ret = kstrtouint(mad_input, 10, &adc);
if ((ret < 0) || (adc > 6)) {
pr_err("%s: Invalid ADC = %s\n", __func__,
tomtom_conn_mad_text[tomtom_mad_input]);
ret = -EINVAL;
}
snprintf(mad_amic_input_widget, 6, "%s%u", "AMIC", adc);
mad_input_widget = mad_amic_input_widget;
pr_debug("%s: tomtom amic input widget = %s\n", __func__,
mad_amic_input_widget);
} else {
/* DMIC type input widget*/
mad_input_widget = tomtom_conn_mad_text[tomtom_mad_input];
}
pr_debug("%s: tomtom input widget = %s\n", __func__, mad_input_widget);
for (i = 0; i < card->num_dapm_routes; i++) {
if (!strcmp(card->dapm_routes[i].sink, mad_input_widget)) {
source_widget = card->dapm_routes[i].source;
if (!source_widget) {
dev_err(codec->dev,
"%s: invalid source widget\n",
__func__);
return -EINVAL;
}
if (strnstr(source_widget,
"MIC BIAS1", sizeof("MIC BIAS1"))) {
mic_bias_found = 1;
micb_int_reg = TOMTOM_A_MICB_1_INT_RBIAS;
break;
} else if (strnstr(source_widget,
"MIC BIAS2", sizeof("MIC BIAS2"))) {
mic_bias_found = 2;
micb_int_reg = TOMTOM_A_MICB_2_INT_RBIAS;
break;
} else if (strnstr(source_widget,
"MIC BIAS3", sizeof("MIC BIAS3"))) {
mic_bias_found = 3;
micb_int_reg = TOMTOM_A_MICB_3_INT_RBIAS;
break;
} else if (strnstr(source_widget,
"MIC BIAS4", sizeof("MIC BIAS4"))) {
mic_bias_found = 4;
micb_int_reg = micb_4_int_reg;
break;
}
}
}
if (mic_bias_found) {
pr_debug("%s: source mic bias = %s. sink = %s\n", __func__,
card->dapm_routes[i].source,
card->dapm_routes[i].sink);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_INP_SEL,
0x0F, tomtom_mad_input);
snd_soc_update_bits(codec, TOMTOM_A_MAD_ANA_CTRL,
0x07, mic_bias_found);
/* Setup internal micbias */
if (strnstr(source_widget, "Internal1", strlen(source_widget)))
snd_soc_update_bits(codec,
micb_int_reg,
0xE0, 0xE0);
else if (strnstr(source_widget, "Internal2",
strlen(source_widget)))
snd_soc_update_bits(codec,
micb_int_reg,
0x1C, 0x1C);
else if (strnstr(source_widget, "Internal3",
strlen(source_widget)))
snd_soc_update_bits(codec,
micb_int_reg,
0x3, 0x3);
else
/*
* If not internal, make sure to write the
* register to default value
*/
snd_soc_write(codec, micb_int_reg, 0x24);
return 0;
} else {
pr_err("%s: mic bias source not found for input = %s\n",
__func__, mad_input_widget);
return -EINVAL;
}
}
static int tomtom_tx_hpf_bypass_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u32 tx_index;
tx_index = (u32)kcontrol->private_value;
if (tx_index > NUM_DECIMATORS) {
pr_err("%s: Invalid TX decimator %d\n", __func__,
tx_index);
return -EINVAL;
}
ucontrol->value.integer.value[0] =
tx_hpf_work[tx_index-1].tx_hpf_bypass;
return 0;
}
static int tomtom_tx_hpf_bypass_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
bool tx_hpf_bypass_cfg;
u32 tx_index;
tx_hpf_bypass_cfg = (bool)ucontrol->value.integer.value[0];
pr_debug("%s: tx_hpf_bypass = %d\n", __func__,
tx_hpf_bypass_cfg);
tx_index = (u32)kcontrol->private_value;
if (tx_index > NUM_DECIMATORS) {
pr_err("%s: Invalid TX decimator %d\n", __func__,
tx_index);
return -EINVAL;
}
if (tx_hpf_work[tx_index-1].tx_hpf_bypass != tx_hpf_bypass_cfg)
tx_hpf_work[tx_index-1].tx_hpf_bypass = tx_hpf_bypass_cfg;
pr_debug("%s: Set TX%d HPF bypass configuration %d",
__func__, tx_index,
tx_hpf_work[tx_index-1].tx_hpf_bypass);
return 0;
}
static const struct snd_kcontrol_new tomtom_snd_controls[] = {
SOC_SINGLE_SX_TLV("RX1 Digital Volume", TOMTOM_A_CDC_RX1_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX2 Digital Volume", TOMTOM_A_CDC_RX2_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX3 Digital Volume", TOMTOM_A_CDC_RX3_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX4 Digital Volume", TOMTOM_A_CDC_RX4_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX5 Digital Volume", TOMTOM_A_CDC_RX5_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX6 Digital Volume", TOMTOM_A_CDC_RX6_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX7 Digital Volume", TOMTOM_A_CDC_RX7_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("RX8 Digital Volume", TOMTOM_A_CDC_RX8_VOL_CTL_B2_CTL,
0, -84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC1 Volume", TOMTOM_A_CDC_TX1_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC2 Volume", TOMTOM_A_CDC_TX2_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC3 Volume", TOMTOM_A_CDC_TX3_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC4 Volume", TOMTOM_A_CDC_TX4_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC5 Volume", TOMTOM_A_CDC_TX5_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC6 Volume", TOMTOM_A_CDC_TX6_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC7 Volume", TOMTOM_A_CDC_TX7_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC8 Volume", TOMTOM_A_CDC_TX8_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC9 Volume", TOMTOM_A_CDC_TX9_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("DEC10 Volume", TOMTOM_A_CDC_TX10_VOL_CTL_GAIN, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP1 Volume", TOMTOM_A_CDC_IIR1_GAIN_B1_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP2 Volume", TOMTOM_A_CDC_IIR1_GAIN_B2_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP3 Volume", TOMTOM_A_CDC_IIR1_GAIN_B3_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR1 INP4 Volume", TOMTOM_A_CDC_IIR1_GAIN_B4_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR2 INP1 Volume", TOMTOM_A_CDC_IIR2_GAIN_B1_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR2 INP2 Volume", TOMTOM_A_CDC_IIR2_GAIN_B2_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR2 INP3 Volume", TOMTOM_A_CDC_IIR2_GAIN_B3_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_SX_TLV("IIR2 INP4 Volume", TOMTOM_A_CDC_IIR2_GAIN_B4_CTL, 0,
-84, 40, digital_gain),
SOC_SINGLE_EXT("ANC Slot", SND_SOC_NOPM, 0, 100, 0, tomtom_get_anc_slot,
tomtom_put_anc_slot),
SOC_ENUM_EXT("ANC Function", tomtom_anc_func_enum, tomtom_get_anc_func,
tomtom_put_anc_func),
SOC_ENUM("TX1 HPF cut off", cf_dec1_enum),
SOC_ENUM("TX2 HPF cut off", cf_dec2_enum),
SOC_ENUM("TX3 HPF cut off", cf_dec3_enum),
SOC_ENUM("TX4 HPF cut off", cf_dec4_enum),
SOC_ENUM("TX5 HPF cut off", cf_dec5_enum),
SOC_ENUM("TX6 HPF cut off", cf_dec6_enum),
SOC_ENUM("TX7 HPF cut off", cf_dec7_enum),
SOC_ENUM("TX8 HPF cut off", cf_dec8_enum),
SOC_ENUM("TX9 HPF cut off", cf_dec9_enum),
SOC_ENUM("TX10 HPF cut off", cf_dec10_enum),
SOC_SINGLE_BOOL_EXT("TX1 HPF Switch", 1,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX2 HPF Switch", 2,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX3 HPF Switch", 3,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX4 HPF Switch", 4,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX5 HPF Switch", 5,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX6 HPF Switch", 6,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX7 HPF Switch", 7,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX8 HPF Switch", 8,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX9 HPF Switch", 9,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE_BOOL_EXT("TX10 HPF Switch", 10,
tomtom_tx_hpf_bypass_get,
tomtom_tx_hpf_bypass_put),
SOC_SINGLE("RX1 HPF Switch", TOMTOM_A_CDC_RX1_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX2 HPF Switch", TOMTOM_A_CDC_RX2_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX3 HPF Switch", TOMTOM_A_CDC_RX3_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX4 HPF Switch", TOMTOM_A_CDC_RX4_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX5 HPF Switch", TOMTOM_A_CDC_RX5_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX6 HPF Switch", TOMTOM_A_CDC_RX6_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX7 HPF Switch", TOMTOM_A_CDC_RX7_B5_CTL, 2, 1, 0),
SOC_SINGLE("RX8 HPF Switch", TOMTOM_A_CDC_RX8_B5_CTL, 2, 1, 0),
SOC_ENUM("RX1 HPF cut off", cf_rxmix1_enum),
SOC_ENUM("RX2 HPF cut off", cf_rxmix2_enum),
SOC_ENUM("RX3 HPF cut off", cf_rxmix3_enum),
SOC_ENUM("RX4 HPF cut off", cf_rxmix4_enum),
SOC_ENUM("RX5 HPF cut off", cf_rxmix5_enum),
SOC_ENUM("RX6 HPF cut off", cf_rxmix6_enum),
SOC_ENUM("RX7 HPF cut off", cf_rxmix7_enum),
SOC_ENUM("RX8 HPF cut off", cf_rxmix8_enum),
SOC_SINGLE_EXT("IIR1 Enable Band1", IIR1, BAND1, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band2", IIR1, BAND2, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band3", IIR1, BAND3, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band4", IIR1, BAND4, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR1 Enable Band5", IIR1, BAND5, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band1", IIR2, BAND1, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band2", IIR2, BAND2, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band3", IIR2, BAND3, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band4", IIR2, BAND4, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_EXT("IIR2 Enable Band5", IIR2, BAND5, 1, 0,
tomtom_get_iir_enable_audio_mixer, tomtom_put_iir_enable_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band1", IIR1, BAND1, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band2", IIR1, BAND2, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band3", IIR1, BAND3, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band4", IIR1, BAND4, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR1 Band5", IIR1, BAND5, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band1", IIR2, BAND1, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band2", IIR2, BAND2, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band3", IIR2, BAND3, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band4", IIR2, BAND4, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_MULTI_EXT("IIR2 Band5", IIR2, BAND5, 255, 0, 5,
tomtom_get_iir_band_audio_mixer, tomtom_put_iir_band_audio_mixer),
SOC_SINGLE_EXT("COMP0 Switch", SND_SOC_NOPM, COMPANDER_0, 1, 0,
tomtom_get_compander, tomtom_set_compander),
SOC_SINGLE_EXT("COMP1 Switch", SND_SOC_NOPM, COMPANDER_1, 1, 0,
tomtom_get_compander, tomtom_set_compander),
SOC_SINGLE_EXT("COMP2 Switch", SND_SOC_NOPM, COMPANDER_2, 1, 0,
tomtom_get_compander, tomtom_set_compander),
SOC_ENUM_EXT("MAD Input", tomtom_conn_mad_enum,
tomtom_mad_input_get, tomtom_mad_input_put),
};
static int tomtom_pa_gain_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 ear_pa_gain;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
ear_pa_gain = snd_soc_read(codec, TOMTOM_A_RX_EAR_GAIN);
ear_pa_gain = ear_pa_gain >> 5;
ucontrol->value.integer.value[0] = ear_pa_gain;
pr_debug("%s: ear_pa_gain = 0x%x\n", __func__, ear_pa_gain);
return 0;
}
static int tomtom_pa_gain_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
u8 ear_pa_gain;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
pr_debug("%s: ucontrol->value.integer.value[0] = %ld\n", __func__,
ucontrol->value.integer.value[0]);
ear_pa_gain = ucontrol->value.integer.value[0] << 5;
snd_soc_update_bits(codec, TOMTOM_A_RX_EAR_GAIN, 0xE0, ear_pa_gain);
return 0;
}
static const char * const tomtom_1_x_ear_pa_gain_text[] = {
"POS_6_DB", "POS_4P5_DB", "POS_3_DB", "POS_1P5_DB",
"POS_0_DB", "NEG_2P5_DB", "UNDEFINED", "NEG_12_DB"
};
static const struct soc_enum tomtom_1_x_ear_pa_gain_enum =
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(tomtom_1_x_ear_pa_gain_text),
tomtom_1_x_ear_pa_gain_text);
static const struct snd_kcontrol_new tomtom_1_x_analog_gain_controls[] = {
SOC_ENUM_EXT("EAR PA Gain", tomtom_1_x_ear_pa_gain_enum,
tomtom_pa_gain_get, tomtom_pa_gain_put),
SOC_SINGLE_TLV("HPHL Volume", TOMTOM_A_RX_HPH_L_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("HPHR Volume", TOMTOM_A_RX_HPH_R_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT1 Volume", TOMTOM_A_RX_LINE_1_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT2 Volume", TOMTOM_A_RX_LINE_2_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT3 Volume", TOMTOM_A_RX_LINE_3_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("LINEOUT4 Volume", TOMTOM_A_RX_LINE_4_GAIN, 0, 20, 1,
line_gain),
SOC_SINGLE_TLV("SPK DRV Volume", TOMTOM_A_SPKR_DRV1_GAIN, 3, 8, 1,
line_gain),
SOC_SINGLE_TLV("SPK DRV2 Volume", TOMTOM_A_SPKR_DRV2_GAIN, 3, 8, 1,
line_gain),
SOC_SINGLE_TLV("ADC1 Volume", TOMTOM_A_TX_1_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC2 Volume", TOMTOM_A_TX_2_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC3 Volume", TOMTOM_A_TX_3_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC4 Volume", TOMTOM_A_TX_4_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC5 Volume", TOMTOM_A_TX_5_GAIN, 2, 19, 0,
analog_gain),
SOC_SINGLE_TLV("ADC6 Volume", TOMTOM_A_TX_6_GAIN, 2, 19, 0,
analog_gain),
};
static int tomtom_hph_impedance_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
uint32_t zl, zr;
bool hphr;
struct soc_multi_mixer_control *mc;
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
mc = (struct soc_multi_mixer_control *)(kcontrol->private_value);
hphr = mc->shift;
wcd9xxx_mbhc_get_impedance(&priv->mbhc, &zl, &zr);
pr_debug("%s: zl %u, zr %u\n", __func__, zl, zr);
ucontrol->value.integer.value[0] = hphr ? zr : zl;
return 0;
}
static const struct snd_kcontrol_new impedance_detect_controls[] = {
SOC_SINGLE_EXT("HPHL Impedance", 0, 0, UINT_MAX, 0,
tomtom_hph_impedance_get, NULL),
SOC_SINGLE_EXT("HPHR Impedance", 0, 1, UINT_MAX, 0,
tomtom_hph_impedance_get, NULL),
};
static int tomtom_get_hph_type(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol);
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_mbhc *mbhc;
if (!priv) {
pr_debug("%s: wcd9330 private data is NULL\n", __func__);
return 0;
}
mbhc = &priv->mbhc;
if (!mbhc) {
pr_debug("%s: mbhc not initialized\n", __func__);
return 0;
}
ucontrol->value.integer.value[0] = (u32) mbhc->hph_type;
pr_debug("%s: hph_type = %u\n", __func__, mbhc->hph_type);
return 0;
}
static const struct snd_kcontrol_new hph_type_detect_controls[] = {
SOC_SINGLE_EXT("HPH Type", 0, 0, UINT_MAX, 0,
tomtom_get_hph_type, NULL),
};
static const char * const rx_mix1_text[] = {
"ZERO", "SRC1", "SRC2", "IIR1", "IIR2", "RX1", "RX2", "RX3", "RX4",
"RX5", "RX6", "RX7"
};
static const char * const rx8_mix1_text[] = {
"ZERO", "IIR1", "IIR2", "RX1", "RX2", "RX3", "RX4",
"RX5", "RX6", "RX7", "RX8"
};
static const char * const rx_mix2_text[] = {
"ZERO", "SRC1", "SRC2", "IIR1", "IIR2"
};
static const char * const rx_rdac5_text[] = {
"DEM4", "DEM3_INV"
};
static const char * const rx_rdac7_text[] = {
"DEM6", "DEM5_INV"
};
static const char * const mad_sel_text[] = {
"SPE", "MSM"
};
static const char * const sb_tx1_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC1", "RMIX8"
};
static const char * const sb_tx2_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC2", "RMIX8"
};
static const char * const sb_tx3_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC3", "RMIX8"
};
static const char * const sb_tx4_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC4", "RMIX8"
};
static const char * const sb_tx5_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC5", "RMIX8"
};
static const char * const sb_tx6_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC6", "RMIX8"
};
static const char * const sb_tx7_to_tx10_mux_text[] = {
"ZERO", "RMIX1", "RMIX2", "RMIX3", "RMIX4", "RMIX5", "RMIX6", "RMIX7",
"DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10"
};
static const char * const dec1_mux_text[] = {
"ZERO", "DMIC1", "ADC6",
};
static const char * const dec2_mux_text[] = {
"ZERO", "DMIC2", "ADC5",
};
static const char * const dec3_mux_text[] = {
"ZERO", "DMIC3", "ADC4",
};
static const char * const dec4_mux_text[] = {
"ZERO", "DMIC4", "ADC3",
};
static const char * const dec5_mux_text[] = {
"ZERO", "DMIC5", "ADC2",
};
static const char * const dec6_mux_text[] = {
"ZERO", "DMIC6", "ADC1",
};
static const char * const dec7_mux_text[] = {
"ZERO", "DMIC1", "DMIC6", "ADC1", "ADC6", "ANC1_FB", "ANC2_FB",
};
static const char * const dec8_mux_text[] = {
"ZERO", "DMIC2", "DMIC5", "ADC2", "ADC5", "ANC1_FB", "ANC2_FB",
};
static const char * const dec9_mux_text[] = {
"ZERO", "DMIC4", "DMIC5", "ADC2", "ADC3", "ADCMB", "ANC1_FB", "ANC2_FB",
};
static const char * const dec10_mux_text[] = {
"ZERO", "DMIC3", "DMIC6", "ADC1", "ADC4", "ADCMB", "ANC1_FB", "ANC2_FB",
};
static const char * const anc_mux_text[] = {
"ZERO", "ADC1", "ADC2", "ADC3", "ADC4", "ADC5", "ADC6", "ADC_MB",
"RSVD_1", "DMIC1", "DMIC2", "DMIC3", "DMIC4", "DMIC5", "DMIC6"
};
static const char * const anc1_fb_mux_text[] = {
"ZERO", "EAR_HPH_L", "EAR_LINE_1",
};
static const char * const iir_inp1_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10", "RX1", "RX2", "RX3", "RX4", "RX5", "RX6", "RX7"
};
static const char * const iir_inp2_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10", "RX1", "RX2", "RX3", "RX4", "RX5", "RX6", "RX7"
};
static const char * const iir_inp3_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10", "RX1", "RX2", "RX3", "RX4", "RX5", "RX6", "RX7"
};
static const char * const iir_inp4_text[] = {
"ZERO", "DEC1", "DEC2", "DEC3", "DEC4", "DEC5", "DEC6", "DEC7", "DEC8",
"DEC9", "DEC10", "RX1", "RX2", "RX3", "RX4", "RX5", "RX6", "RX7"
};
static const struct soc_enum rx_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx_mix1_inp3_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B2_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx2_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX2_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx2_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX2_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx3_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX3_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx3_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX3_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx4_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX4_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx4_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX4_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx5_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX5_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx5_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX5_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx6_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX6_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx6_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX6_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx7_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX7_B1_CTL, 0, 12, rx_mix1_text);
static const struct soc_enum rx7_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX7_B1_CTL, 4, 12, rx_mix1_text);
static const struct soc_enum rx8_mix1_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX8_B1_CTL, 0, 11, rx8_mix1_text);
static const struct soc_enum rx8_mix1_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX8_B1_CTL, 4, 11, rx8_mix1_text);
static const struct soc_enum rx1_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx1_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX1_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx2_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX2_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx2_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX2_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx7_mix2_inp1_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX7_B3_CTL, 0, 5, rx_mix2_text);
static const struct soc_enum rx7_mix2_inp2_chain_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_RX7_B3_CTL, 3, 5, rx_mix2_text);
static const struct soc_enum rx_rdac5_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_MISC, 2, 2, rx_rdac5_text);
static const struct soc_enum rx_rdac7_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_MISC, 1, 2, rx_rdac7_text);
static const struct soc_enum mad_sel_enum =
SOC_ENUM_SINGLE(TOMTOM_A_SVASS_CFG, 0, 2, mad_sel_text);
static const struct soc_enum sb_tx1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B1_CTL, 0, 10, sb_tx1_mux_text);
static const struct soc_enum sb_tx2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B2_CTL, 0, 10, sb_tx2_mux_text);
static const struct soc_enum sb_tx3_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B3_CTL, 0, 10, sb_tx3_mux_text);
static const struct soc_enum sb_tx4_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B4_CTL, 0, 10, sb_tx4_mux_text);
static const struct soc_enum sb_tx5_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B5_CTL, 0, 10, sb_tx5_mux_text);
static const struct soc_enum sb_tx6_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B6_CTL, 0, 10, sb_tx6_mux_text);
static const struct soc_enum sb_tx7_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B7_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum sb_tx8_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B8_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum sb_tx9_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B9_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum sb_tx10_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_SB_B10_CTL, 0, 18,
sb_tx7_to_tx10_mux_text);
static const struct soc_enum dec1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B1_CTL, 0, 3, dec1_mux_text);
static const struct soc_enum dec2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B1_CTL, 2, 3, dec2_mux_text);
static const struct soc_enum dec3_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B1_CTL, 4, 3, dec3_mux_text);
static const struct soc_enum dec4_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B1_CTL, 6, 3, dec4_mux_text);
static const struct soc_enum dec5_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B2_CTL, 0, 3, dec5_mux_text);
static const struct soc_enum dec6_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B2_CTL, 2, 3, dec6_mux_text);
static const struct soc_enum dec7_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B2_CTL, 4, 7, dec7_mux_text);
static const struct soc_enum dec8_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B3_CTL, 0, 7, dec8_mux_text);
static const struct soc_enum dec9_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B3_CTL, 3, 8, dec9_mux_text);
static const struct soc_enum dec10_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_TX_B4_CTL, 0, 8, dec10_mux_text);
static const struct soc_enum anc1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_ANC_B1_CTL, 0, 15, anc_mux_text);
static const struct soc_enum anc2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_ANC_B1_CTL, 4, 15, anc_mux_text);
static const struct soc_enum anc1_fb_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_ANC_B2_CTL, 0, 3, anc1_fb_mux_text);
static const struct soc_enum iir1_inp1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ1_B1_CTL, 0, 18, iir_inp1_text);
static const struct soc_enum iir2_inp1_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ2_B1_CTL, 0, 18, iir_inp1_text);
static const struct soc_enum iir1_inp2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ1_B2_CTL, 0, 18, iir_inp2_text);
static const struct soc_enum iir2_inp2_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ2_B2_CTL, 0, 18, iir_inp2_text);
static const struct soc_enum iir1_inp3_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ1_B3_CTL, 0, 18, iir_inp3_text);
static const struct soc_enum iir2_inp3_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ2_B3_CTL, 0, 18, iir_inp3_text);
static const struct soc_enum iir1_inp4_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ1_B4_CTL, 0, 18, iir_inp4_text);
static const struct soc_enum iir2_inp4_mux_enum =
SOC_ENUM_SINGLE(TOMTOM_A_CDC_CONN_EQ2_B4_CTL, 0, 18, iir_inp4_text);
static const struct snd_kcontrol_new rx_mix1_inp1_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP1 Mux", rx_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx_mix1_inp2_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP2 Mux", rx_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx_mix1_inp3_mux =
SOC_DAPM_ENUM("RX1 MIX1 INP3 Mux", rx_mix1_inp3_chain_enum);
static const struct snd_kcontrol_new rx2_mix1_inp1_mux =
SOC_DAPM_ENUM("RX2 MIX1 INP1 Mux", rx2_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx2_mix1_inp2_mux =
SOC_DAPM_ENUM("RX2 MIX1 INP2 Mux", rx2_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx3_mix1_inp1_mux =
SOC_DAPM_ENUM("RX3 MIX1 INP1 Mux", rx3_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx3_mix1_inp2_mux =
SOC_DAPM_ENUM("RX3 MIX1 INP2 Mux", rx3_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx4_mix1_inp1_mux =
SOC_DAPM_ENUM("RX4 MIX1 INP1 Mux", rx4_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx4_mix1_inp2_mux =
SOC_DAPM_ENUM("RX4 MIX1 INP2 Mux", rx4_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx5_mix1_inp1_mux =
SOC_DAPM_ENUM("RX5 MIX1 INP1 Mux", rx5_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx5_mix1_inp2_mux =
SOC_DAPM_ENUM("RX5 MIX1 INP2 Mux", rx5_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx6_mix1_inp1_mux =
SOC_DAPM_ENUM("RX6 MIX1 INP1 Mux", rx6_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx6_mix1_inp2_mux =
SOC_DAPM_ENUM("RX6 MIX1 INP2 Mux", rx6_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx7_mix1_inp1_mux =
SOC_DAPM_ENUM("RX7 MIX1 INP1 Mux", rx7_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx7_mix1_inp2_mux =
SOC_DAPM_ENUM("RX7 MIX1 INP2 Mux", rx7_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx8_mix1_inp1_mux =
SOC_DAPM_ENUM("RX8 MIX1 INP1 Mux", rx8_mix1_inp1_chain_enum);
static const struct snd_kcontrol_new rx8_mix1_inp2_mux =
SOC_DAPM_ENUM("RX8 MIX1 INP2 Mux", rx8_mix1_inp2_chain_enum);
static const struct snd_kcontrol_new rx1_mix2_inp1_mux =
SOC_DAPM_ENUM("RX1 MIX2 INP1 Mux", rx1_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx1_mix2_inp2_mux =
SOC_DAPM_ENUM("RX1 MIX2 INP2 Mux", rx1_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx2_mix2_inp1_mux =
SOC_DAPM_ENUM("RX2 MIX2 INP1 Mux", rx2_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx2_mix2_inp2_mux =
SOC_DAPM_ENUM("RX2 MIX2 INP2 Mux", rx2_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx7_mix2_inp1_mux =
SOC_DAPM_ENUM("RX7 MIX2 INP1 Mux", rx7_mix2_inp1_chain_enum);
static const struct snd_kcontrol_new rx7_mix2_inp2_mux =
SOC_DAPM_ENUM("RX7 MIX2 INP2 Mux", rx7_mix2_inp2_chain_enum);
static const struct snd_kcontrol_new rx_dac5_mux =
SOC_DAPM_ENUM("RDAC5 MUX Mux", rx_rdac5_enum);
static const struct snd_kcontrol_new rx_dac7_mux =
SOC_DAPM_ENUM("RDAC7 MUX Mux", rx_rdac7_enum);
static const struct snd_kcontrol_new mad_sel_mux =
SOC_DAPM_ENUM("MAD_SEL MUX Mux", mad_sel_enum);
static const struct snd_kcontrol_new sb_tx1_mux =
SOC_DAPM_ENUM("SLIM TX1 MUX Mux", sb_tx1_mux_enum);
static const struct snd_kcontrol_new sb_tx2_mux =
SOC_DAPM_ENUM("SLIM TX2 MUX Mux", sb_tx2_mux_enum);
static const struct snd_kcontrol_new sb_tx3_mux =
SOC_DAPM_ENUM("SLIM TX3 MUX Mux", sb_tx3_mux_enum);
static const struct snd_kcontrol_new sb_tx4_mux =
SOC_DAPM_ENUM("SLIM TX4 MUX Mux", sb_tx4_mux_enum);
static const struct snd_kcontrol_new sb_tx5_mux =
SOC_DAPM_ENUM("SLIM TX5 MUX Mux", sb_tx5_mux_enum);
static const struct snd_kcontrol_new sb_tx6_mux =
SOC_DAPM_ENUM("SLIM TX6 MUX Mux", sb_tx6_mux_enum);
static const struct snd_kcontrol_new sb_tx7_mux =
SOC_DAPM_ENUM("SLIM TX7 MUX Mux", sb_tx7_mux_enum);
static const struct snd_kcontrol_new sb_tx8_mux =
SOC_DAPM_ENUM("SLIM TX8 MUX Mux", sb_tx8_mux_enum);
static const struct snd_kcontrol_new sb_tx9_mux =
SOC_DAPM_ENUM("SLIM TX9 MUX Mux", sb_tx9_mux_enum);
static const struct snd_kcontrol_new sb_tx10_mux =
SOC_DAPM_ENUM("SLIM TX10 MUX Mux", sb_tx10_mux_enum);
static int wcd9330_put_dec_enum(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *w = wlist->widgets[0];
struct snd_soc_codec *codec = w->codec;
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
unsigned int dec_mux, decimator;
char *dec_name = NULL;
char *widget_name = NULL;
char *temp;
u16 tx_mux_ctl_reg;
u8 adc_dmic_sel = 0x0;
int ret = 0;
char *dec;
if (ucontrol->value.enumerated.item[0] > e->max - 1)
return -EINVAL;
dec_mux = ucontrol->value.enumerated.item[0];
widget_name = kstrndup(w->name, 15, GFP_KERNEL);
if (!widget_name)
return -ENOMEM;
temp = widget_name;
dec_name = strsep(&widget_name, " ");
widget_name = temp;
if (!dec_name) {
pr_err("%s: Invalid decimator = %s\n", __func__, w->name);
ret = -EINVAL;
goto out;
}
dec = strpbrk(dec_name, "123456789");
if (!dec) {
dev_err(w->dapm->dev, "%s: decimator index not found\n",
__func__);
ret = -EINVAL;
goto out;
}
ret = kstrtouint(dec, 10, &decimator);
if (ret < 0) {
pr_err("%s: Invalid decimator = %s\n", __func__, dec_name);
ret = -EINVAL;
goto out;
}
dev_dbg(w->dapm->dev, "%s(): widget = %s decimator = %u dec_mux = %u\n"
, __func__, w->name, decimator, dec_mux);
switch (decimator) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
if (dec_mux == 1)
adc_dmic_sel = 0x1;
else
adc_dmic_sel = 0x0;
break;
case 7:
case 8:
case 9:
case 10:
if ((dec_mux == 1) || (dec_mux == 2))
adc_dmic_sel = 0x1;
else
adc_dmic_sel = 0x0;
break;
default:
pr_err("%s: Invalid Decimator = %u\n", __func__, decimator);
ret = -EINVAL;
goto out;
}
tx_mux_ctl_reg = TOMTOM_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x1, adc_dmic_sel);
ret = snd_soc_dapm_put_enum_double(kcontrol, ucontrol);
out:
kfree(widget_name);
return ret;
}
#define WCD9330_DEC_ENUM(xname, xenum) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_soc_info_enum_double, \
.get = snd_soc_dapm_get_enum_double, \
.put = wcd9330_put_dec_enum, \
.private_value = (unsigned long)&xenum }
static const struct snd_kcontrol_new dec1_mux =
WCD9330_DEC_ENUM("DEC1 MUX Mux", dec1_mux_enum);
static const struct snd_kcontrol_new dec2_mux =
WCD9330_DEC_ENUM("DEC2 MUX Mux", dec2_mux_enum);
static const struct snd_kcontrol_new dec3_mux =
WCD9330_DEC_ENUM("DEC3 MUX Mux", dec3_mux_enum);
static const struct snd_kcontrol_new dec4_mux =
WCD9330_DEC_ENUM("DEC4 MUX Mux", dec4_mux_enum);
static const struct snd_kcontrol_new dec5_mux =
WCD9330_DEC_ENUM("DEC5 MUX Mux", dec5_mux_enum);
static const struct snd_kcontrol_new dec6_mux =
WCD9330_DEC_ENUM("DEC6 MUX Mux", dec6_mux_enum);
static const struct snd_kcontrol_new dec7_mux =
WCD9330_DEC_ENUM("DEC7 MUX Mux", dec7_mux_enum);
static const struct snd_kcontrol_new dec8_mux =
WCD9330_DEC_ENUM("DEC8 MUX Mux", dec8_mux_enum);
static const struct snd_kcontrol_new dec9_mux =
WCD9330_DEC_ENUM("DEC9 MUX Mux", dec9_mux_enum);
static const struct snd_kcontrol_new dec10_mux =
WCD9330_DEC_ENUM("DEC10 MUX Mux", dec10_mux_enum);
static const struct snd_kcontrol_new iir1_inp1_mux =
SOC_DAPM_ENUM("IIR1 INP1 Mux", iir1_inp1_mux_enum);
static const struct snd_kcontrol_new iir2_inp1_mux =
SOC_DAPM_ENUM("IIR2 INP1 Mux", iir2_inp1_mux_enum);
static const struct snd_kcontrol_new iir1_inp2_mux =
SOC_DAPM_ENUM("IIR1 INP2 Mux", iir1_inp2_mux_enum);
static const struct snd_kcontrol_new iir2_inp2_mux =
SOC_DAPM_ENUM("IIR2 INP2 Mux", iir2_inp2_mux_enum);
static const struct snd_kcontrol_new iir1_inp3_mux =
SOC_DAPM_ENUM("IIR1 INP3 Mux", iir1_inp3_mux_enum);
static const struct snd_kcontrol_new iir2_inp3_mux =
SOC_DAPM_ENUM("IIR2 INP3 Mux", iir2_inp3_mux_enum);
static const struct snd_kcontrol_new iir1_inp4_mux =
SOC_DAPM_ENUM("IIR1 INP4 Mux", iir1_inp4_mux_enum);
static const struct snd_kcontrol_new iir2_inp4_mux =
SOC_DAPM_ENUM("IIR2 INP4 Mux", iir2_inp4_mux_enum);
static const struct snd_kcontrol_new anc1_mux =
SOC_DAPM_ENUM("ANC1 MUX Mux", anc1_mux_enum);
static const struct snd_kcontrol_new anc2_mux =
SOC_DAPM_ENUM("ANC2 MUX Mux", anc2_mux_enum);
static const struct snd_kcontrol_new anc1_fb_mux =
SOC_DAPM_ENUM("ANC1 FB MUX Mux", anc1_fb_mux_enum);
static const struct snd_kcontrol_new dac1_switch[] = {
SOC_DAPM_SINGLE("Switch", TOMTOM_A_RX_EAR_EN, 5, 1, 0)
};
static const struct snd_kcontrol_new hphl_switch[] = {
SOC_DAPM_SINGLE("Switch", TOMTOM_A_RX_HPH_L_DAC_CTL, 6, 1, 0)
};
static const struct snd_kcontrol_new hphl_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
7, 1, 0),
};
static const struct snd_kcontrol_new hphr_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
6, 1, 0),
};
static const struct snd_kcontrol_new ear_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
5, 1, 0),
};
static const struct snd_kcontrol_new lineout1_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
4, 1, 0),
};
static const struct snd_kcontrol_new lineout2_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
3, 1, 0),
};
static const struct snd_kcontrol_new lineout3_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_L Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
2, 1, 0),
};
static const struct snd_kcontrol_new lineout4_pa_mix[] = {
SOC_DAPM_SINGLE("AUX_PGA_R Switch", TOMTOM_A_RX_PA_AUX_IN_CONN,
1, 1, 0),
};
static const struct snd_kcontrol_new lineout3_ground_switch =
SOC_DAPM_SINGLE("Switch", TOMTOM_A_RX_LINE_3_DAC_CTL, 6, 1, 0);
static const struct snd_kcontrol_new lineout4_ground_switch =
SOC_DAPM_SINGLE("Switch", TOMTOM_A_RX_LINE_4_DAC_CTL, 6, 1, 0);
static const struct snd_kcontrol_new aif4_mad_switch =
SOC_DAPM_SINGLE("Switch", TOMTOM_A_SVASS_CLKRST_CTL, 0, 1, 0);
static int tomtom_vi_feed_mixer_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.integer.value[0] = widget->value;
return 0;
}
static int tomtom_vi_feed_mixer_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_multi_mixer_control *mixer =
((struct soc_multi_mixer_control *)kcontrol->private_value);
u32 dai_id = widget->shift;
u32 port_id = mixer->shift;
u32 enable = ucontrol->value.integer.value[0];
pr_debug("%s: enable: %d, port_id:%d, dai_id: %d\n",
__func__, enable, port_id, dai_id);
mutex_lock(&codec->mutex);
if (enable) {
if (port_id == TOMTOM_TX11 && !test_bit(VI_SENSE_1,
&tomtom_p->status_mask)) {
list_add_tail(&core->tx_chs[TOMTOM_TX11].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list);
list_add_tail(&core->tx_chs[TOMTOM_TX12].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list);
set_bit(VI_SENSE_1, &tomtom_p->status_mask);
}
if (port_id == TOMTOM_TX14 && !test_bit(VI_SENSE_2,
&tomtom_p->status_mask)) {
list_add_tail(&core->tx_chs[TOMTOM_TX14].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list);
list_add_tail(&core->tx_chs[TOMTOM_TX15].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list);
set_bit(VI_SENSE_2, &tomtom_p->status_mask);
}
} else {
if (port_id == TOMTOM_TX11 && test_bit(VI_SENSE_1,
&tomtom_p->status_mask)) {
list_del_init(&core->tx_chs[TOMTOM_TX11].list);
list_del_init(&core->tx_chs[TOMTOM_TX12].list);
clear_bit(VI_SENSE_1, &tomtom_p->status_mask);
}
if (port_id == TOMTOM_TX14 && test_bit(VI_SENSE_2,
&tomtom_p->status_mask)) {
list_del_init(&core->tx_chs[TOMTOM_TX14].list);
list_del_init(&core->tx_chs[TOMTOM_TX15].list);
clear_bit(VI_SENSE_2, &tomtom_p->status_mask);
}
}
mutex_unlock(&codec->mutex);
snd_soc_dapm_mixer_update_power(widget, kcontrol, enable);
return 0;
}
/* virtual port entries */
static int slim_tx_mixer_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.integer.value[0] = widget->value;
return 0;
}
static int slim_tx_mixer_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_multi_mixer_control *mixer =
((struct soc_multi_mixer_control *)kcontrol->private_value);
u32 dai_id = widget->shift;
u32 port_id = mixer->shift;
u32 enable = ucontrol->value.integer.value[0];
u32 vtable = vport_check_table[dai_id];
pr_debug("%s: wname %s cname %s value %u shift %d item %ld\n", __func__,
widget->name, ucontrol->id.name, widget->value, widget->shift,
ucontrol->value.integer.value[0]);
mutex_lock(&codec->mutex);
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (dai_id != AIF1_CAP) {
dev_err(codec->dev, "%s: invalid AIF for I2C mode\n",
__func__);
mutex_unlock(&codec->mutex);
return -EINVAL;
}
}
switch (dai_id) {
case AIF1_CAP:
case AIF2_CAP:
case AIF3_CAP:
/* only add to the list if value not set
*/
if (enable && !(widget->value & 1 << port_id)) {
if (tomtom_p->intf_type ==
WCD9XXX_INTERFACE_TYPE_SLIMBUS)
vtable = vport_check_table[dai_id];
if (tomtom_p->intf_type ==
WCD9XXX_INTERFACE_TYPE_I2C)
vtable = vport_i2s_check_table[dai_id];
if (wcd9xxx_tx_vport_validation(
vtable,
port_id,
tomtom_p->dai, NUM_CODEC_DAIS)) {
dev_dbg(codec->dev, "%s: TX%u is used by other virtual port\n",
__func__, port_id + 1);
mutex_unlock(&codec->mutex);
return 0;
}
widget->value |= 1 << port_id;
list_add_tail(&core->tx_chs[port_id].list,
&tomtom_p->dai[dai_id].wcd9xxx_ch_list
);
} else if (!enable && (widget->value & 1 << port_id)) {
widget->value &= ~(1 << port_id);
list_del_init(&core->tx_chs[port_id].list);
} else {
if (enable)
dev_dbg(codec->dev, "%s: TX%u port is used by\n"
"this virtual port\n",
__func__, port_id + 1);
else
dev_dbg(codec->dev, "%s: TX%u port is not used by\n"
"this virtual port\n",
__func__, port_id + 1);
/* avoid update power function */
mutex_unlock(&codec->mutex);
return 0;
}
break;
default:
pr_err("Unknown AIF %d\n", dai_id);
mutex_unlock(&codec->mutex);
return -EINVAL;
}
pr_debug("%s: name %s sname %s updated value %u shift %d\n", __func__,
widget->name, widget->sname, widget->value, widget->shift);
mutex_unlock(&codec->mutex);
snd_soc_dapm_mixer_update_power(widget, kcontrol, enable);
return 0;
}
static int slim_rx_mux_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
ucontrol->value.enumerated.item[0] = widget->value;
return 0;
}
static const char *const slim_rx_mux_text[] = {
"ZERO", "AIF1_PB", "AIF2_PB", "AIF3_PB"
};
static int slim_rx_mux_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_soc_dapm_widget_list *wlist = snd_kcontrol_chip(kcontrol);
struct snd_soc_dapm_widget *widget = wlist->widgets[0];
struct snd_soc_codec *codec = widget->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *core = dev_get_drvdata(codec->dev->parent);
struct soc_enum *e = (struct soc_enum *)kcontrol->private_value;
u32 port_id = widget->shift;
pr_debug("%s: wname %s cname %s value %u shift %d item %ld\n", __func__,
widget->name, ucontrol->id.name, widget->value, widget->shift,
ucontrol->value.integer.value[0]);
widget->value = ucontrol->value.enumerated.item[0];
mutex_lock(&codec->mutex);
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
if (widget->value > 2) {
dev_err(codec->dev, "%s: invalid AIF for I2C mode\n",
__func__);
goto err;
}
}
/* value need to match the Virtual port and AIF number
*/
switch (widget->value) {
case 0:
list_del_init(&core->rx_chs[port_id].list);
break;
case 1:
if (wcd9xxx_rx_vport_validation(port_id +
TOMTOM_RX_PORT_START_NUMBER,
&tomtom_p->dai[AIF1_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tomtom_p->dai[AIF1_PB].wcd9xxx_ch_list);
break;
case 2:
if (wcd9xxx_rx_vport_validation(port_id +
TOMTOM_RX_PORT_START_NUMBER,
&tomtom_p->dai[AIF2_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tomtom_p->dai[AIF2_PB].wcd9xxx_ch_list);
break;
case 3:
if (wcd9xxx_rx_vport_validation(port_id +
TOMTOM_RX_PORT_START_NUMBER,
&tomtom_p->dai[AIF3_PB].wcd9xxx_ch_list)) {
dev_dbg(codec->dev, "%s: RX%u is used by current requesting AIF_PB itself\n",
__func__, port_id + 1);
goto rtn;
}
list_add_tail(&core->rx_chs[port_id].list,
&tomtom_p->dai[AIF3_PB].wcd9xxx_ch_list);
break;
default:
pr_err("Unknown AIF %d\n", widget->value);
goto err;
}
rtn:
mutex_unlock(&codec->mutex);
snd_soc_dapm_mux_update_power(widget, kcontrol, widget->value, e);
return 0;
err:
mutex_unlock(&codec->mutex);
return -EINVAL;
}
static const struct soc_enum slim_rx_mux_enum =
SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(slim_rx_mux_text), slim_rx_mux_text);
static const struct snd_kcontrol_new slim_rx_mux[TOMTOM_RX_MAX] = {
SOC_DAPM_ENUM_EXT("SLIM RX1 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX2 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX3 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX4 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX5 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX6 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX7 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
SOC_DAPM_ENUM_EXT("SLIM RX8 Mux", slim_rx_mux_enum,
slim_rx_mux_get, slim_rx_mux_put),
};
static const struct snd_kcontrol_new aif4_vi_mixer[] = {
SOC_SINGLE_EXT("SPKR_VI_1", SND_SOC_NOPM, TOMTOM_TX11, 1, 0,
tomtom_vi_feed_mixer_get, tomtom_vi_feed_mixer_put),
SOC_SINGLE_EXT("SPKR_VI_2", SND_SOC_NOPM, TOMTOM_TX14, 1, 0,
tomtom_vi_feed_mixer_get, tomtom_vi_feed_mixer_put),
};
static const struct snd_kcontrol_new aif1_cap_mixer[] = {
SOC_SINGLE_EXT("SLIM TX1", SND_SOC_NOPM, TOMTOM_TX1, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX2", SND_SOC_NOPM, TOMTOM_TX2, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX3", SND_SOC_NOPM, TOMTOM_TX3, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX4", SND_SOC_NOPM, TOMTOM_TX4, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX5", SND_SOC_NOPM, TOMTOM_TX5, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX6", SND_SOC_NOPM, TOMTOM_TX6, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX7", SND_SOC_NOPM, TOMTOM_TX7, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX8", SND_SOC_NOPM, TOMTOM_TX8, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX9", SND_SOC_NOPM, TOMTOM_TX9, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX10", SND_SOC_NOPM, TOMTOM_TX10, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
};
static const struct snd_kcontrol_new aif2_cap_mixer[] = {
SOC_SINGLE_EXT("SLIM TX1", SND_SOC_NOPM, TOMTOM_TX1, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX2", SND_SOC_NOPM, TOMTOM_TX2, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX3", SND_SOC_NOPM, TOMTOM_TX3, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX4", SND_SOC_NOPM, TOMTOM_TX4, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX5", SND_SOC_NOPM, TOMTOM_TX5, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX6", SND_SOC_NOPM, TOMTOM_TX6, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX7", SND_SOC_NOPM, TOMTOM_TX7, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX8", SND_SOC_NOPM, TOMTOM_TX8, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX9", SND_SOC_NOPM, TOMTOM_TX9, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX10", SND_SOC_NOPM, TOMTOM_TX10, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
};
static const struct snd_kcontrol_new aif3_cap_mixer[] = {
SOC_SINGLE_EXT("SLIM TX1", SND_SOC_NOPM, TOMTOM_TX1, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX2", SND_SOC_NOPM, TOMTOM_TX2, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX3", SND_SOC_NOPM, TOMTOM_TX3, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX4", SND_SOC_NOPM, TOMTOM_TX4, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX5", SND_SOC_NOPM, TOMTOM_TX5, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX6", SND_SOC_NOPM, TOMTOM_TX6, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX7", SND_SOC_NOPM, TOMTOM_TX7, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX8", SND_SOC_NOPM, TOMTOM_TX8, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX9", SND_SOC_NOPM, TOMTOM_TX9, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
SOC_SINGLE_EXT("SLIM TX10", SND_SOC_NOPM, TOMTOM_TX10, 1, 0,
slim_tx_mixer_get, slim_tx_mixer_put),
};
static void tomtom_codec_enable_adc_block(struct snd_soc_codec *codec,
int enable)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %d\n", __func__, enable);
if (enable) {
tomtom->adc_count++;
snd_soc_update_bits(codec, WCD9XXX_A_CDC_CLK_OTHR_CTL,
0x2, 0x2);
} else {
tomtom->adc_count--;
if (!tomtom->adc_count)
snd_soc_update_bits(codec, WCD9XXX_A_CDC_CLK_OTHR_CTL,
0x2, 0x0);
}
}
static int tomtom_codec_enable_adc(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
u16 adc_reg;
u16 tx_fe_clkdiv_reg;
u8 tx_fe_clkdiv_mask;
u8 init_bit_shift;
u8 bit_pos;
pr_debug("%s %d\n", __func__, event);
switch (w->reg) {
case TOMTOM_A_TX_1_GAIN:
adc_reg = TOMTOM_A_TX_1_2_TEST_CTL;
tx_fe_clkdiv_reg = TOMTOM_A_TX_1_2_TXFE_CLKDIV;
tx_fe_clkdiv_mask = 0x0F;
init_bit_shift = 7;
bit_pos = ADC1_TXFE;
break;
case TOMTOM_A_TX_2_GAIN:
adc_reg = TOMTOM_A_TX_1_2_TEST_CTL;
tx_fe_clkdiv_reg = TOMTOM_A_TX_1_2_TXFE_CLKDIV;
tx_fe_clkdiv_mask = 0xF0;
init_bit_shift = 6;
bit_pos = ADC2_TXFE;
break;
case TOMTOM_A_TX_3_GAIN:
adc_reg = TOMTOM_A_TX_3_4_TEST_CTL;
init_bit_shift = 7;
tx_fe_clkdiv_reg = TOMTOM_A_TX_3_4_TXFE_CKDIV;
tx_fe_clkdiv_mask = 0x0F;
bit_pos = ADC3_TXFE;
break;
case TOMTOM_A_TX_4_GAIN:
adc_reg = TOMTOM_A_TX_3_4_TEST_CTL;
init_bit_shift = 6;
tx_fe_clkdiv_reg = TOMTOM_A_TX_3_4_TXFE_CKDIV;
tx_fe_clkdiv_mask = 0xF0;
bit_pos = ADC4_TXFE;
break;
case TOMTOM_A_TX_5_GAIN:
adc_reg = TOMTOM_A_TX_5_6_TEST_CTL;
init_bit_shift = 7;
tx_fe_clkdiv_reg = TOMTOM_A_TX_5_6_TXFE_CKDIV;
tx_fe_clkdiv_mask = 0x0F;
bit_pos = ADC5_TXFE;
break;
case TOMTOM_A_TX_6_GAIN:
adc_reg = TOMTOM_A_TX_5_6_TEST_CTL;
init_bit_shift = 6;
tx_fe_clkdiv_reg = TOMTOM_A_TX_5_6_TXFE_CKDIV;
tx_fe_clkdiv_mask = 0xF0;
bit_pos = ADC6_TXFE;
break;
default:
pr_err("%s: Error, invalid adc register\n", __func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, tx_fe_clkdiv_reg, tx_fe_clkdiv_mask,
0x0);
set_bit(bit_pos, &priv->status_mask);
tomtom_codec_enable_adc_block(codec, 1);
snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift,
1 << init_bit_shift);
break;
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, adc_reg, 1 << init_bit_shift, 0x00);
break;
case SND_SOC_DAPM_POST_PMD:
tomtom_codec_enable_adc_block(codec, 0);
break;
}
return 0;
}
static int tomtom_codec_ext_clk_en(struct snd_soc_codec *codec,
int enable, bool dapm)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
if (!tomtom->codec_ext_clk_en_cb) {
dev_err(codec->dev,
"%s: Invalid ext_clk_callback\n",
__func__);
return -EINVAL;
}
return tomtom->codec_ext_clk_en_cb(codec, enable, dapm);
}
static int __tomtom_mclk_enable(struct tomtom_priv *tomtom, int mclk_enable)
{
int ret = 0;
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
if (mclk_enable) {
tomtom->ext_clk_users++;
if (tomtom->ext_clk_users > 1)
goto bg_clk_unlock;
ret = clk_prepare_enable(tomtom->wcd_ext_clk);
if (ret) {
pr_err("%s: ext clk enable failed\n",
__func__);
tomtom->ext_clk_users--;
goto bg_clk_unlock;
}
wcd9xxx_resmgr_get_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
wcd9xxx_resmgr_get_clk_block(&tomtom->resmgr, WCD9XXX_CLK_MCLK);
} else {
tomtom->ext_clk_users--;
if (tomtom->ext_clk_users == 0) {
/* Put clock and BG */
wcd9xxx_resmgr_put_clk_block(&tomtom->resmgr,
WCD9XXX_CLK_MCLK);
wcd9xxx_resmgr_put_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
clk_disable_unprepare(tomtom->wcd_ext_clk);
}
}
bg_clk_unlock:
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
return ret;
}
int tomtom_codec_mclk_enable(struct snd_soc_codec *codec,
int enable, bool dapm)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
if (tomtom->wcd_ext_clk) {
dev_dbg(codec->dev, "%s: mclk_enable = %u, dapm = %d\n",
__func__, enable, dapm);
return __tomtom_mclk_enable(tomtom, enable);
} else if (tomtom->codec_ext_clk_en_cb)
return tomtom_codec_ext_clk_en(codec, enable, dapm);
else {
dev_err(codec->dev,
"%s: Cannot turn on MCLK\n",
__func__);
return -EINVAL;
}
}
EXPORT_SYMBOL(tomtom_codec_mclk_enable);
static int tomtom_codec_get_ext_clk_users(struct tomtom_priv *tomtom)
{
if (tomtom->wcd_ext_clk)
return tomtom->ext_clk_users;
else if (tomtom->codec_get_ext_clk_cnt)
return tomtom->codec_get_ext_clk_cnt();
else
return 0;
}
/* tomtom_codec_internal_rco_ctrl( )
* Make sure that BG_CLK_LOCK is not acquired. Exit if acquired to avoid
* potential deadlock as ext_clk_en_cb() also tries to acquire the same
* lock to enable MCLK for RCO calibration
*/
static int tomtom_codec_internal_rco_ctrl(struct snd_soc_codec *codec,
bool enable)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int ret = 0;
if (mutex_is_locked(&tomtom->resmgr.codec_bg_clk_lock)) {
dev_err(codec->dev, "%s: BG_CLK already acquired\n",
__func__);
ret = -EINVAL;
goto done;
}
if (enable) {
if (wcd9xxx_resmgr_get_clk_type(&tomtom->resmgr) ==
WCD9XXX_CLK_RCO) {
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_get_clk_block(&tomtom->resmgr,
WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
} else {
tomtom_codec_mclk_enable(codec, true, false);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
tomtom->resmgr.ext_clk_users =
tomtom_codec_get_ext_clk_users(tomtom);
wcd9xxx_resmgr_get_clk_block(&tomtom->resmgr,
WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
tomtom_codec_mclk_enable(codec, false, false);
}
} else {
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_put_clk_block(&tomtom->resmgr,
WCD9XXX_CLK_RCO);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
}
done:
return ret;
}
static int tomtom_codec_enable_aux_pga(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_get_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
/* AUX PGA requires RCO or MCLK */
tomtom_codec_internal_rco_ctrl(codec, true);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_enable_rx_bias(&tomtom->resmgr, 1);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
break;
case SND_SOC_DAPM_POST_PMD:
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_enable_rx_bias(&tomtom->resmgr, 0);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
tomtom_codec_internal_rco_ctrl(codec, false);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
wcd9xxx_resmgr_put_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
break;
}
return 0;
}
static int tomtom_codec_enable_lineout(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
u16 lineout_gain_reg;
pr_debug("%s %d %s\n", __func__, event, w->name);
switch (w->shift) {
case 0:
lineout_gain_reg = TOMTOM_A_RX_LINE_1_GAIN;
break;
case 1:
lineout_gain_reg = TOMTOM_A_RX_LINE_2_GAIN;
break;
case 2:
lineout_gain_reg = TOMTOM_A_RX_LINE_3_GAIN;
break;
case 3:
lineout_gain_reg = TOMTOM_A_RX_LINE_4_GAIN;
break;
default:
pr_err("%s: Error, incorrect lineout register value\n",
__func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, lineout_gain_reg, 0x40, 0x40);
break;
case SND_SOC_DAPM_POST_PMU:
wcd9xxx_clsh_fsm(codec, &tomtom->clsh_d,
WCD9XXX_CLSH_STATE_LO,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
pr_debug("%s: sleeping 5 ms after %s PA turn on\n",
__func__, w->name);
/* Wait for CnP time after PA enable */
usleep_range(5000, 5100);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, lineout_gain_reg, 0x40, 0x00);
pr_debug("%s: sleeping 5 ms after %s PA turn off\n",
__func__, w->name);
/* Wait for CnP time after PA disable */
usleep_range(5000, 5100);
break;
}
return 0;
}
static int tomtom_codec_enable_spk_pa(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
u16 spk_drv_reg;
pr_debug("%s: %d %s\n", __func__, event, w->name);
if (strnstr(w->name, "SPK2 PA", sizeof("SPK2 PA")))
spk_drv_reg = TOMTOM_A_SPKR_DRV2_EN;
else
spk_drv_reg = TOMTOM_A_SPKR_DRV1_EN;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
tomtom->spkr_pa_widget_on = true;
snd_soc_update_bits(codec, spk_drv_reg, 0x80, 0x80);
break;
case SND_SOC_DAPM_POST_PMD:
tomtom->spkr_pa_widget_on = false;
snd_soc_update_bits(codec, spk_drv_reg, 0x80, 0x00);
break;
}
return 0;
}
static u8 tomtom_get_dmic_clk_val(struct snd_soc_codec *codec,
u32 mclk_rate, u32 dmic_clk_rate)
{
u32 div_factor;
u8 dmic_ctl_val;
dev_dbg(codec->dev,
"%s: mclk_rate = %d, dmic_sample_rate = %d\n",
__func__, mclk_rate, dmic_clk_rate);
/* Default value to return in case of error */
if (mclk_rate == TOMTOM_MCLK_CLK_9P6MHZ)
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_2;
else
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_3;
if (dmic_clk_rate == 0) {
dev_err(codec->dev,
"%s: dmic_sample_rate cannot be 0\n",
__func__);
goto done;
}
div_factor = mclk_rate / dmic_clk_rate;
switch (div_factor) {
case 2:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_2;
break;
case 3:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_3;
break;
case 4:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_4;
break;
case 6:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_6;
break;
case 16:
dmic_ctl_val = WCD9330_DMIC_CLK_DIV_16;
break;
default:
dev_err(codec->dev,
"%s: Invalid div_factor %u, clk_rate(%u), dmic_rate(%u)\n",
__func__, div_factor, mclk_rate, dmic_clk_rate);
break;
}
done:
return dmic_ctl_val;
}
static int tomtom_codec_enable_dmic(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_pdata *pdata = tomtom->resmgr.pdata;
u8 dmic_clk_en;
u16 dmic_clk_reg;
s32 *dmic_clk_cnt;
u8 dmic_rate_val, dmic_rate_shift;
unsigned int dmic;
int ret;
char *wname;
wname = strpbrk(w->name, "123456");
if (!wname) {
dev_err(codec->dev, "%s: widget not found\n", __func__);
return -EINVAL;
}
ret = kstrtouint(wname, 10, &dmic);
if (ret < 0) {
pr_err("%s: Invalid DMIC line on the codec\n", __func__);
return -EINVAL;
}
switch (dmic) {
case 1:
case 2:
dmic_clk_en = 0x01;
dmic_clk_cnt = &(tomtom->dmic_1_2_clk_cnt);
dmic_clk_reg = TOMTOM_A_DMIC_B1_CTL;
dmic_rate_shift = 5;
pr_debug("%s() event %d DMIC%d dmic_1_2_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
case 3:
case 4:
dmic_clk_en = 0x02;
dmic_clk_cnt = &(tomtom->dmic_3_4_clk_cnt);
dmic_clk_reg = TOMTOM_A_DMIC_B2_CTL;
dmic_rate_shift = 1;
pr_debug("%s() event %d DMIC%d dmic_3_4_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
case 5:
case 6:
dmic_clk_en = 0x04;
dmic_clk_cnt = &(tomtom->dmic_5_6_clk_cnt);
dmic_clk_reg = TOMTOM_A_DMIC_B2_CTL;
dmic_rate_shift = 4;
pr_debug("%s() event %d DMIC%d dmic_5_6_clk_cnt %d\n",
__func__, event, dmic, *dmic_clk_cnt);
break;
default:
pr_err("%s: Invalid DMIC Selection\n", __func__);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
dmic_rate_val =
tomtom_get_dmic_clk_val(codec,
pdata->mclk_rate,
pdata->dmic_sample_rate);
(*dmic_clk_cnt)++;
if (*dmic_clk_cnt == 1) {
snd_soc_update_bits(codec, dmic_clk_reg,
0x07 << dmic_rate_shift,
dmic_rate_val << dmic_rate_shift);
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B1_CTL,
dmic_clk_en, dmic_clk_en);
}
break;
case SND_SOC_DAPM_POST_PMD:
dmic_rate_val =
tomtom_get_dmic_clk_val(codec,
pdata->mclk_rate,
pdata->mad_dmic_sample_rate);
(*dmic_clk_cnt)--;
if (*dmic_clk_cnt == 0) {
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B1_CTL,
dmic_clk_en, 0);
snd_soc_update_bits(codec, dmic_clk_reg,
0x07 << dmic_rate_shift,
dmic_rate_val << dmic_rate_shift);
}
break;
}
return 0;
}
static int tomtom_codec_config_mad(struct snd_soc_codec *codec)
{
int ret;
const struct firmware *fw;
struct firmware_cal *hwdep_cal = NULL;
struct mad_audio_cal *mad_cal;
const void *data;
const char *filename = TOMTOM_MAD_AUDIO_FIRMWARE_PATH;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
size_t cal_size;
int idx;
pr_debug("%s: enter\n", __func__);
if (!tomtom->fw_data) {
dev_err(codec->dev, "%s: invalid cal data\n",
__func__);
return -ENODEV;
}
hwdep_cal = wcdcal_get_fw_cal(tomtom->fw_data, WCD9XXX_MAD_CAL);
if (hwdep_cal) {
data = hwdep_cal->data;
cal_size = hwdep_cal->size;
dev_dbg(codec->dev, "%s: using hwdep calibration\n",
__func__);
} else {
ret = request_firmware(&fw, filename, codec->dev);
if (ret != 0) {
pr_err("Failed to acquire MAD firwmare data %s: %d\n",
filename, ret);
return -ENODEV;
}
if (!fw) {
dev_err(codec->dev, "failed to get mad fw");
return -ENODEV;
}
data = fw->data;
cal_size = fw->size;
dev_dbg(codec->dev, "%s: using request_firmware calibration\n",
__func__);
}
if (cal_size < sizeof(struct mad_audio_cal)) {
pr_err("%s: incorrect hwdep cal size %zu\n",
__func__, cal_size);
ret = -ENOMEM;
goto err;
}
mad_cal = (struct mad_audio_cal *)(data);
if (!mad_cal) {
dev_err(codec->dev, "%s: Invalid calibration data\n",
__func__);
ret = -EINVAL;
goto err;
}
snd_soc_write(codec, TOMTOM_A_CDC_MAD_MAIN_CTL_2,
mad_cal->microphone_info.cycle_time);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_MAIN_CTL_1, 0xFF << 3,
((uint16_t)mad_cal->microphone_info.settle_time)
<< 3);
/* Audio */
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_8,
mad_cal->audio_info.rms_omit_samples);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_1,
0x07 << 4, mad_cal->audio_info.rms_comp_time << 4);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_2, 0x03 << 2,
mad_cal->audio_info.detection_mechanism << 2);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_7,
mad_cal->audio_info.rms_diff_threshold & 0x3F);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_5,
mad_cal->audio_info.rms_threshold_lsb);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_CTL_6,
mad_cal->audio_info.rms_threshold_msb);
for (idx = 0; idx < ARRAY_SIZE(mad_cal->audio_info.iir_coefficients);
idx++) {
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_AUDIO_IIR_CTL_PTR,
0x3F, idx);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_AUDIO_IIR_CTL_VAL,
mad_cal->audio_info.iir_coefficients[idx]);
dev_dbg(codec->dev, "%s:MAD Audio IIR Coef[%d] = 0X%x",
__func__, idx,
mad_cal->audio_info.iir_coefficients[idx]);
}
/* Beacon */
snd_soc_write(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_8,
mad_cal->beacon_info.rms_omit_samples);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_1,
0x07 << 4, mad_cal->beacon_info.rms_comp_time);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_2, 0x03 << 2,
mad_cal->beacon_info.detection_mechanism << 2);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_7,
mad_cal->beacon_info.rms_diff_threshold & 0x1F);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_5,
mad_cal->beacon_info.rms_threshold_lsb);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_6,
mad_cal->beacon_info.rms_threshold_msb);
/* Ultrasound */
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_BEACON_CTL_1,
0x07 << 4, mad_cal->beacon_info.rms_comp_time);
snd_soc_update_bits(codec, TOMTOM_A_CDC_MAD_ULTR_CTL_2, 0x03 << 2,
mad_cal->ultrasound_info.detection_mechanism);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_ULTR_CTL_7,
mad_cal->ultrasound_info.rms_diff_threshold & 0x1F);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_ULTR_CTL_5,
mad_cal->ultrasound_info.rms_threshold_lsb);
snd_soc_write(codec, TOMTOM_A_CDC_MAD_ULTR_CTL_6,
mad_cal->ultrasound_info.rms_threshold_msb);
/* Set MAD intr time to 20 msec */
snd_soc_update_bits(codec, 0x4E, 0x01F, 0x13);
pr_debug("%s: leave ret %d\n", __func__, ret);
err:
if (!hwdep_cal)
release_firmware(fw);
return ret;
}
static int tomtom_codec_enable_mad(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int ret = 0;
u8 mad_micb, mad_cfilt;
u16 mad_cfilt_reg;
mad_micb = snd_soc_read(codec, TOMTOM_A_MAD_ANA_CTRL) & 0x07;
switch (mad_micb) {
case 1:
mad_cfilt = tomtom->resmgr.pdata->micbias.bias1_cfilt_sel;
break;
case 2:
mad_cfilt = tomtom->resmgr.pdata->micbias.bias2_cfilt_sel;
break;
case 3:
mad_cfilt = tomtom->resmgr.pdata->micbias.bias3_cfilt_sel;
break;
case 4:
mad_cfilt = tomtom->resmgr.pdata->micbias.bias4_cfilt_sel;
break;
default:
dev_err(codec->dev,
"%s: Invalid micbias selection 0x%x\n",
__func__, mad_micb);
return -EINVAL;
}
switch (mad_cfilt) {
case WCD9XXX_CFILT1_SEL:
mad_cfilt_reg = TOMTOM_A_MICB_CFILT_1_VAL;
break;
case WCD9XXX_CFILT2_SEL:
mad_cfilt_reg = TOMTOM_A_MICB_CFILT_2_VAL;
break;
case WCD9XXX_CFILT3_SEL:
mad_cfilt_reg = TOMTOM_A_MICB_CFILT_3_VAL;
break;
default:
dev_err(codec->dev,
"%s: invalid cfilt 0x%x for micb 0x%x\n",
__func__, mad_cfilt, mad_micb);
return -EINVAL;
}
dev_dbg(codec->dev,
"%s event = %d, mad_cfilt_reg = 0x%x\n",
__func__, event, mad_cfilt_reg);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Undo reset for MAD */
snd_soc_update_bits(codec, TOMTOM_A_SVASS_CLKRST_CTL,
0x02, 0x00);
ret = tomtom_codec_config_mad(codec);
if (ret) {
pr_err("%s: Failed to config MAD\n", __func__);
break;
}
/* setup MAD micbias to VDDIO */
snd_soc_update_bits(codec, mad_cfilt_reg,
0x02, 0x02);
break;
case SND_SOC_DAPM_POST_PMD:
/* Reset the MAD block */
snd_soc_update_bits(codec, TOMTOM_A_SVASS_CLKRST_CTL,
0x02, 0x02);
/* Undo setup of MAD micbias to VDDIO */
snd_soc_update_bits(codec, mad_cfilt_reg,
0x02, 0x00);
}
return ret;
}
static int tomtom_codec_enable_micbias(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
u16 micb_int_reg = 0, micb_ctl_reg = 0;
u8 cfilt_sel_val = 0;
char *internal1_text = "Internal1";
char *internal2_text = "Internal2";
char *internal3_text = "Internal3";
enum wcd9xxx_notify_event e_post_off, e_pre_on, e_post_on;
pr_debug("%s: w->name %s event %d\n", __func__, w->name, event);
if (strnstr(w->name, "MIC BIAS1", sizeof("MIC BIAS1"))) {
micb_ctl_reg = TOMTOM_A_MICB_1_CTL;
micb_int_reg = TOMTOM_A_MICB_1_INT_RBIAS;
cfilt_sel_val = tomtom->resmgr.pdata->micbias.bias1_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_1_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_1_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_1_OFF;
} else if (strnstr(w->name, "MIC BIAS2", sizeof("MIC BIAS2"))) {
micb_ctl_reg = TOMTOM_A_MICB_2_CTL;
micb_int_reg = TOMTOM_A_MICB_2_INT_RBIAS;
cfilt_sel_val = tomtom->resmgr.pdata->micbias.bias2_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_2_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_2_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_2_OFF;
} else if (strnstr(w->name, "MIC BIAS3", sizeof("MIC BIAS3"))) {
micb_ctl_reg = TOMTOM_A_MICB_3_CTL;
micb_int_reg = TOMTOM_A_MICB_3_INT_RBIAS;
cfilt_sel_val = tomtom->resmgr.pdata->micbias.bias3_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_3_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_3_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_3_OFF;
} else if (strnstr(w->name, "MIC BIAS4", sizeof("MIC BIAS4"))) {
micb_ctl_reg = TOMTOM_A_MICB_4_CTL;
micb_int_reg = tomtom->resmgr.reg_addr->micb_4_int_rbias;
cfilt_sel_val = tomtom->resmgr.pdata->micbias.bias4_cfilt_sel;
e_pre_on = WCD9XXX_EVENT_PRE_MICBIAS_4_ON;
e_post_on = WCD9XXX_EVENT_POST_MICBIAS_4_ON;
e_post_off = WCD9XXX_EVENT_POST_MICBIAS_4_OFF;
} else {
pr_err("%s: Error, invalid micbias %s\n", __func__, w->name);
return -EINVAL;
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Let MBHC module know so micbias switch to be off */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_pre_on);
/* Get cfilt */
wcd9xxx_resmgr_cfilt_get(&tomtom->resmgr, cfilt_sel_val);
if (strnstr(w->name, internal1_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0xE0, 0xE0);
else if (strnstr(w->name, internal2_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x1C, 0x1C);
else if (strnstr(w->name, internal3_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x3, 0x3);
else
/*
* If not internal, make sure to write the
* register to default value
*/
snd_soc_write(codec, micb_int_reg, 0x24);
if (tomtom->mbhc_started && micb_ctl_reg ==
TOMTOM_A_MICB_2_CTL) {
if (++tomtom->micb_2_users == 1) {
if (tomtom->resmgr.pdata->
micbias.bias2_is_headset_only)
wcd9xxx_resmgr_add_cond_update_bits(
&tomtom->resmgr,
WCD9XXX_COND_HPH_MIC,
micb_ctl_reg, w->shift,
false);
else
snd_soc_update_bits(codec, micb_ctl_reg,
1 << w->shift,
1 << w->shift);
}
pr_debug("%s: micb_2_users %d\n", __func__,
tomtom->micb_2_users);
} else if (micb_ctl_reg == TOMTOM_A_MICB_3_CTL) {
if (++tomtom->micb_3_users == 1)
snd_soc_update_bits(codec, micb_ctl_reg,
1 << w->shift,
1 << w->shift);
} else {
snd_soc_update_bits(codec, micb_ctl_reg, 1 << w->shift,
1 << w->shift);
}
break;
case SND_SOC_DAPM_POST_PMU:
usleep_range(5000, 5100);
/* Let MBHC module know so micbias is on */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_post_on);
break;
case SND_SOC_DAPM_POST_PMD:
if (tomtom->mbhc_started && micb_ctl_reg ==
TOMTOM_A_MICB_2_CTL) {
if (--tomtom->micb_2_users == 0) {
if (tomtom->resmgr.pdata->
micbias.bias2_is_headset_only)
wcd9xxx_resmgr_rm_cond_update_bits(
&tomtom->resmgr,
WCD9XXX_COND_HPH_MIC,
micb_ctl_reg, 7, false);
else
snd_soc_update_bits(codec, micb_ctl_reg,
1 << w->shift, 0);
}
pr_debug("%s: micb_2_users %d\n", __func__,
tomtom->micb_2_users);
WARN(tomtom->micb_2_users < 0,
"Unexpected micbias users %d\n",
tomtom->micb_2_users);
} else if (micb_ctl_reg == TOMTOM_A_MICB_3_CTL) {
if (--tomtom->micb_3_users == 0)
snd_soc_update_bits(codec, micb_ctl_reg,
1 << w->shift, 0);
pr_debug("%s: micb_3_users %d\n", __func__,
tomtom->micb_3_users);
WARN(tomtom->micb_3_users < 0,
"Unexpected micbias-3 users %d\n",
tomtom->micb_3_users);
} else {
snd_soc_update_bits(codec, micb_ctl_reg, 1 << w->shift,
0);
}
/* Let MBHC module know so micbias switch to be off */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_post_off);
if (strnstr(w->name, internal1_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x80, 0x00);
else if (strnstr(w->name, internal2_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x10, 0x00);
else if (strnstr(w->name, internal3_text, 30))
snd_soc_update_bits(codec, micb_int_reg, 0x2, 0x0);
/* Put cfilt */
wcd9xxx_resmgr_cfilt_put(&tomtom->resmgr, cfilt_sel_val);
break;
}
return 0;
}
/* called under codec_resource_lock acquisition */
static int tomtom_enable_mbhc_micbias(struct snd_soc_codec *codec, bool enable,
enum wcd9xxx_micbias_num micb_num)
{
int rc;
if (micb_num != MBHC_MICBIAS2) {
dev_err(codec->dev, "%s: Unsupported micbias, micb_num=%d\n",
__func__, micb_num);
return -EINVAL;
}
if (enable)
rc = snd_soc_dapm_force_enable_pin(&codec->dapm,
DAPM_MICBIAS2_EXTERNAL_STANDALONE);
else
rc = snd_soc_dapm_disable_pin(&codec->dapm,
DAPM_MICBIAS2_EXTERNAL_STANDALONE);
if (!rc)
snd_soc_dapm_sync(&codec->dapm);
pr_debug("%s: leave ret %d\n", __func__, rc);
return rc;
}
static int tomtom_codec_enable_on_demand_supply(
struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int ret = 0;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
dev_dbg(codec->dev, "%s: event:%d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (priv->micbias_reg) {
ret = regulator_enable(priv->micbias_reg);
if (ret)
dev_err(codec->dev,
"%s: Failed to enable micbias_reg\n",
__func__);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (priv->micbias_reg) {
ret = regulator_disable(priv->micbias_reg);
if (ret)
dev_err(codec->dev,
"%s: Failed to disable micbias_reg\n",
__func__);
}
break;
default:
break;
}
return ret;
}
static void txfe_clkdiv_update(struct snd_soc_codec *codec)
{
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
if (test_bit(ADC1_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_1_2_TXFE_CLKDIV,
0x0F, 0x05);
clear_bit(ADC1_TXFE, &priv->status_mask);
}
if (test_bit(ADC2_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_1_2_TXFE_CLKDIV,
0xF0, 0x50);
clear_bit(ADC2_TXFE, &priv->status_mask);
}
if (test_bit(ADC3_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_3_4_TXFE_CKDIV,
0x0F, 0x05);
clear_bit(ADC3_TXFE, &priv->status_mask);
}
if (test_bit(ADC4_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_3_4_TXFE_CKDIV,
0xF0, 0x50);
clear_bit(ADC4_TXFE, &priv->status_mask);
}
if (test_bit(ADC5_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_5_6_TXFE_CKDIV,
0x0F, 0x05);
clear_bit(ADC5_TXFE, &priv->status_mask);
}
if (test_bit(ADC6_TXFE, &priv->status_mask)) {
snd_soc_update_bits(codec, TOMTOM_A_TX_5_6_TXFE_CKDIV,
0xF0, 0x50);
clear_bit(ADC6_TXFE, &priv->status_mask);
}
}
static void tx_hpf_corner_freq_callback(struct work_struct *work)
{
struct delayed_work *hpf_delayed_work;
struct hpf_work *hpf_work;
struct tomtom_priv *tomtom;
struct snd_soc_codec *codec;
u16 tx_mux_ctl_reg;
u8 hpf_cut_of_freq;
hpf_delayed_work = to_delayed_work(work);
hpf_work = container_of(hpf_delayed_work, struct hpf_work, dwork);
tomtom = hpf_work->tomtom;
codec = hpf_work->tomtom->codec;
hpf_cut_of_freq = hpf_work->tx_hpf_cut_of_freq;
tx_mux_ctl_reg = TOMTOM_A_CDC_TX1_MUX_CTL +
(hpf_work->decimator - 1) * 8;
pr_debug("%s(): decimator %u hpf_cut_of_freq 0x%x\n", __func__,
hpf_work->decimator, (unsigned int)hpf_cut_of_freq);
/*
* Restore TXFE ClkDiv registers to default.
* If any of these registers are modified during analog
* front-end enablement, they will be restored back to the
* default
*/
txfe_clkdiv_update(codec);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30, hpf_cut_of_freq << 4);
}
#define TX_MUX_CTL_CUT_OFF_FREQ_MASK 0x30
#define CF_MIN_3DB_4HZ 0x0
#define CF_MIN_3DB_75HZ 0x1
#define CF_MIN_3DB_150HZ 0x2
static int tomtom_codec_enable_dec(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
unsigned int decimator;
char *dec_name = NULL;
char *widget_name = NULL;
char *temp;
int ret = 0;
u16 dec_reset_reg, tx_vol_ctl_reg, tx_mux_ctl_reg;
u8 dec_hpf_cut_of_freq;
int offset;
char *dec;
pr_debug("%s %d\n", __func__, event);
widget_name = kstrndup(w->name, 15, GFP_KERNEL);
if (!widget_name)
return -ENOMEM;
temp = widget_name;
dec_name = strsep(&widget_name, " ");
widget_name = temp;
if (!dec_name) {
pr_err("%s: Invalid decimator = %s\n", __func__, w->name);
ret = -EINVAL;
goto out;
}
dec = strpbrk(dec_name, "123456789");
if (!dec) {
dev_err(codec->dev, "%s: decimator index not found\n",
__func__);
ret = -EINVAL;
goto out;
}
ret = kstrtouint(dec, 10, &decimator);
if (ret < 0) {
pr_err("%s: Invalid decimator = %s\n", __func__, dec_name);
ret = -EINVAL;
goto out;
}
pr_debug("%s(): widget = %s dec_name = %s decimator = %u\n", __func__,
w->name, dec_name, decimator);
if (w->reg == TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL) {
dec_reset_reg = TOMTOM_A_CDC_CLK_TX_RESET_B1_CTL;
offset = 0;
} else if (w->reg == TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL) {
dec_reset_reg = TOMTOM_A_CDC_CLK_TX_RESET_B2_CTL;
offset = 8;
} else {
pr_err("%s: Error, incorrect dec\n", __func__);
return -EINVAL;
}
tx_vol_ctl_reg = TOMTOM_A_CDC_TX1_VOL_CTL_CFG + 8 * (decimator - 1);
tx_mux_ctl_reg = TOMTOM_A_CDC_TX1_MUX_CTL + 8 * (decimator - 1);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Enableable TX digital mute */
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01);
snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift,
1 << w->shift);
snd_soc_update_bits(codec, dec_reset_reg, 1 << w->shift, 0x0);
pr_debug("%s: decimator = %u, bypass = %d\n", __func__,
decimator, tx_hpf_work[decimator - 1].tx_hpf_bypass);
if (tx_hpf_work[decimator - 1].tx_hpf_bypass != true) {
dec_hpf_cut_of_freq = snd_soc_read(codec,
tx_mux_ctl_reg);
dec_hpf_cut_of_freq = (dec_hpf_cut_of_freq & 0x30) >> 4;
tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq =
dec_hpf_cut_of_freq;
if ((dec_hpf_cut_of_freq != CF_MIN_3DB_150HZ)) {
/* set cut of freq to CF_MIN_3DB_150HZ (0x1); */
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30,
CF_MIN_3DB_150HZ << 4);
}
/* enable HPF */
snd_soc_update_bits(codec, tx_mux_ctl_reg , 0x08, 0x00);
} else
/* bypass HPF */
snd_soc_update_bits(codec, tx_mux_ctl_reg , 0x08, 0x08);
break;
case SND_SOC_DAPM_POST_PMU:
/* Disable TX digital mute */
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x00);
if ((tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq !=
CF_MIN_3DB_150HZ) &&
(tx_hpf_work[decimator - 1].tx_hpf_bypass != true)) {
schedule_delayed_work(&tx_hpf_work[decimator - 1].dwork,
msecs_to_jiffies(300));
}
/* apply the digital gain after the decimator is enabled*/
if ((w->shift + offset) < ARRAY_SIZE(tx_digital_gain_reg))
snd_soc_write(codec,
tx_digital_gain_reg[w->shift + offset],
snd_soc_read(codec,
tx_digital_gain_reg[w->shift + offset])
);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, tx_vol_ctl_reg, 0x01, 0x01);
cancel_delayed_work_sync(&tx_hpf_work[decimator - 1].dwork);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x08, 0x08);
snd_soc_update_bits(codec, tx_mux_ctl_reg, 0x30,
(tx_hpf_work[decimator - 1].tx_hpf_cut_of_freq) << 4);
break;
}
out:
kfree(widget_name);
return ret;
}
static int tomtom_codec_enable_vdd_spkr(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int ret = 0;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: %d %s\n", __func__, event, w->name);
WARN_ONCE(!priv->spkdrv_reg, "SPKDRV supply %s isn't defined\n",
WCD9XXX_VDD_SPKDRV_NAME);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (priv->spkdrv_reg) {
ret = regulator_enable(priv->spkdrv_reg);
if (ret)
pr_err("%s: Failed to enable spkdrv_reg %s\n",
__func__, WCD9XXX_VDD_SPKDRV_NAME);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (priv->spkdrv_reg) {
ret = regulator_disable(priv->spkdrv_reg);
if (ret)
pr_err("%s: Failed to disable spkdrv_reg %s\n",
__func__, WCD9XXX_VDD_SPKDRV_NAME);
}
break;
}
return ret;
}
static int tomtom_codec_enable_vdd_spkr2(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int ret = 0;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: %d %s\n", __func__, event, w->name);
/*
* If on-demand voltage regulators of spkr1 and spkr2 has been derived
* from same power rail then same on-demand voltage regulator can be
* used by both spkr1 and spkr2, if a separate device tree entry has
* not been defined for on-demand voltage regulator for spkr2.
*/
if (!priv->spkdrv2_reg) {
if (priv->spkdrv_reg) {
priv->spkdrv2_reg = priv->spkdrv_reg;
} else {
WARN_ONCE(!priv->spkdrv2_reg,
"SPKDRV2 supply %s isn't defined\n",
WCD9XXX_VDD_SPKDRV2_NAME);
return 0;
}
}
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (priv->spkdrv2_reg) {
ret = regulator_enable(priv->spkdrv2_reg);
if (ret)
pr_err("%s: Failed to enable spkdrv2_reg %s ret:%d\n",
__func__, WCD9XXX_VDD_SPKDRV2_NAME, ret);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (priv->spkdrv2_reg) {
ret = regulator_disable(priv->spkdrv2_reg);
if (ret)
pr_err("%s: Failed to disable spkdrv2_reg %s ret:%d\n",
__func__, WCD9XXX_VDD_SPKDRV2_NAME, ret);
}
break;
}
return ret;
}
static int tomtom_codec_enable_interpolator(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %d %s\n", __func__, event, w->name);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_RESET_CTL,
1 << w->shift, 1 << w->shift);
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_RESET_CTL,
1 << w->shift, 0x0);
break;
case SND_SOC_DAPM_POST_PMU:
/* apply the digital gain after the interpolator is enabled*/
if ((w->shift) < ARRAY_SIZE(rx_digital_gain_reg))
snd_soc_write(codec,
rx_digital_gain_reg[w->shift],
snd_soc_read(codec,
rx_digital_gain_reg[w->shift])
);
/* Check for Rx1 and Rx2 paths for uhqa mode update */
if (w->shift == 0 || w->shift == 1)
tomtom_update_uhqa_mode(codec, (1 << w->shift));
break;
}
return 0;
}
/* called under codec_resource_lock acquisition */
static int __tomtom_codec_enable_ldo_h(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: enter\n", __func__);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/*
* ldo_h_users is protected by codec->mutex, don't need
* additional mutex
*/
if (++priv->ldo_h_users == 1) {
WCD9XXX_BG_CLK_LOCK(&priv->resmgr);
wcd9xxx_resmgr_get_bandgap(&priv->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr);
tomtom_codec_internal_rco_ctrl(codec, true);
snd_soc_update_bits(codec, TOMTOM_A_LDO_H_MODE_1,
1 << 7, 1 << 7);
tomtom_codec_internal_rco_ctrl(codec, false);
pr_debug("%s: ldo_h_users %d\n", __func__,
priv->ldo_h_users);
/* LDO enable requires 1ms to settle down */
usleep_range(1000, 1100);
}
break;
case SND_SOC_DAPM_POST_PMD:
if (--priv->ldo_h_users == 0) {
tomtom_codec_internal_rco_ctrl(codec, true);
snd_soc_update_bits(codec, TOMTOM_A_LDO_H_MODE_1,
1 << 7, 0);
tomtom_codec_internal_rco_ctrl(codec, false);
WCD9XXX_BG_CLK_LOCK(&priv->resmgr);
wcd9xxx_resmgr_put_bandgap(&priv->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
WCD9XXX_BG_CLK_UNLOCK(&priv->resmgr);
pr_debug("%s: ldo_h_users %d\n", __func__,
priv->ldo_h_users);
}
WARN(priv->ldo_h_users < 0, "Unexpected ldo_h users %d\n",
priv->ldo_h_users);
break;
}
pr_debug("%s: leave\n", __func__);
return 0;
}
static int tomtom_codec_enable_ldo_h(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
int rc;
rc = __tomtom_codec_enable_ldo_h(w, kcontrol, event);
return rc;
}
static int tomtom_codec_enable_rx_bias(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
wcd9xxx_resmgr_enable_rx_bias(&tomtom->resmgr, 1);
break;
case SND_SOC_DAPM_POST_PMD:
wcd9xxx_resmgr_enable_rx_bias(&tomtom->resmgr, 0);
break;
}
return 0;
}
static int tomtom_codec_enable_anc(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
const char *filename;
const struct firmware *fw;
int i;
int ret = 0;
int num_anc_slots;
struct wcd9xxx_anc_header *anc_head;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct firmware_cal *hwdep_cal = NULL;
u32 anc_writes_size = 0;
u32 anc_cal_size = 0;
int anc_size_remaining;
u32 *anc_ptr;
u16 reg;
u8 mask, val, old_val;
size_t cal_size;
const void *data;
if (tomtom->anc_func == 0)
return 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
filename = "wcd9320/wcd9320_anc.bin";
hwdep_cal = wcdcal_get_fw_cal(tomtom->fw_data, WCD9XXX_ANC_CAL);
if (hwdep_cal) {
data = hwdep_cal->data;
cal_size = hwdep_cal->size;
dev_dbg(codec->dev, "%s: using hwdep calibration\n",
__func__);
} else {
ret = request_firmware(&fw, filename, codec->dev);
if (ret != 0) {
dev_err(codec->dev, "Failed to acquire ANC data: %d\n",
ret);
return -ENODEV;
}
if (!fw) {
dev_err(codec->dev, "failed to get anc fw");
return -ENODEV;
}
data = fw->data;
cal_size = fw->size;
dev_dbg(codec->dev, "%s: using request_firmware calibration\n",
__func__);
}
if (cal_size < sizeof(struct wcd9xxx_anc_header)) {
dev_err(codec->dev, "Not enough data\n");
ret = -ENOMEM;
goto err;
}
/* First number is the number of register writes */
anc_head = (struct wcd9xxx_anc_header *)(data);
anc_ptr = (u32 *)(data +
sizeof(struct wcd9xxx_anc_header));
anc_size_remaining = cal_size -
sizeof(struct wcd9xxx_anc_header);
num_anc_slots = anc_head->num_anc_slots;
if (tomtom->anc_slot >= num_anc_slots) {
dev_err(codec->dev, "Invalid ANC slot selected\n");
ret = -EINVAL;
goto err;
}
for (i = 0; i < num_anc_slots; i++) {
if (anc_size_remaining < TOMTOM_PACKED_REG_SIZE) {
dev_err(codec->dev, "Invalid register format\n");
ret = -EINVAL;
goto err;
}
anc_writes_size = (u32)(*anc_ptr);
anc_size_remaining -= sizeof(u32);
anc_ptr += 1;
if (anc_writes_size * TOMTOM_PACKED_REG_SIZE
> anc_size_remaining) {
dev_err(codec->dev, "Invalid register format\n");
ret = -EINVAL;
goto err;
}
if (tomtom->anc_slot == i)
break;
anc_size_remaining -= (anc_writes_size *
TOMTOM_PACKED_REG_SIZE);
anc_ptr += anc_writes_size;
}
if (i == num_anc_slots) {
dev_err(codec->dev, "Selected ANC slot not present\n");
ret = -EINVAL;
goto err;
}
i = 0;
anc_cal_size = anc_writes_size;
if (w->reg == TOMTOM_A_RX_HPH_L_DAC_CTL) {
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x03, 0x03);
anc_writes_size = (anc_cal_size/2);
}
if (w->reg == TOMTOM_A_RX_HPH_R_DAC_CTL) {
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x0C, 0x0C);
i = (anc_cal_size/2);
anc_writes_size = anc_cal_size;
}
for (; i < anc_writes_size; i++) {
TOMTOM_CODEC_UNPACK_ENTRY(anc_ptr[i], reg,
mask, val);
/*
* ANC Soft reset register is ignored from ACDB
* because ANC left soft reset bits will be called
* while enabling ANC HPH Right DAC.
*/
if ((reg == TOMTOM_A_CDC_CLK_ANC_RESET_CTL) &&
((w->reg == TOMTOM_A_RX_HPH_L_DAC_CTL) ||
(w->reg == TOMTOM_A_RX_HPH_R_DAC_CTL))) {
continue;
}
old_val = snd_soc_read(codec, reg);
snd_soc_write(codec, reg, (old_val & ~mask) |
(val & mask));
}
if (w->reg == TOMTOM_A_RX_HPH_L_DAC_CTL)
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x03, 0x00);
if (w->reg == TOMTOM_A_RX_HPH_R_DAC_CTL)
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x0C, 0x00);
if (!hwdep_cal)
release_firmware(fw);
txfe_clkdiv_update(codec);
break;
case SND_SOC_DAPM_PRE_PMD:
msleep(40);
snd_soc_update_bits(codec, TOMTOM_A_CDC_ANC1_B1_CTL, 0x01,
0x00);
snd_soc_update_bits(codec, TOMTOM_A_CDC_ANC2_B1_CTL, 0x02,
0x00);
msleep(20);
snd_soc_write(codec, TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x0F);
snd_soc_write(codec, TOMTOM_A_CDC_CLK_ANC_CLK_EN_CTL, 0);
snd_soc_write(codec, TOMTOM_A_CDC_CLK_ANC_RESET_CTL, 0x00);
break;
}
return 0;
err:
if (!hwdep_cal)
release_firmware(fw);
return ret;
}
static int tomtom_hphl_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
uint32_t impedl, impedr;
int ret = 0;
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (tomtom_p->anc_func) {
tomtom_codec_enable_anc(w, kcontrol, event);
msleep(50);
}
if (!high_perf_mode && !tomtom_p->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHL,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
} else {
wcd9xxx_enable_high_perf_mode(codec, &tomtom_p->clsh_d,
tomtom_p->uhqa_mode,
WCD9XXX_CLSAB_STATE_HPHL,
WCD9XXX_CLSAB_REQ_ENABLE);
}
ret = wcd9xxx_mbhc_get_impedance(&tomtom_p->mbhc,
&impedl, &impedr);
if (!ret)
wcd9xxx_clsh_imped_config(codec, impedl);
else
dev_dbg(codec->dev, "%s: Failed to get mbhc impedance %d\n",
__func__, ret);
break;
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX1_B3_CTL, 0xBC, 0x94);
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX1_B4_CTL, 0x30, 0x10);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX1_B3_CTL, 0xBC, 0x00);
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX1_B4_CTL, 0x30, 0x00);
break;
case SND_SOC_DAPM_POST_PMD:
if (!high_perf_mode && !tomtom_p->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHL,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
} else {
wcd9xxx_enable_high_perf_mode(codec, &tomtom_p->clsh_d,
tomtom_p->uhqa_mode,
WCD9XXX_CLSAB_STATE_HPHL,
WCD9XXX_CLSAB_REQ_DISABLE);
}
break;
}
return 0;
}
static int tomtom_hphr_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
if (tomtom_p->anc_func) {
tomtom_codec_enable_anc(w, kcontrol, event);
msleep(50);
}
snd_soc_update_bits(codec, w->reg, 0x40, 0x40);
if (!high_perf_mode && !tomtom_p->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHR,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
} else {
wcd9xxx_enable_high_perf_mode(codec, &tomtom_p->clsh_d,
tomtom_p->uhqa_mode,
WCD9XXX_CLSAB_STATE_HPHR,
WCD9XXX_CLSAB_REQ_ENABLE);
}
break;
case SND_SOC_DAPM_POST_PMU:
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX2_B3_CTL, 0xBC, 0x94);
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX2_B4_CTL, 0x30, 0x10);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX2_B3_CTL, 0xBC, 0x00);
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX2_B4_CTL, 0x30, 0x00);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, w->reg, 0x40, 0x00);
if (!high_perf_mode && !tomtom_p->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_HPHR,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
} else {
wcd9xxx_enable_high_perf_mode(codec, &tomtom_p->clsh_d,
tomtom_p->uhqa_mode,
WCD9XXX_CLSAB_STATE_HPHR,
WCD9XXX_CLSAB_REQ_DISABLE);
}
break;
}
return 0;
}
static int tomtom_hph_pa_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
enum wcd9xxx_notify_event e_pre_on, e_post_off;
u8 req_clsh_state;
u32 pa_settle_time = TOMTOM_HPH_PA_SETTLE_COMP_OFF;
pr_debug("%s: %s event = %d\n", __func__, w->name, event);
if (w->shift == 5) {
e_pre_on = WCD9XXX_EVENT_PRE_HPHL_PA_ON;
e_post_off = WCD9XXX_EVENT_POST_HPHL_PA_OFF;
req_clsh_state = WCD9XXX_CLSH_STATE_HPHL;
} else if (w->shift == 4) {
e_pre_on = WCD9XXX_EVENT_PRE_HPHR_PA_ON;
e_post_off = WCD9XXX_EVENT_POST_HPHR_PA_OFF;
req_clsh_state = WCD9XXX_CLSH_STATE_HPHR;
} else {
pr_err("%s: Invalid w->shift %d\n", __func__, w->shift);
return -EINVAL;
}
if (tomtom->comp_enabled[COMPANDER_1])
pa_settle_time = TOMTOM_HPH_PA_SETTLE_COMP_ON;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
/* Let MBHC module know PA is turning on */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_pre_on);
break;
case SND_SOC_DAPM_POST_PMU:
usleep_range(pa_settle_time, pa_settle_time + 1000);
pr_debug("%s: sleep %d us after %s PA enable\n", __func__,
pa_settle_time, w->name);
if (!high_perf_mode && !tomtom->uhqa_mode) {
wcd9xxx_clsh_fsm(codec, &tomtom->clsh_d,
req_clsh_state,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
}
break;
case SND_SOC_DAPM_POST_PMD:
/* Let MBHC module know PA turned off */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr, e_post_off);
usleep_range(pa_settle_time, pa_settle_time + 1000);
pr_debug("%s: sleep %d us after %s PA disable\n", __func__,
pa_settle_time, w->name);
break;
}
return 0;
}
static int tomtom_codec_enable_anc_hph(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
int ret = 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
ret = tomtom_hph_pa_event(w, kcontrol, event);
break;
case SND_SOC_DAPM_POST_PMU:
if ((snd_soc_read(codec, TOMTOM_A_RX_HPH_L_DAC_CTL) & 0x80) &&
(snd_soc_read(codec, TOMTOM_A_RX_HPH_R_DAC_CTL)
& 0x80)) {
snd_soc_update_bits(codec,
TOMTOM_A_RX_HPH_CNP_EN, 0x30, 0x30);
msleep(30);
}
ret = tomtom_hph_pa_event(w, kcontrol, event);
break;
case SND_SOC_DAPM_PRE_PMD:
if (w->shift == 5) {
snd_soc_update_bits(codec,
TOMTOM_A_RX_HPH_CNP_EN, 0x30, 0x00);
msleep(40);
snd_soc_update_bits(codec,
TOMTOM_A_TX_7_MBHC_EN, 0x80, 00);
ret |= tomtom_codec_enable_anc(w, kcontrol, event);
}
break;
case SND_SOC_DAPM_POST_PMD:
ret = tomtom_hph_pa_event(w, kcontrol, event);
break;
}
return ret;
}
static const struct snd_soc_dapm_widget tomtom_dapm_i2s_widgets[] = {
SND_SOC_DAPM_SUPPLY("RX_I2S_CLK", TOMTOM_A_CDC_CLK_RX_I2S_CTL,
4, 0, NULL, 0),
SND_SOC_DAPM_SUPPLY("TX_I2S_CLK", TOMTOM_A_CDC_CLK_TX_I2S_CTL, 4,
0, NULL, 0),
};
static int tomtom_lineout_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
wcd9xxx_clsh_fsm(codec, &tomtom->clsh_d,
WCD9XXX_CLSH_STATE_LO,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
snd_soc_update_bits(codec, w->reg, 0x40, 0x40);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, w->reg, 0x40, 0x00);
wcd9xxx_clsh_fsm(codec, &tomtom->clsh_d,
WCD9XXX_CLSH_STATE_LO,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
break;
}
return 0;
}
static int tomtom_spk_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
snd_soc_update_bits(codec, WCD9XXX_A_CDC_CLK_OTHR_CTL,
0x80, 0x80);
break;
case SND_SOC_DAPM_POST_PMD:
if ((snd_soc_read(codec, w->reg) & 0x03) == 0)
snd_soc_update_bits(codec, WCD9XXX_A_CDC_CLK_OTHR_CTL,
0x80, 0x00);
break;
}
return 0;
}
static const struct snd_soc_dapm_route audio_i2s_map[] = {
{"SLIM RX1", NULL, "RX_I2S_CLK"},
{"SLIM RX2", NULL, "RX_I2S_CLK"},
{"SLIM RX3", NULL, "RX_I2S_CLK"},
{"SLIM RX4", NULL, "RX_I2S_CLK"},
{"SLIM TX7 MUX", NULL, "TX_I2S_CLK"},
{"SLIM TX8 MUX", NULL, "TX_I2S_CLK"},
{"SLIM TX9 MUX", NULL, "TX_I2S_CLK"},
{"SLIM TX10 MUX", NULL, "TX_I2S_CLK"},
{"RX_I2S_CLK", NULL, "CDC_I2S_RX_CONN"},
};
static const struct snd_soc_dapm_route audio_map[] = {
/* SLIMBUS Connections */
{"AIF1 CAP", NULL, "AIF1_CAP Mixer"},
{"AIF2 CAP", NULL, "AIF2_CAP Mixer"},
{"AIF3 CAP", NULL, "AIF3_CAP Mixer"},
/* VI Feedback */
{"AIF4_VI Mixer", "SPKR_VI_1", "VIINPUT"},
{"AIF4_VI Mixer", "SPKR_VI_2", "VIINPUT"},
{"AIF4 VI", NULL, "AIF4_VI Mixer"},
/* MAD */
{"MAD_SEL MUX", "SPE", "MAD_CPE_INPUT"},
{"MAD_SEL MUX", "MSM", "MADINPUT"},
{"MADONOFF", "Switch", "MAD_SEL MUX"},
{"AIF4 MAD", NULL, "MADONOFF"},
/* SLIM_MIXER("AIF1_CAP Mixer"),*/
{"AIF1_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF1_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF1_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF1_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF1_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"AIF1_CAP Mixer", "SLIM TX6", "SLIM TX6 MUX"},
{"AIF1_CAP Mixer", "SLIM TX7", "SLIM TX7 MUX"},
{"AIF1_CAP Mixer", "SLIM TX8", "SLIM TX8 MUX"},
{"AIF1_CAP Mixer", "SLIM TX9", "SLIM TX9 MUX"},
{"AIF1_CAP Mixer", "SLIM TX10", "SLIM TX10 MUX"},
/* SLIM_MIXER("AIF2_CAP Mixer"),*/
{"AIF2_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF2_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF2_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF2_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF2_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"AIF2_CAP Mixer", "SLIM TX6", "SLIM TX6 MUX"},
{"AIF2_CAP Mixer", "SLIM TX7", "SLIM TX7 MUX"},
{"AIF2_CAP Mixer", "SLIM TX8", "SLIM TX8 MUX"},
{"AIF2_CAP Mixer", "SLIM TX9", "SLIM TX9 MUX"},
{"AIF2_CAP Mixer", "SLIM TX10", "SLIM TX10 MUX"},
/* SLIM_MIXER("AIF3_CAP Mixer"),*/
{"AIF3_CAP Mixer", "SLIM TX1", "SLIM TX1 MUX"},
{"AIF3_CAP Mixer", "SLIM TX2", "SLIM TX2 MUX"},
{"AIF3_CAP Mixer", "SLIM TX3", "SLIM TX3 MUX"},
{"AIF3_CAP Mixer", "SLIM TX4", "SLIM TX4 MUX"},
{"AIF3_CAP Mixer", "SLIM TX5", "SLIM TX5 MUX"},
{"AIF3_CAP Mixer", "SLIM TX6", "SLIM TX6 MUX"},
{"AIF3_CAP Mixer", "SLIM TX7", "SLIM TX7 MUX"},
{"AIF3_CAP Mixer", "SLIM TX8", "SLIM TX8 MUX"},
{"AIF3_CAP Mixer", "SLIM TX9", "SLIM TX9 MUX"},
{"AIF3_CAP Mixer", "SLIM TX10", "SLIM TX10 MUX"},
{"SLIM TX1 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX1 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX1 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX1 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX1 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX1 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX1 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX1 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX1 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX2 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX2 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX2 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX2 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX2 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX2 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX2 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX2 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX2 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX3 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX3 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX3 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX3 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX3 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX3 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX3 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX3 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX3 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX4 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX4 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX4 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX4 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX4 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX4 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX4 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX4 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX4 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX5 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX5 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX5 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX5 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX5 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX5 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX5 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX5 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX5 MUX", "RMIX8", "RX8 MIX1"},
{"SLIM TX6 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX7 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX7 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX7 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX7 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX7 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX7 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX7 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX7 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX7 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX7 MUX", "DEC10", "DEC10 MUX"},
{"SLIM TX7 MUX", "RMIX1", "RX1 MIX1"},
{"SLIM TX7 MUX", "RMIX2", "RX2 MIX1"},
{"SLIM TX7 MUX", "RMIX3", "RX3 MIX1"},
{"SLIM TX7 MUX", "RMIX4", "RX4 MIX1"},
{"SLIM TX7 MUX", "RMIX5", "RX5 MIX1"},
{"SLIM TX7 MUX", "RMIX6", "RX6 MIX1"},
{"SLIM TX7 MUX", "RMIX7", "RX7 MIX1"},
{"SLIM TX8 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX8 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX8 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX8 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX8 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX8 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX8 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX8 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX8 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX8 MUX", "DEC10", "DEC10 MUX"},
{"SLIM TX9 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX9 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX9 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX9 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX9 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX9 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX9 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX9 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX9 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX9 MUX", "DEC10", "DEC10 MUX"},
{"SLIM TX10 MUX", "DEC1", "DEC1 MUX"},
{"SLIM TX10 MUX", "DEC2", "DEC2 MUX"},
{"SLIM TX10 MUX", "DEC3", "DEC3 MUX"},
{"SLIM TX10 MUX", "DEC4", "DEC4 MUX"},
{"SLIM TX10 MUX", "DEC5", "DEC5 MUX"},
{"SLIM TX10 MUX", "DEC6", "DEC6 MUX"},
{"SLIM TX10 MUX", "DEC7", "DEC7 MUX"},
{"SLIM TX10 MUX", "DEC8", "DEC8 MUX"},
{"SLIM TX10 MUX", "DEC9", "DEC9 MUX"},
{"SLIM TX10 MUX", "DEC10", "DEC10 MUX"},
/* Earpiece (RX MIX1) */
{"EAR", NULL, "EAR PA"},
{"EAR PA", NULL, "EAR_PA_MIXER"},
{"EAR_PA_MIXER", NULL, "DAC1"},
{"DAC1", NULL, "RX_BIAS"},
{"ANC EAR", NULL, "ANC EAR PA"},
{"ANC EAR PA", NULL, "EAR_PA_MIXER"},
{"ANC1 FB MUX", "EAR_HPH_L", "RX1 MIX2"},
{"ANC1 FB MUX", "EAR_LINE_1", "RX2 MIX2"},
/* Headset (RX MIX1 and RX MIX2) */
{"HEADPHONE", NULL, "HPHL"},
{"HEADPHONE", NULL, "HPHR"},
{"HPHL", NULL, "HPHL_PA_MIXER"},
{"HPHL_PA_MIXER", NULL, "HPHL DAC"},
{"HPHL DAC", NULL, "RX_BIAS"},
{"HPHR", NULL, "HPHR_PA_MIXER"},
{"HPHR_PA_MIXER", NULL, "HPHR DAC"},
{"HPHR DAC", NULL, "RX_BIAS"},
{"ANC HEADPHONE", NULL, "ANC HPHL"},
{"ANC HEADPHONE", NULL, "ANC HPHR"},
{"ANC HPHL", NULL, "HPHL_PA_MIXER"},
{"ANC HPHR", NULL, "HPHR_PA_MIXER"},
{"ANC1 MUX", "ADC1", "ADC1"},
{"ANC1 MUX", "ADC2", "ADC2"},
{"ANC1 MUX", "ADC3", "ADC3"},
{"ANC1 MUX", "ADC4", "ADC4"},
{"ANC1 MUX", "ADC5", "ADC5"},
{"ANC1 MUX", "ADC6", "ADC6"},
{"ANC1 MUX", "DMIC1", "DMIC1"},
{"ANC1 MUX", "DMIC2", "DMIC2"},
{"ANC1 MUX", "DMIC3", "DMIC3"},
{"ANC1 MUX", "DMIC4", "DMIC4"},
{"ANC1 MUX", "DMIC5", "DMIC5"},
{"ANC1 MUX", "DMIC6", "DMIC6"},
{"ANC2 MUX", "ADC1", "ADC1"},
{"ANC2 MUX", "ADC2", "ADC2"},
{"ANC2 MUX", "ADC3", "ADC3"},
{"ANC2 MUX", "ADC4", "ADC4"},
{"ANC2 MUX", "ADC5", "ADC5"},
{"ANC2 MUX", "ADC6", "ADC6"},
{"ANC2 MUX", "DMIC1", "DMIC1"},
{"ANC2 MUX", "DMIC2", "DMIC2"},
{"ANC2 MUX", "DMIC3", "DMIC3"},
{"ANC2 MUX", "DMIC4", "DMIC4"},
{"ANC2 MUX", "DMIC5", "DMIC5"},
{"ANC2 MUX", "DMIC6", "DMIC6"},
{"ANC HPHR", NULL, "CDC_CONN"},
{"DAC1", "Switch", "CLASS_H_DSM MUX"},
{"HPHL DAC", "Switch", "CLASS_H_DSM MUX"},
{"HPHR DAC", NULL, "RX2 CHAIN"},
{"LINEOUT1", NULL, "LINEOUT1 PA"},
{"LINEOUT2", NULL, "LINEOUT2 PA"},
{"LINEOUT3", NULL, "LINEOUT3 PA"},
{"LINEOUT4", NULL, "LINEOUT4 PA"},
{"SPK_OUT", NULL, "SPK PA"},
{"SPK_OUT", NULL, "SPK2 PA"},
{"LINEOUT1 PA", NULL, "LINEOUT1_PA_MIXER"},
{"LINEOUT1_PA_MIXER", NULL, "LINEOUT1 DAC"},
{"LINEOUT2 PA", NULL, "LINEOUT2_PA_MIXER"},
{"LINEOUT2_PA_MIXER", NULL, "LINEOUT2 DAC"},
{"LINEOUT3 PA", NULL, "LINEOUT3_PA_MIXER"},
{"LINEOUT3_PA_MIXER", NULL, "LINEOUT3 DAC"},
{"LINEOUT4 PA", NULL, "LINEOUT4_PA_MIXER"},
{"LINEOUT4_PA_MIXER", NULL, "LINEOUT4 DAC"},
{"LINEOUT1 DAC", NULL, "RX3 MIX1"},
{"RDAC5 MUX", "DEM3_INV", "RX3 MIX1"},
{"RDAC5 MUX", "DEM4", "RX4 MIX1"},
{"LINEOUT3 DAC", NULL, "RDAC5 MUX"},
{"LINEOUT2 DAC", NULL, "RX5 MIX1"},
{"RDAC7 MUX", "DEM5_INV", "RX5 MIX1"},
{"RDAC7 MUX", "DEM6", "RX6 MIX1"},
{"LINEOUT4 DAC", NULL, "RDAC7 MUX"},
{"SPK PA", NULL, "SPK DAC"},
{"SPK DAC", NULL, "RX7 MIX2"},
{"SPK DAC", NULL, "VDD_SPKDRV"},
{"SPK2 PA", NULL, "SPK2 DAC"},
{"SPK2 DAC", NULL, "RX8 MIX1"},
{"SPK2 DAC", NULL, "VDD_SPKDRV2"},
{"CLASS_H_DSM MUX", "DSM_HPHL_RX1", "RX1 CHAIN"},
{"RX1 INTERP", NULL, "RX1 MIX2"},
{"RX1 CHAIN", NULL, "RX1 INTERP"},
{"RX2 INTERP", NULL, "RX2 MIX2"},
{"RX2 CHAIN", NULL, "RX2 INTERP"},
{"RX1 MIX2", NULL, "ANC1 MUX"},
{"RX2 MIX2", NULL, "ANC2 MUX"},
{"LINEOUT1 DAC", NULL, "RX_BIAS"},
{"LINEOUT2 DAC", NULL, "RX_BIAS"},
{"LINEOUT3 DAC", NULL, "RX_BIAS"},
{"LINEOUT4 DAC", NULL, "RX_BIAS"},
{"SPK DAC", NULL, "RX_BIAS"},
{"SPK2 DAC", NULL, "RX_BIAS"},
{"RX7 MIX1", NULL, "COMP0_CLK"},
{"RX8 MIX1", NULL, "COMP0_CLK"},
{"RX1 MIX1", NULL, "COMP1_CLK"},
{"RX2 MIX1", NULL, "COMP1_CLK"},
{"RX3 MIX1", NULL, "COMP2_CLK"},
{"RX5 MIX1", NULL, "COMP2_CLK"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP1"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP2"},
{"RX1 MIX1", NULL, "RX1 MIX1 INP3"},
{"RX2 MIX1", NULL, "RX2 MIX1 INP1"},
{"RX2 MIX1", NULL, "RX2 MIX1 INP2"},
{"RX3 MIX1", NULL, "RX3 MIX1 INP1"},
{"RX3 MIX1", NULL, "RX3 MIX1 INP2"},
{"RX4 MIX1", NULL, "RX4 MIX1 INP1"},
{"RX4 MIX1", NULL, "RX4 MIX1 INP2"},
{"RX5 MIX1", NULL, "RX5 MIX1 INP1"},
{"RX5 MIX1", NULL, "RX5 MIX1 INP2"},
{"RX6 MIX1", NULL, "RX6 MIX1 INP1"},
{"RX6 MIX1", NULL, "RX6 MIX1 INP2"},
{"RX7 MIX1", NULL, "RX7 MIX1 INP1"},
{"RX7 MIX1", NULL, "RX7 MIX1 INP2"},
{"RX8 MIX1", NULL, "RX8 MIX1 INP1"},
{"RX8 MIX1", NULL, "RX8 MIX1 INP2"},
{"RX1 MIX2", NULL, "RX1 MIX1"},
{"RX1 MIX2", NULL, "RX1 MIX2 INP1"},
{"RX1 MIX2", NULL, "RX1 MIX2 INP2"},
{"RX2 MIX2", NULL, "RX2 MIX1"},
{"RX2 MIX2", NULL, "RX2 MIX2 INP1"},
{"RX2 MIX2", NULL, "RX2 MIX2 INP2"},
{"RX7 MIX2", NULL, "RX7 MIX1"},
{"RX7 MIX2", NULL, "RX7 MIX2 INP1"},
{"RX7 MIX2", NULL, "RX7 MIX2 INP2"},
/* SLIM_MUX("AIF1_PB", "AIF1 PB"),*/
{"SLIM RX1 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX2 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX3 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX4 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX5 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX6 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX7 MUX", "AIF1_PB", "AIF1 PB"},
{"SLIM RX8 MUX", "AIF1_PB", "AIF1 PB"},
/* SLIM_MUX("AIF2_PB", "AIF2 PB"),*/
{"SLIM RX1 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX2 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX3 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX4 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX5 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX6 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX7 MUX", "AIF2_PB", "AIF2 PB"},
{"SLIM RX8 MUX", "AIF2_PB", "AIF2 PB"},
/* SLIM_MUX("AIF3_PB", "AIF3 PB"),*/
{"SLIM RX1 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX2 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX3 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX4 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX5 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX6 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX7 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX8 MUX", "AIF3_PB", "AIF3 PB"},
{"SLIM RX1", NULL, "SLIM RX1 MUX"},
{"SLIM RX2", NULL, "SLIM RX2 MUX"},
{"SLIM RX3", NULL, "SLIM RX3 MUX"},
{"SLIM RX4", NULL, "SLIM RX4 MUX"},
{"SLIM RX5", NULL, "SLIM RX5 MUX"},
{"SLIM RX6", NULL, "SLIM RX6 MUX"},
{"SLIM RX7", NULL, "SLIM RX7 MUX"},
{"SLIM RX8", NULL, "SLIM RX8 MUX"},
{"RX1 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX1 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX1 MIX1 INP1", "IIR1", "IIR1"},
{"RX1 MIX1 INP1", "IIR2", "IIR2"},
{"RX1 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX1 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX1 MIX1 INP2", "IIR1", "IIR1"},
{"RX1 MIX1 INP2", "IIR2", "IIR2"},
{"RX1 MIX1 INP3", "RX1", "SLIM RX1"},
{"RX1 MIX1 INP3", "RX2", "SLIM RX2"},
{"RX1 MIX1 INP3", "RX3", "SLIM RX3"},
{"RX1 MIX1 INP3", "RX4", "SLIM RX4"},
{"RX1 MIX1 INP3", "RX5", "SLIM RX5"},
{"RX1 MIX1 INP3", "RX6", "SLIM RX6"},
{"RX1 MIX1 INP3", "RX7", "SLIM RX7"},
{"RX2 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX2 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX2 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX2 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX2 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX2 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX2 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX2 MIX1 INP1", "IIR1", "IIR1"},
{"RX2 MIX1 INP1", "IIR2", "IIR2"},
{"RX2 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX2 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX2 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX2 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX2 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX2 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX2 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX2 MIX1 INP2", "IIR1", "IIR1"},
{"RX2 MIX1 INP2", "IIR2", "IIR2"},
{"RX3 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX3 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX3 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX3 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX3 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX3 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX3 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX3 MIX1 INP1", "IIR1", "IIR1"},
{"RX3 MIX1 INP1", "IIR2", "IIR2"},
{"RX3 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX3 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX3 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX3 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX3 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX3 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX3 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX3 MIX1 INP2", "IIR1", "IIR1"},
{"RX3 MIX1 INP2", "IIR2", "IIR2"},
{"RX4 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX4 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX4 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX4 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX4 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX4 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX4 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX4 MIX1 INP1", "IIR1", "IIR1"},
{"RX4 MIX1 INP1", "IIR2", "IIR2"},
{"RX4 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX4 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX4 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX4 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX4 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX4 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX4 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX4 MIX1 INP2", "IIR1", "IIR1"},
{"RX4 MIX1 INP2", "IIR2", "IIR2"},
{"RX5 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX5 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX5 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX5 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX5 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX5 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX5 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX5 MIX1 INP1", "IIR1", "IIR1"},
{"RX5 MIX1 INP1", "IIR2", "IIR2"},
{"RX5 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX5 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX5 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX5 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX5 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX5 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX5 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX5 MIX1 INP2", "IIR1", "IIR1"},
{"RX5 MIX1 INP2", "IIR2", "IIR2"},
{"RX6 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX6 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX6 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX6 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX6 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX6 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX6 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX6 MIX1 INP1", "IIR1", "IIR1"},
{"RX6 MIX1 INP1", "IIR2", "IIR2"},
{"RX6 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX6 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX6 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX6 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX6 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX6 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX6 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX6 MIX1 INP2", "IIR1", "IIR1"},
{"RX6 MIX1 INP2", "IIR2", "IIR2"},
{"RX7 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX7 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX7 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX7 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX7 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX7 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX7 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX7 MIX1 INP1", "IIR1", "IIR1"},
{"RX7 MIX1 INP1", "IIR2", "IIR2"},
{"RX7 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX7 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX7 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX7 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX7 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX7 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX7 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX7 MIX1 INP2", "IIR1", "IIR1"},
{"RX7 MIX1 INP2", "IIR2", "IIR2"},
{"RX8 MIX1 INP1", "RX1", "SLIM RX1"},
{"RX8 MIX1 INP1", "RX2", "SLIM RX2"},
{"RX8 MIX1 INP1", "RX3", "SLIM RX3"},
{"RX8 MIX1 INP1", "RX4", "SLIM RX4"},
{"RX8 MIX1 INP1", "RX5", "SLIM RX5"},
{"RX8 MIX1 INP1", "RX6", "SLIM RX6"},
{"RX8 MIX1 INP1", "RX7", "SLIM RX7"},
{"RX8 MIX1 INP1", "RX8", "SLIM RX8"},
{"RX8 MIX1 INP1", "IIR1", "IIR1"},
{"RX8 MIX1 INP1", "IIR2", "IIR2"},
{"RX8 MIX1 INP2", "RX1", "SLIM RX1"},
{"RX8 MIX1 INP2", "RX2", "SLIM RX2"},
{"RX8 MIX1 INP2", "RX3", "SLIM RX3"},
{"RX8 MIX1 INP2", "RX4", "SLIM RX4"},
{"RX8 MIX1 INP2", "RX5", "SLIM RX5"},
{"RX8 MIX1 INP2", "RX6", "SLIM RX6"},
{"RX8 MIX1 INP2", "RX7", "SLIM RX7"},
{"RX8 MIX1 INP2", "RX8", "SLIM RX8"},
{"RX8 MIX1 INP2", "IIR1", "IIR1"},
{"RX8 MIX1 INP2", "IIR2", "IIR2"},
/* IIR1, IIR2 inputs to Second RX Mixer on RX1, RX2 and RX7 chains. */
{"RX1 MIX2 INP1", "IIR1", "IIR1"},
{"RX1 MIX2 INP2", "IIR1", "IIR1"},
{"RX2 MIX2 INP1", "IIR1", "IIR1"},
{"RX2 MIX2 INP2", "IIR1", "IIR1"},
{"RX7 MIX2 INP1", "IIR1", "IIR1"},
{"RX7 MIX2 INP2", "IIR1", "IIR1"},
{"RX1 MIX2 INP1", "IIR2", "IIR2"},
{"RX1 MIX2 INP2", "IIR2", "IIR2"},
{"RX2 MIX2 INP1", "IIR2", "IIR2"},
{"RX2 MIX2 INP2", "IIR2", "IIR2"},
{"RX7 MIX2 INP1", "IIR2", "IIR2"},
{"RX7 MIX2 INP2", "IIR2", "IIR2"},
/* Decimator Inputs */
{"DEC1 MUX", "DMIC1", "DMIC1"},
{"DEC1 MUX", "ADC6", "ADC6"},
{"DEC1 MUX", NULL, "CDC_CONN"},
{"DEC2 MUX", "DMIC2", "DMIC2"},
{"DEC2 MUX", "ADC5", "ADC5"},
{"DEC2 MUX", NULL, "CDC_CONN"},
{"DEC3 MUX", "DMIC3", "DMIC3"},
{"DEC3 MUX", "ADC4", "ADC4"},
{"DEC3 MUX", NULL, "CDC_CONN"},
{"DEC4 MUX", "DMIC4", "DMIC4"},
{"DEC4 MUX", "ADC3", "ADC3"},
{"DEC4 MUX", NULL, "CDC_CONN"},
{"DEC5 MUX", "DMIC5", "DMIC5"},
{"DEC5 MUX", "ADC2", "ADC2"},
{"DEC5 MUX", NULL, "CDC_CONN"},
{"DEC6 MUX", "DMIC6", "DMIC6"},
{"DEC6 MUX", "ADC1", "ADC1"},
{"DEC6 MUX", NULL, "CDC_CONN"},
{"DEC7 MUX", "DMIC1", "DMIC1"},
{"DEC7 MUX", "DMIC6", "DMIC6"},
{"DEC7 MUX", "ADC1", "ADC1"},
{"DEC7 MUX", "ADC6", "ADC6"},
{"DEC7 MUX", "ANC1_FB", "ANC1 MUX"},
{"DEC7 MUX", "ANC2_FB", "ANC2 MUX"},
{"DEC7 MUX", NULL, "CDC_CONN"},
{"DEC8 MUX", "DMIC2", "DMIC2"},
{"DEC8 MUX", "DMIC5", "DMIC5"},
{"DEC8 MUX", "ADC2", "ADC2"},
{"DEC8 MUX", "ADC5", "ADC5"},
{"DEC8 MUX", "ANC1_FB", "ANC1 MUX"},
{"DEC8 MUX", "ANC2_FB", "ANC2 MUX"},
{"DEC8 MUX", NULL, "CDC_CONN"},
{"DEC9 MUX", "DMIC4", "DMIC4"},
{"DEC9 MUX", "DMIC5", "DMIC5"},
{"DEC9 MUX", "ADC2", "ADC2"},
{"DEC9 MUX", "ADC3", "ADC3"},
{"DEC9 MUX", "ANC1_FB", "ANC1 MUX"},
{"DEC9 MUX", "ANC2_FB", "ANC2 MUX"},
{"DEC9 MUX", NULL, "CDC_CONN"},
{"DEC10 MUX", "DMIC3", "DMIC3"},
{"DEC10 MUX", "DMIC6", "DMIC6"},
{"DEC10 MUX", "ADC1", "ADC1"},
{"DEC10 MUX", "ADC4", "ADC4"},
{"DEC10 MUX", "ANC1_FB", "ANC1 MUX"},
{"DEC10 MUX", "ANC2_FB", "ANC2 MUX"},
{"DEC10 MUX", NULL, "CDC_CONN"},
/* ADC Connections */
{"ADC1", NULL, "AMIC1"},
{"ADC2", NULL, "AMIC2"},
{"ADC3", NULL, "AMIC3"},
{"ADC4", NULL, "AMIC4"},
{"ADC5", NULL, "AMIC5"},
{"ADC6", NULL, "AMIC6"},
/* AUX PGA Connections */
{"EAR_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"HPHL_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"HPHR_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT1_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT2_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"LINEOUT3_PA_MIXER", "AUX_PGA_L Switch", "AUX_PGA_Left"},
{"LINEOUT4_PA_MIXER", "AUX_PGA_R Switch", "AUX_PGA_Right"},
{"AUX_PGA_Left", NULL, "AMIC5"},
{"AUX_PGA_Right", NULL, "AMIC6"},
{"IIR1", NULL, "IIR1 INP1 MUX"},
{"IIR1 INP1 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP1 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP1 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP1 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP1 MUX", "DEC5", "DEC5 MUX"},
{"IIR1 INP1 MUX", "DEC6", "DEC6 MUX"},
{"IIR1 INP1 MUX", "DEC7", "DEC7 MUX"},
{"IIR1 INP1 MUX", "DEC8", "DEC8 MUX"},
{"IIR1 INP1 MUX", "DEC9", "DEC9 MUX"},
{"IIR1 INP1 MUX", "DEC10", "DEC10 MUX"},
{"IIR1 INP1 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP1 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP1 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP1 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP1 MUX", "RX5", "SLIM RX5"},
{"IIR1 INP1 MUX", "RX6", "SLIM RX6"},
{"IIR1 INP1 MUX", "RX7", "SLIM RX7"},
{"IIR2", NULL, "IIR2 INP1 MUX"},
{"IIR2 INP1 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP1 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP1 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP1 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP1 MUX", "DEC5", "DEC5 MUX"},
{"IIR2 INP1 MUX", "DEC6", "DEC6 MUX"},
{"IIR2 INP1 MUX", "DEC7", "DEC7 MUX"},
{"IIR2 INP1 MUX", "DEC8", "DEC8 MUX"},
{"IIR2 INP1 MUX", "DEC9", "DEC9 MUX"},
{"IIR2 INP1 MUX", "DEC10", "DEC10 MUX"},
{"IIR2 INP1 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP1 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP1 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP1 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP1 MUX", "RX5", "SLIM RX5"},
{"IIR2 INP1 MUX", "RX6", "SLIM RX6"},
{"IIR2 INP1 MUX", "RX7", "SLIM RX7"},
{"IIR1", NULL, "IIR1 INP2 MUX"},
{"IIR1 INP2 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP2 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP2 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP2 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP2 MUX", "DEC5", "DEC5 MUX"},
{"IIR1 INP2 MUX", "DEC6", "DEC6 MUX"},
{"IIR1 INP2 MUX", "DEC7", "DEC7 MUX"},
{"IIR1 INP2 MUX", "DEC8", "DEC8 MUX"},
{"IIR1 INP2 MUX", "DEC9", "DEC9 MUX"},
{"IIR1 INP2 MUX", "DEC10", "DEC10 MUX"},
{"IIR1 INP2 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP2 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP2 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP2 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP2 MUX", "RX5", "SLIM RX5"},
{"IIR1 INP2 MUX", "RX6", "SLIM RX6"},
{"IIR1 INP2 MUX", "RX7", "SLIM RX7"},
{"IIR2", NULL, "IIR2 INP2 MUX"},
{"IIR2 INP2 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP2 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP2 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP2 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP2 MUX", "DEC5", "DEC5 MUX"},
{"IIR2 INP2 MUX", "DEC6", "DEC6 MUX"},
{"IIR2 INP2 MUX", "DEC7", "DEC7 MUX"},
{"IIR2 INP2 MUX", "DEC8", "DEC8 MUX"},
{"IIR2 INP2 MUX", "DEC9", "DEC9 MUX"},
{"IIR2 INP2 MUX", "DEC10", "DEC10 MUX"},
{"IIR2 INP2 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP2 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP2 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP2 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP2 MUX", "RX5", "SLIM RX5"},
{"IIR2 INP2 MUX", "RX6", "SLIM RX6"},
{"IIR2 INP2 MUX", "RX7", "SLIM RX7"},
{"IIR1", NULL, "IIR1 INP3 MUX"},
{"IIR1 INP3 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP3 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP3 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP3 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP3 MUX", "DEC5", "DEC5 MUX"},
{"IIR1 INP3 MUX", "DEC6", "DEC6 MUX"},
{"IIR1 INP3 MUX", "DEC7", "DEC7 MUX"},
{"IIR1 INP3 MUX", "DEC8", "DEC8 MUX"},
{"IIR1 INP3 MUX", "DEC9", "DEC9 MUX"},
{"IIR1 INP3 MUX", "DEC10", "DEC10 MUX"},
{"IIR1 INP3 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP3 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP3 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP3 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP3 MUX", "RX5", "SLIM RX5"},
{"IIR1 INP3 MUX", "RX6", "SLIM RX6"},
{"IIR1 INP3 MUX", "RX7", "SLIM RX7"},
{"IIR2", NULL, "IIR2 INP3 MUX"},
{"IIR2 INP3 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP3 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP3 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP3 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP3 MUX", "DEC5", "DEC5 MUX"},
{"IIR2 INP3 MUX", "DEC6", "DEC6 MUX"},
{"IIR2 INP3 MUX", "DEC7", "DEC7 MUX"},
{"IIR2 INP3 MUX", "DEC8", "DEC8 MUX"},
{"IIR2 INP3 MUX", "DEC9", "DEC9 MUX"},
{"IIR2 INP3 MUX", "DEC10", "DEC10 MUX"},
{"IIR2 INP3 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP3 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP3 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP3 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP3 MUX", "RX5", "SLIM RX5"},
{"IIR2 INP3 MUX", "RX6", "SLIM RX6"},
{"IIR2 INP3 MUX", "RX7", "SLIM RX7"},
{"IIR1", NULL, "IIR1 INP4 MUX"},
{"IIR1 INP4 MUX", "DEC1", "DEC1 MUX"},
{"IIR1 INP4 MUX", "DEC2", "DEC2 MUX"},
{"IIR1 INP4 MUX", "DEC3", "DEC3 MUX"},
{"IIR1 INP4 MUX", "DEC4", "DEC4 MUX"},
{"IIR1 INP4 MUX", "DEC5", "DEC5 MUX"},
{"IIR1 INP4 MUX", "DEC6", "DEC6 MUX"},
{"IIR1 INP4 MUX", "DEC7", "DEC7 MUX"},
{"IIR1 INP4 MUX", "DEC8", "DEC8 MUX"},
{"IIR1 INP4 MUX", "DEC9", "DEC9 MUX"},
{"IIR1 INP4 MUX", "DEC10", "DEC10 MUX"},
{"IIR1 INP4 MUX", "RX1", "SLIM RX1"},
{"IIR1 INP4 MUX", "RX2", "SLIM RX2"},
{"IIR1 INP4 MUX", "RX3", "SLIM RX3"},
{"IIR1 INP4 MUX", "RX4", "SLIM RX4"},
{"IIR1 INP4 MUX", "RX5", "SLIM RX5"},
{"IIR1 INP4 MUX", "RX6", "SLIM RX6"},
{"IIR1 INP4 MUX", "RX7", "SLIM RX7"},
{"IIR2", NULL, "IIR2 INP4 MUX"},
{"IIR2 INP4 MUX", "DEC1", "DEC1 MUX"},
{"IIR2 INP4 MUX", "DEC2", "DEC2 MUX"},
{"IIR2 INP4 MUX", "DEC3", "DEC3 MUX"},
{"IIR2 INP4 MUX", "DEC4", "DEC4 MUX"},
{"IIR2 INP4 MUX", "DEC5", "DEC5 MUX"},
{"IIR2 INP4 MUX", "DEC6", "DEC6 MUX"},
{"IIR2 INP4 MUX", "DEC7", "DEC7 MUX"},
{"IIR2 INP4 MUX", "DEC8", "DEC8 MUX"},
{"IIR2 INP4 MUX", "DEC9", "DEC9 MUX"},
{"IIR2 INP4 MUX", "DEC10", "DEC10 MUX"},
{"IIR2 INP4 MUX", "RX1", "SLIM RX1"},
{"IIR2 INP4 MUX", "RX2", "SLIM RX2"},
{"IIR2 INP4 MUX", "RX3", "SLIM RX3"},
{"IIR2 INP4 MUX", "RX4", "SLIM RX4"},
{"IIR2 INP4 MUX", "RX5", "SLIM RX5"},
{"IIR2 INP4 MUX", "RX6", "SLIM RX6"},
{"IIR2 INP4 MUX", "RX7", "SLIM RX7"},
{"MIC BIAS1 Internal1", NULL, "LDO_H"},
{"MIC BIAS1 Internal2", NULL, "LDO_H"},
{"MIC BIAS1 External", NULL, "LDO_H"},
{"MIC BIAS2 Internal1", NULL, "LDO_H"},
{"MIC BIAS2 Internal2", NULL, "LDO_H"},
{"MIC BIAS2 Internal3", NULL, "LDO_H"},
{"MIC BIAS2 External", NULL, "LDO_H"},
{"MIC BIAS3 Internal1", NULL, "LDO_H"},
{"MIC BIAS3 Internal2", NULL, "LDO_H"},
{"MIC BIAS3 External", NULL, "LDO_H"},
{"MIC BIAS4 External", NULL, "LDO_H"},
{DAPM_MICBIAS2_EXTERNAL_STANDALONE, NULL, "LDO_H Standalone"},
};
static int tomtom_readable(struct snd_soc_codec *ssc, unsigned int reg)
{
return tomtom_reg_readable[reg];
}
static bool tomtom_is_digital_gain_register(unsigned int reg)
{
bool rtn = false;
switch (reg) {
case TOMTOM_A_CDC_RX1_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX2_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX3_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX4_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX5_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX6_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX7_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_RX8_VOL_CTL_B2_CTL:
case TOMTOM_A_CDC_TX1_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX2_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX3_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX4_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX5_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX6_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX7_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX8_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX9_VOL_CTL_GAIN:
case TOMTOM_A_CDC_TX10_VOL_CTL_GAIN:
rtn = true;
break;
default:
break;
}
return rtn;
}
static int tomtom_volatile(struct snd_soc_codec *ssc, unsigned int reg)
{
int i;
/* Registers lower than 0x100 are top level registers which can be
* written by the TomTom core driver.
*/
if ((reg >= TOMTOM_A_CDC_MBHC_EN_CTL) || (reg < 0x100))
return 1;
if (reg == TOMTOM_A_CDC_CLK_RX_RESET_CTL)
return 1;
/* IIR Coeff registers are not cacheable */
if ((reg >= TOMTOM_A_CDC_IIR1_COEF_B1_CTL) &&
(reg <= TOMTOM_A_CDC_IIR2_COEF_B2_CTL))
return 1;
/* ANC filter registers are not cacheable */
if ((reg >= TOMTOM_A_CDC_ANC1_IIR_B1_CTL) &&
(reg <= TOMTOM_A_CDC_ANC1_LPF_B2_CTL))
return 1;
if ((reg >= TOMTOM_A_CDC_ANC2_IIR_B1_CTL) &&
(reg <= TOMTOM_A_CDC_ANC2_LPF_B2_CTL))
return 1;
/* Digital gain register is not cacheable so we have to write
* the setting even it is the same
*/
if (tomtom_is_digital_gain_register(reg))
return 1;
/* HPH status registers */
if (reg == TOMTOM_A_RX_HPH_L_STATUS || reg == TOMTOM_A_RX_HPH_R_STATUS)
return 1;
if (reg == TOMTOM_A_MBHC_INSERT_DET_STATUS)
return 1;
if (reg == TOMTOM_A_RX_HPH_CNP_EN)
return 1;
if (((reg >= TOMTOM_A_CDC_SPKR_CLIPDET_VAL0 &&
reg <= TOMTOM_A_CDC_SPKR_CLIPDET_VAL7)) ||
((reg >= TOMTOM_A_CDC_SPKR2_CLIPDET_VAL0) &&
(reg <= TOMTOM_A_CDC_SPKR2_CLIPDET_VAL7)))
return 1;
if (reg == TOMTOM_A_CDC_VBAT_GAIN_MON_VAL)
return 1;
for (i = 0; i < ARRAY_SIZE(audio_reg_cfg); i++)
if (audio_reg_cfg[i].reg_logical_addr -
TOMTOM_REGISTER_START_OFFSET == reg)
return 1;
if (reg == TOMTOM_A_SVASS_SPE_INBOX_TRG)
return 1;
if (reg == TOMTOM_A_QFUSE_STATUS)
return 1;
for (i = 0; i < ARRAY_SIZE(non_cacheable_reg); i++)
if (reg == non_cacheable_reg[i])
return 1;
return 0;
}
static int tomtom_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int value)
{
int ret;
struct wcd9xxx *wcd9xxx = codec->control_data;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
if (reg == SND_SOC_NOPM)
return 0;
BUG_ON(reg > TOMTOM_MAX_REGISTER);
if (!tomtom_volatile(codec, reg)) {
ret = snd_soc_cache_write(codec, reg, value);
if (ret != 0)
dev_err(codec->dev, "Cache write to %x failed: %d\n",
reg, ret);
}
if (unlikely(test_bit(BUS_DOWN, &tomtom_p->status_mask))) {
dev_err(codec->dev, "write 0x%02x while offline\n", reg);
return -ENODEV;
} else
return wcd9xxx_reg_write(&wcd9xxx->core_res, reg, value);
}
static unsigned int tomtom_read(struct snd_soc_codec *codec,
unsigned int reg)
{
unsigned int val;
int ret;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx *wcd9xxx = codec->control_data;
if (reg == SND_SOC_NOPM)
return 0;
BUG_ON(reg > TOMTOM_MAX_REGISTER);
if (!tomtom_volatile(codec, reg) && tomtom_readable(codec, reg) &&
reg < codec->driver->reg_cache_size) {
ret = snd_soc_cache_read(codec, reg, &val);
if (ret >= 0) {
return val;
} else
dev_err(codec->dev, "Cache read from %x failed: %d\n",
reg, ret);
}
if (unlikely(test_bit(BUS_DOWN, &tomtom_p->status_mask))) {
dev_err(codec->dev, "read 0x%02x while offline\n", reg);
return -ENODEV;
} else {
val = wcd9xxx_reg_read(&wcd9xxx->core_res, reg);
return val;
}
}
static int tomtom_startup(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
pr_debug("%s(): substream = %s stream = %d\n" , __func__,
substream->name, substream->stream);
return 0;
}
static void tomtom_shutdown(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
pr_debug("%s(): substream = %s stream = %d\n" , __func__,
substream->name, substream->stream);
}
int tomtom_mclk_enable(struct snd_soc_codec *codec, int mclk_enable, bool dapm)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
pr_debug("%s: mclk_enable = %u, dapm = %d\n", __func__, mclk_enable,
dapm);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
if (mclk_enable) {
wcd9xxx_resmgr_get_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
wcd9xxx_resmgr_get_clk_block(&tomtom->resmgr, WCD9XXX_CLK_MCLK);
} else {
/* Put clock and BG */
wcd9xxx_resmgr_put_clk_block(&tomtom->resmgr, WCD9XXX_CLK_MCLK);
wcd9xxx_resmgr_put_bandgap(&tomtom->resmgr,
WCD9XXX_BANDGAP_AUDIO_MODE);
}
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
return 0;
}
static int tomtom_set_dai_sysclk(struct snd_soc_dai *dai,
int clk_id, unsigned int freq, int dir)
{
pr_debug("%s\n", __func__);
return 0;
}
static int tomtom_set_dai_fmt(struct snd_soc_dai *dai, unsigned int fmt)
{
u8 val = 0;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(dai->codec);
pr_debug("%s\n", __func__);
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBS_CFS:
/* CPU is master */
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
if (dai->id == AIF1_CAP)
snd_soc_update_bits(dai->codec,
TOMTOM_A_CDC_CLK_TX_I2S_CTL,
TOMTOM_I2S_MASTER_MODE_MASK, 0);
else if (dai->id == AIF1_PB)
snd_soc_update_bits(dai->codec,
TOMTOM_A_CDC_CLK_RX_I2S_CTL,
TOMTOM_I2S_MASTER_MODE_MASK, 0);
}
break;
case SND_SOC_DAIFMT_CBM_CFM:
/* CPU is slave */
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
val = TOMTOM_I2S_MASTER_MODE_MASK;
if (dai->id == AIF1_CAP)
snd_soc_update_bits(dai->codec,
TOMTOM_A_CDC_CLK_TX_I2S_CTL, val, val);
else if (dai->id == AIF1_PB)
snd_soc_update_bits(dai->codec,
TOMTOM_A_CDC_CLK_RX_I2S_CTL, val, val);
}
break;
default:
return -EINVAL;
}
return 0;
}
static int tomtom_set_channel_map(struct snd_soc_dai *dai,
unsigned int tx_num, unsigned int *tx_slot,
unsigned int rx_num, unsigned int *rx_slot)
{
struct wcd9xxx_codec_dai_data *dai_data = NULL;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(dai->codec);
struct wcd9xxx *core = dev_get_drvdata(dai->codec->dev->parent);
if (!tx_slot || !rx_slot) {
pr_err("%s: Invalid tx_slot=%pK, rx_slot=%pK\n",
__func__, tx_slot, rx_slot);
return -EINVAL;
}
pr_debug("%s(): dai_name = %s DAI-ID %x tx_ch %d rx_ch %d\n"
"tomtom->intf_type %d\n",
__func__, dai->name, dai->id, tx_num, rx_num,
tomtom->intf_type);
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
wcd9xxx_init_slimslave(core, core->slim->laddr,
tx_num, tx_slot, rx_num, rx_slot);
/* Reserve TX13 for MAD data channel */
dai_data = &tomtom->dai[AIF4_MAD_TX];
if (dai_data) {
list_add_tail(&core->tx_chs[TOMTOM_TX13].list,
&dai_data->wcd9xxx_ch_list);
}
}
return 0;
}
static int tomtom_get_channel_map(struct snd_soc_dai *dai,
unsigned int *tx_num, unsigned int *tx_slot,
unsigned int *rx_num, unsigned int *rx_slot)
{
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(dai->codec);
u32 i = 0;
struct wcd9xxx_ch *ch;
switch (dai->id) {
case AIF1_PB:
case AIF2_PB:
case AIF3_PB:
if (!rx_slot || !rx_num) {
pr_err("%s: Invalid rx_slot %pK or rx_num %pK\n",
__func__, rx_slot, rx_num);
return -EINVAL;
}
list_for_each_entry(ch, &tomtom_p->dai[dai->id].wcd9xxx_ch_list,
list) {
pr_debug("%s: slot_num %u ch->ch_num %d\n",
__func__, i, ch->ch_num);
rx_slot[i++] = ch->ch_num;
}
pr_debug("%s: rx_num %d\n", __func__, i);
*rx_num = i;
break;
case AIF1_CAP:
case AIF2_CAP:
case AIF3_CAP:
case AIF4_VIFEED:
case AIF4_MAD_TX:
if (!tx_slot || !tx_num) {
pr_err("%s: Invalid tx_slot %pK or tx_num %pK\n",
__func__, tx_slot, tx_num);
return -EINVAL;
}
list_for_each_entry(ch, &tomtom_p->dai[dai->id].wcd9xxx_ch_list,
list) {
pr_debug("%s: slot_num %u ch->ch_num %d\n",
__func__, i, ch->ch_num);
tx_slot[i++] = ch->ch_num;
}
pr_debug("%s: tx_num %d\n", __func__, i);
*tx_num = i;
break;
default:
pr_err("%s: Invalid DAI ID %x\n", __func__, dai->id);
break;
}
return 0;
}
static int tomtom_set_interpolator_rate(struct snd_soc_dai *dai,
u8 rx_fs_rate_reg_val, u32 compander_fs, u32 sample_rate)
{
u32 j;
u8 rx_mix1_inp, rx8_mix1_inp;
u16 rx_mix_1_reg_1, rx_mix_1_reg_2;
u16 rx_fs_reg;
u8 rx_mix_1_reg_1_val, rx_mix_1_reg_2_val;
struct snd_soc_codec *codec = dai->codec;
struct wcd9xxx_ch *ch;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
int port_rx_8 = TOMTOM_RX_PORT_START_NUMBER + NUM_INTERPOLATORS - 1;
list_for_each_entry(ch, &tomtom->dai[dai->id].wcd9xxx_ch_list, list) {
/* for RX port starting from 16 instead of 10 like tabla */
rx_mix1_inp = ch->port + RX_MIX1_INP_SEL_RX1 -
TOMTOM_TX_PORT_NUMBER;
rx8_mix1_inp = ch->port + RX8_MIX1_INP_SEL_RX1 -
TOMTOM_RX_PORT_START_NUMBER;
if (((ch->port < port_rx_8) &&
((rx_mix1_inp < RX_MIX1_INP_SEL_RX1) ||
(rx_mix1_inp > RX_MIX1_INP_SEL_RX7))) ||
((rx8_mix1_inp < RX8_MIX1_INP_SEL_RX1) ||
(rx8_mix1_inp > RX8_MIX1_INP_SEL_RX8))) {
pr_err("%s: Invalid TOMTOM_RX%u port. Dai ID is %d\n",
__func__, rx8_mix1_inp - 2,
dai->id);
return -EINVAL;
}
rx_mix_1_reg_1 = TOMTOM_A_CDC_CONN_RX1_B1_CTL;
for (j = 0; j < NUM_INTERPOLATORS - 1; j++) {
rx_mix_1_reg_2 = rx_mix_1_reg_1 + 1;
rx_mix_1_reg_1_val = snd_soc_read(codec,
rx_mix_1_reg_1);
rx_mix_1_reg_2_val = snd_soc_read(codec,
rx_mix_1_reg_2);
if (((rx_mix_1_reg_1_val & 0x0F) == rx_mix1_inp) ||
(((rx_mix_1_reg_1_val >> 4) & 0x0F)
== rx_mix1_inp) ||
((rx_mix_1_reg_2_val & 0x0F) == rx_mix1_inp)) {
rx_fs_reg = TOMTOM_A_CDC_RX1_B5_CTL + 8 * j;
pr_debug("%s: AIF_PB DAI(%d) connected to RX%u\n",
__func__, dai->id, j + 1);
pr_debug("%s: set RX%u sample rate to %u\n",
__func__, j + 1, sample_rate);
snd_soc_update_bits(codec, rx_fs_reg,
0xE0, rx_fs_rate_reg_val);
if (comp_rx_path[j] < COMPANDER_MAX)
tomtom->comp_fs[comp_rx_path[j]]
= compander_fs;
}
if (j < 2)
rx_mix_1_reg_1 += 3;
else
rx_mix_1_reg_1 += 2;
}
/* RX8 interpolator path */
rx_mix_1_reg_1_val = snd_soc_read(codec,
TOMTOM_A_CDC_CONN_RX8_B1_CTL);
if (((rx_mix_1_reg_1_val & 0x0F) == rx8_mix1_inp) ||
(((rx_mix_1_reg_1_val >> 4) & 0x0F) == rx8_mix1_inp)) {
snd_soc_update_bits(codec, TOMTOM_A_CDC_RX8_B5_CTL,
0xE0, rx_fs_rate_reg_val);
pr_debug("%s: AIF_PB DAI(%d) connected to RX%u\n",
__func__, dai->id, NUM_INTERPOLATORS);
pr_debug("%s: set RX%u sample rate to %u\n",
__func__, NUM_INTERPOLATORS,
sample_rate);
if (comp_rx_path[NUM_INTERPOLATORS - 1] < COMPANDER_MAX)
tomtom->comp_fs[comp_rx_path[j]] =
compander_fs;
}
}
return 0;
}
static int tomtom_set_decimator_rate(struct snd_soc_dai *dai,
u8 tx_fs_rate_reg_val, u32 sample_rate)
{
struct snd_soc_codec *codec = dai->codec;
struct wcd9xxx_ch *ch;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
u32 tx_port;
u16 tx_port_reg, tx_fs_reg;
u8 tx_port_reg_val;
s8 decimator;
list_for_each_entry(ch, &tomtom->dai[dai->id].wcd9xxx_ch_list, list) {
tx_port = ch->port + 1;
pr_debug("%s: dai->id = %d, tx_port = %d",
__func__, dai->id, tx_port);
if ((tx_port < 1) || (tx_port > NUM_DECIMATORS)) {
pr_err("%s: Invalid SLIM TX%u port. DAI ID is %d\n",
__func__, tx_port, dai->id);
return -EINVAL;
}
tx_port_reg = TOMTOM_A_CDC_CONN_TX_SB_B1_CTL + (tx_port - 1);
tx_port_reg_val = snd_soc_read(codec, tx_port_reg);
decimator = 0;
if ((tx_port >= 1) && (tx_port <= 6)) {
tx_port_reg_val = tx_port_reg_val & 0x0F;
if (tx_port_reg_val == 0x8)
decimator = tx_port;
} else if ((tx_port >= 7) && (tx_port <= NUM_DECIMATORS)) {
tx_port_reg_val = tx_port_reg_val & 0x1F;
if ((tx_port_reg_val >= 0x8) &&
(tx_port_reg_val <= 0x11)) {
decimator = (tx_port_reg_val - 0x8) + 1;
}
}
if (decimator) { /* SLIM_TX port has a DEC as input */
tx_fs_reg = TOMTOM_A_CDC_TX1_CLK_FS_CTL +
8 * (decimator - 1);
pr_debug("%s: set DEC%u (-> SLIM_TX%u) rate to %u\n",
__func__, decimator, tx_port, sample_rate);
snd_soc_update_bits(codec, tx_fs_reg, 0x07,
tx_fs_rate_reg_val);
} else {
if ((tx_port_reg_val >= 0x1) &&
(tx_port_reg_val <= 0x7)) {
pr_debug("%s: RMIX%u going to SLIM TX%u\n",
__func__, tx_port_reg_val, tx_port);
} else if ((tx_port_reg_val >= 0x8) &&
(tx_port_reg_val <= 0x11)) {
pr_err("%s: ERROR: Should not be here\n",
__func__);
pr_err("%s: ERROR: DEC connected to SLIM TX%u\n",
__func__, tx_port);
return -EINVAL;
} else if (tx_port_reg_val == 0) {
pr_debug("%s: no signal to SLIM TX%u\n",
__func__, tx_port);
} else {
pr_err("%s: ERROR: wrong signal to SLIM TX%u\n",
__func__, tx_port);
pr_err("%s: ERROR: wrong signal = %u\n",
__func__, tx_port_reg_val);
return -EINVAL;
}
}
}
return 0;
}
static void tomtom_set_rxsb_port_format(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_codec_dai_data *cdc_dai;
struct wcd9xxx_ch *ch;
int port;
u8 bit_sel;
u16 sb_ctl_reg, field_shift;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
bit_sel = 0x2;
tomtom_p->dai[dai->id].bit_width = 16;
break;
case SNDRV_PCM_FORMAT_S24_LE:
bit_sel = 0x0;
tomtom_p->dai[dai->id].bit_width = 24;
break;
default:
dev_err(codec->dev, "Invalid format\n");
return;
}
cdc_dai = &tomtom_p->dai[dai->id];
list_for_each_entry(ch, &cdc_dai->wcd9xxx_ch_list, list) {
port = wcd9xxx_get_slave_port(ch->ch_num);
if (IS_ERR_VALUE(port) ||
!TOMTOM_VALIDATE_RX_SBPORT_RANGE(port)) {
dev_warn(codec->dev,
"%s: invalid port ID %d returned for RX DAI\n",
__func__, port);
return;
}
port = TOMTOM_CONVERT_RX_SBPORT_ID(port);
if (port <= 3) {
sb_ctl_reg = TOMTOM_A_CDC_CONN_RX_SB_B1_CTL;
field_shift = port << 1;
} else if (port <= 7) {
sb_ctl_reg = TOMTOM_A_CDC_CONN_RX_SB_B2_CTL;
field_shift = (port - 4) << 1;
} else { /* should not happen */
dev_warn(codec->dev,
"%s: bad port ID %d\n", __func__, port);
return;
}
dev_dbg(codec->dev, "%s: sb_ctl_reg %x field_shift %x\n",
__func__, sb_ctl_reg, field_shift);
snd_soc_update_bits(codec, sb_ctl_reg, 0x3 << field_shift,
bit_sel << field_shift);
}
}
static void tomtom_set_tx_sb_port_format(struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_codec_dai_data *cdc_dai;
struct wcd9xxx_ch *ch;
int port;
u8 bit_sel, bit_shift;
u16 sb_ctl_reg;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
bit_sel = 0x2;
tomtom_p->dai[dai->id].bit_width = 16;
break;
case SNDRV_PCM_FORMAT_S24_LE:
bit_sel = 0x0;
tomtom_p->dai[dai->id].bit_width = 24;
break;
default:
dev_err(codec->dev, "%s: Invalid format %d\n", __func__,
params_format(params));
return;
}
cdc_dai = &tomtom_p->dai[dai->id];
list_for_each_entry(ch, &cdc_dai->wcd9xxx_ch_list, list) {
port = wcd9xxx_get_slave_port(ch->ch_num);
if (IS_ERR_VALUE(port) ||
!TOMTOM_VALIDATE_TX_SBPORT_RANGE(port)) {
dev_warn(codec->dev,
"%s: invalid port ID %d returned for TX DAI\n",
__func__, port);
return;
}
if (port < 6) /* 6 = SLIMBUS TX7 */
bit_shift = TOMTOM_BIT_ADJ_SHIFT_PORT1_6;
else if (port < 10)
bit_shift = TOMTOM_BIT_ADJ_SHIFT_PORT7_10;
else {
dev_warn(codec->dev,
"%s: port ID %d bitwidth is fixed\n",
__func__, port);
return;
}
sb_ctl_reg = (TOMTOM_A_CDC_CONN_TX_SB_B1_CTL + port);
dev_dbg(codec->dev, "%s: reg %x bit_sel %x bit_shift %x\n",
__func__, sb_ctl_reg, bit_sel, bit_shift);
snd_soc_update_bits(codec, sb_ctl_reg, 0x3 <<
bit_shift, bit_sel << bit_shift);
}
}
static int tomtom_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(dai->codec);
u8 tx_fs_rate, rx_fs_rate, i2s_bit_mode;
u32 compander_fs;
int ret;
pr_debug("%s: dai_name = %s DAI-ID %x rate %d num_ch %d\n", __func__,
dai->name, dai->id, params_rate(params),
params_channels(params));
switch (params_rate(params)) {
case 8000:
tx_fs_rate = 0x00;
rx_fs_rate = 0x00;
compander_fs = COMPANDER_FS_8KHZ;
break;
case 16000:
tx_fs_rate = 0x01;
rx_fs_rate = 0x20;
compander_fs = COMPANDER_FS_16KHZ;
break;
case 32000:
tx_fs_rate = 0x02;
rx_fs_rate = 0x40;
compander_fs = COMPANDER_FS_32KHZ;
break;
case 48000:
tx_fs_rate = 0x03;
rx_fs_rate = 0x60;
compander_fs = COMPANDER_FS_48KHZ;
break;
case 96000:
tx_fs_rate = 0x04;
rx_fs_rate = 0x80;
compander_fs = COMPANDER_FS_96KHZ;
break;
case 192000:
tx_fs_rate = 0x05;
rx_fs_rate = 0xA0;
compander_fs = COMPANDER_FS_192KHZ;
break;
default:
pr_err("%s: Invalid sampling rate %d\n", __func__,
params_rate(params));
return -EINVAL;
}
switch (substream->stream) {
case SNDRV_PCM_STREAM_CAPTURE:
if (dai->id != AIF4_VIFEED &&
dai->id != AIF4_MAD_TX) {
ret = tomtom_set_decimator_rate(dai, tx_fs_rate,
params_rate(params));
if (ret < 0) {
pr_err("%s: set decimator rate failed %d\n",
__func__, ret);
return ret;
}
}
tomtom->dai[dai->id].rate = params_rate(params);
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
i2s_bit_mode = 0x01;
tomtom->dai[dai->id].bit_width = 16;
break;
case SNDRV_PCM_FORMAT_S24_LE:
tomtom->dai[dai->id].bit_width = 24;
i2s_bit_mode = 0x00;
break;
case SNDRV_PCM_FORMAT_S32_LE:
tomtom->dai[dai->id].bit_width = 32;
i2s_bit_mode = 0x00;
break;
default:
dev_err(codec->dev,
"%s: Invalid format 0x%x\n",
__func__, params_format(params));
return -EINVAL;
}
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_TX_I2S_CTL,
0x20, i2s_bit_mode << 5);
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_TX_I2S_CTL,
0x07, tx_fs_rate);
} else {
/* only generic ports can have sample bit adjustment */
if (dai->id != AIF4_VIFEED &&
dai->id != AIF4_MAD_TX)
tomtom_set_tx_sb_port_format(params, dai);
}
break;
case SNDRV_PCM_STREAM_PLAYBACK:
ret = tomtom_set_interpolator_rate(dai, rx_fs_rate,
compander_fs,
params_rate(params));
if (ret < 0) {
pr_err("%s: set decimator rate failed %d\n", __func__,
ret);
return ret;
}
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_RX_I2S_CTL,
0x20, 0x20);
break;
case SNDRV_PCM_FORMAT_S32_LE:
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_RX_I2S_CTL,
0x20, 0x00);
break;
default:
pr_err("invalid format\n");
break;
}
snd_soc_update_bits(codec, TOMTOM_A_CDC_CLK_RX_I2S_CTL,
0x03, (rx_fs_rate >> 0x05));
} else {
tomtom_set_rxsb_port_format(params, dai);
tomtom->dai[dai->id].rate = params_rate(params);
}
break;
default:
pr_err("%s: Invalid stream type %d\n", __func__,
substream->stream);
return -EINVAL;
}
return 0;
}
static struct snd_soc_dai_ops tomtom_dai_ops = {
.startup = tomtom_startup,
.shutdown = tomtom_shutdown,
.hw_params = tomtom_hw_params,
.set_sysclk = tomtom_set_dai_sysclk,
.set_fmt = tomtom_set_dai_fmt,
.set_channel_map = tomtom_set_channel_map,
.get_channel_map = tomtom_get_channel_map,
};
static struct snd_soc_dai_driver tomtom_dai[] = {
{
.name = "tomtom_rx1",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF1 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS_S16_S24_LE,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_tx1",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF1 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_rx2",
.id = AIF2_PB,
.playback = {
.stream_name = "AIF2 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS_S16_S24_LE,
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_tx2",
.id = AIF2_CAP,
.capture = {
.stream_name = "AIF2 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 8,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_rx3",
.id = AIF3_PB,
.playback = {
.stream_name = "AIF3 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS_S16_S24_LE,
.rate_min = 8000,
.rate_max = 192000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_tx3",
.id = AIF3_CAP,
.capture = {
.stream_name = "AIF3 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 48000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 2,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_vifeedback",
.id = AIF4_VIFEED,
.capture = {
.stream_name = "VIfeed",
.rates = SNDRV_PCM_RATE_48000,
.formats = TOMTOM_FORMATS,
.rate_max = 48000,
.rate_min = 48000,
.channels_min = 2,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_mad1",
.id = AIF4_MAD_TX,
.capture = {
.stream_name = "AIF4 MAD TX",
.rates = SNDRV_PCM_RATE_16000,
.formats = TOMTOM_FORMATS_S16_S24_LE,
.rate_min = 16000,
.rate_max = 16000,
.channels_min = 1,
.channels_max = 1,
},
.ops = &tomtom_dai_ops,
},
};
static struct snd_soc_dai_driver tomtom_i2s_dai[] = {
{
.name = "tomtom_i2s_rx1",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF1 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_i2s_tx1",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF1 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_i2s_rx2",
.id = AIF1_PB,
.playback = {
.stream_name = "AIF2 Playback",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
{
.name = "tomtom_i2s_tx2",
.id = AIF1_CAP,
.capture = {
.stream_name = "AIF2 Capture",
.rates = WCD9330_RATES,
.formats = TOMTOM_FORMATS,
.rate_max = 192000,
.rate_min = 8000,
.channels_min = 1,
.channels_max = 4,
},
.ops = &tomtom_dai_ops,
},
};
static int tomtom_codec_enable_slim_chmask(struct wcd9xxx_codec_dai_data *dai,
bool up)
{
int ret = 0;
struct wcd9xxx_ch *ch;
if (up) {
list_for_each_entry(ch, &dai->wcd9xxx_ch_list, list) {
ret = wcd9xxx_get_slave_port(ch->ch_num);
if (ret < 0) {
pr_err("%s: Invalid slave port ID: %d\n",
__func__, ret);
ret = -EINVAL;
} else {
set_bit(ret, &dai->ch_mask);
}
}
} else {
ret = wait_event_timeout(dai->dai_wait, (dai->ch_mask == 0),
msecs_to_jiffies(
TOMTOM_SLIM_CLOSE_TIMEOUT));
if (!ret) {
pr_err("%s: Slim close tx/rx wait timeout\n", __func__);
ret = -ETIMEDOUT;
} else {
ret = 0;
}
}
return ret;
}
static void tomtom_codec_enable_int_port(struct wcd9xxx_codec_dai_data *dai,
struct snd_soc_codec *codec)
{
struct wcd9xxx_ch *ch;
int port_num = 0;
unsigned short reg = 0;
u8 val = 0;
if (!dai || !codec) {
pr_err("%s: Invalid params\n", __func__);
return;
}
list_for_each_entry(ch, &dai->wcd9xxx_ch_list, list) {
if (ch->port >= TOMTOM_RX_PORT_START_NUMBER) {
port_num = ch->port - TOMTOM_RX_PORT_START_NUMBER;
reg = TOMTOM_SLIM_PGD_PORT_INT_EN0 + (port_num / 8);
val = wcd9xxx_interface_reg_read(codec->control_data,
reg);
if (!(val & (1 << (port_num % 8)))) {
val |= (1 << (port_num % 8));
wcd9xxx_interface_reg_write(
codec->control_data, reg, val);
val = wcd9xxx_interface_reg_read(
codec->control_data, reg);
}
} else {
port_num = ch->port;
reg = TOMTOM_SLIM_PGD_PORT_INT_TX_EN0 + (port_num / 8);
val = wcd9xxx_interface_reg_read(codec->control_data,
reg);
if (!(val & (1 << (port_num % 8)))) {
val |= (1 << (port_num % 8));
wcd9xxx_interface_reg_write(codec->control_data,
reg, val);
val = wcd9xxx_interface_reg_read(
codec->control_data, reg);
}
}
}
}
static int tomtom_codec_enable_slimrx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct wcd9xxx *core;
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
int ret = 0;
struct wcd9xxx_codec_dai_data *dai;
core = dev_get_drvdata(codec->dev->parent);
pr_debug("%s: event called! codec name %s num_dai %d\n"
"stream name %s event %d\n",
__func__, w->codec->name, w->codec->num_dai, w->sname, event);
/* Execute the callback only if interface type is slimbus */
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS)
return 0;
dai = &tomtom_p->dai[w->shift];
pr_debug("%s: w->name %s w->shift %d event %d\n",
__func__, w->name, w->shift, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
dai->bus_down_in_recovery = false;
tomtom_codec_enable_int_port(dai, codec);
(void) tomtom_codec_enable_slim_chmask(dai, true);
ret = wcd9xxx_cfg_slim_sch_rx(core, &dai->wcd9xxx_ch_list,
dai->rate, dai->bit_width,
&dai->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_disconnect_port(core,
&dai->wcd9xxx_ch_list,
dai->grph);
pr_debug("%s: Disconnect RX port, ret = %d\n",
__func__, ret);
ret = wcd9xxx_close_slim_sch_rx(core, &dai->wcd9xxx_ch_list,
dai->grph);
if (!dai->bus_down_in_recovery)
ret = tomtom_codec_enable_slim_chmask(dai, false);
else
pr_debug("%s: bus in recovery skip enable slim_chmask",
__func__);
break;
}
return ret;
}
static int tomtom_codec_enable_slimvi_feedback(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct wcd9xxx *core = NULL;
struct snd_soc_codec *codec = NULL;
struct tomtom_priv *tomtom_p = NULL;
int ret = 0;
struct wcd9xxx_codec_dai_data *dai = NULL;
if (!w || !w->codec) {
pr_err("%s invalid params\n", __func__);
return -EINVAL;
}
codec = w->codec;
tomtom_p = snd_soc_codec_get_drvdata(codec);
core = dev_get_drvdata(codec->dev->parent);
pr_debug("%s: event called! codec name %s num_dai %d stream name %s\n",
__func__, w->codec->name, w->codec->num_dai, w->sname);
/* Execute the callback only if interface type is slimbus */
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
pr_err("%s Interface is not correct", __func__);
return 0;
}
pr_debug("%s(): w->name %s event %d w->shift %d\n",
__func__, w->name, event, w->shift);
if (w->shift != AIF4_VIFEED) {
pr_err("%s Error in enabling the tx path\n", __func__);
ret = -EINVAL;
goto out_vi;
}
dai = &tomtom_p->dai[w->shift];
switch (event) {
case SND_SOC_DAPM_POST_PMU:
if (test_bit(VI_SENSE_1, &tomtom_p->status_mask)) {
pr_debug("%s: spkr1 enabled\n", __func__);
/* Enable V&I sensing */
snd_soc_update_bits(codec,
TOMTOM_A_SPKR1_PROT_EN, 0x88, 0x88);
/* Enable spkr VI clocks */
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0xC, 0xC);
}
if (test_bit(VI_SENSE_2, &tomtom_p->status_mask)) {
pr_debug("%s: spkr2 enabled\n", __func__);
/* Enable V&I sensing */
snd_soc_update_bits(codec,
TOMTOM_A_SPKR2_PROT_EN, 0x88, 0x88);
/* Enable spkr VI clocks */
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0x30, 0x30);
}
dai->bus_down_in_recovery = false;
tomtom_codec_enable_int_port(dai, codec);
(void) tomtom_codec_enable_slim_chmask(dai, true);
ret = wcd9xxx_cfg_slim_sch_tx(core, &dai->wcd9xxx_ch_list,
dai->rate, dai->bit_width,
&dai->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_close_slim_sch_tx(core, &dai->wcd9xxx_ch_list,
dai->grph);
if (ret)
pr_err("%s error in close_slim_sch_tx %d\n",
__func__, ret);
if (!dai->bus_down_in_recovery)
ret = tomtom_codec_enable_slim_chmask(dai, false);
if (ret < 0) {
ret = wcd9xxx_disconnect_port(core,
&dai->wcd9xxx_ch_list,
dai->grph);
pr_debug("%s: Disconnect TX port, ret = %d\n",
__func__, ret);
}
if (test_bit(VI_SENSE_1, &tomtom_p->status_mask)) {
/* Disable V&I sensing */
pr_debug("%s: spkr1 disabled\n", __func__);
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0xC, 0x0);
snd_soc_update_bits(codec,
TOMTOM_A_SPKR1_PROT_EN, 0x88, 0x00);
}
if (test_bit(VI_SENSE_2, &tomtom_p->status_mask)) {
/* Disable V&I sensing */
pr_debug("%s: spkr2 disabled\n", __func__);
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0x30, 0x0);
snd_soc_update_bits(codec,
TOMTOM_A_SPKR2_PROT_EN, 0x88, 0x00);
}
break;
}
out_vi:
return ret;
}
/* __tomtom_codec_enable_slimtx: Enable the slimbus slave port
* for TX path
* @codec: Handle to the codec for which the slave port is to be
* enabled.
* @dai_data: The dai specific data for dai which is enabled.
*/
static int __tomtom_codec_enable_slimtx(struct snd_soc_codec *codec,
int event, struct wcd9xxx_codec_dai_data *dai_data)
{
struct wcd9xxx *core;
int ret = 0;
core = dev_get_drvdata(codec->dev->parent);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
dai_data->bus_down_in_recovery = false;
tomtom_codec_enable_int_port(dai_data, codec);
(void) tomtom_codec_enable_slim_chmask(dai_data, true);
ret = wcd9xxx_cfg_slim_sch_tx(core, &dai_data->wcd9xxx_ch_list,
dai_data->rate,
dai_data->bit_width,
&dai_data->grph);
break;
case SND_SOC_DAPM_POST_PMD:
ret = wcd9xxx_close_slim_sch_tx(core,
&dai_data->wcd9xxx_ch_list,
dai_data->grph);
if (!dai_data->bus_down_in_recovery)
ret = tomtom_codec_enable_slim_chmask(dai_data, false);
if (ret < 0) {
ret = wcd9xxx_disconnect_port(core,
&dai_data->wcd9xxx_ch_list,
dai_data->grph);
dev_dbg(codec->dev,
"%s: Disconnect TX port, ret = %d\n",
__func__, ret);
}
break;
}
return ret;
}
/*
* tomtom_codec_enable_slimtx_mad: Callback function that will be invoked
* to setup the slave port for MAD.
* @codec: Handle to the codec
* @event: Indicates whether to enable or disable the slave port
*/
static int tomtom_codec_enable_slimtx_mad(struct snd_soc_codec *codec,
u8 event)
{
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_codec_dai_data *dai;
int dapm_event = SND_SOC_DAPM_POST_PMU;
dai = &tomtom_p->dai[AIF4_MAD_TX];
if (event == 0)
dapm_event = SND_SOC_DAPM_POST_PMD;
dev_dbg(codec->dev,
"%s: mad_channel, event = 0x%x\n",
__func__, event);
return __tomtom_codec_enable_slimtx(codec, dapm_event, dai);
}
/*
* tomtom_codec_enable_slimtx: DAPM widget allback for TX widgets
* @w: widget for which this callback is invoked
* @kcontrol: kcontrol associated with this widget
* @event: DAPM supplied event indicating enable/disable
*/
static int tomtom_codec_enable_slimtx(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol,
int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
struct wcd9xxx_codec_dai_data *dai;
dev_dbg(codec->dev,
"%s: codec name %s num_dai %d stream name %s\n",
__func__, w->codec->name,
w->codec->num_dai, w->sname);
/* Execute the callback only if interface type is slimbus */
if (tomtom_p->intf_type != WCD9XXX_INTERFACE_TYPE_SLIMBUS)
return 0;
dev_dbg(codec->dev,
"%s(): w->name %s event %d w->shift %d\n",
__func__, w->name, event, w->shift);
dai = &tomtom_p->dai[w->shift];
return __tomtom_codec_enable_slimtx(codec, event, dai);
}
static int tomtom_codec_enable_ear_pa(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_EAR,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
usleep_range(5000, 5100);
break;
}
return 0;
}
static int tomtom_codec_ear_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
struct tomtom_priv *tomtom_p = snd_soc_codec_get_drvdata(codec);
pr_debug("%s %s %d\n", __func__, w->name, event);
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_EAR,
WCD9XXX_CLSH_REQ_ENABLE,
WCD9XXX_CLSH_EVENT_PRE_DAC);
break;
case SND_SOC_DAPM_POST_PMD:
wcd9xxx_clsh_fsm(codec, &tomtom_p->clsh_d,
WCD9XXX_CLSH_STATE_EAR,
WCD9XXX_CLSH_REQ_DISABLE,
WCD9XXX_CLSH_EVENT_POST_PA);
usleep_range(5000, 5100);
break;
default:
break;
}
return 0;
}
static int tomtom_codec_set_iir_gain(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
pr_debug("%s: event = %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU: /* fall through */
case SND_SOC_DAPM_PRE_PMD:
if (strnstr(w->name, "IIR1", sizeof("IIR1"))) {
snd_soc_write(codec, TOMTOM_A_CDC_IIR1_GAIN_B1_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR1_GAIN_B1_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR1_GAIN_B2_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR1_GAIN_B2_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR1_GAIN_B3_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR1_GAIN_B3_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR1_GAIN_B4_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR1_GAIN_B4_CTL));
} else {
snd_soc_write(codec, TOMTOM_A_CDC_IIR2_GAIN_B1_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR2_GAIN_B1_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR2_GAIN_B2_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR2_GAIN_B2_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR2_GAIN_B3_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR2_GAIN_B3_CTL));
snd_soc_write(codec, TOMTOM_A_CDC_IIR2_GAIN_B4_CTL,
snd_soc_read(codec,
TOMTOM_A_CDC_IIR2_GAIN_B4_CTL));
}
break;
}
return 0;
}
static int tomtom_codec_dsm_mux_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
u8 reg_val, zoh_mux_val = 0x00;
pr_debug("%s: event = %d\n", __func__, event);
switch (event) {
case SND_SOC_DAPM_POST_PMU:
reg_val = snd_soc_read(codec, TOMTOM_A_CDC_CONN_CLSH_CTL);
if ((reg_val & 0x30) == 0x10)
zoh_mux_val = 0x04;
else if ((reg_val & 0x30) == 0x20)
zoh_mux_val = 0x08;
if (zoh_mux_val != 0x00)
snd_soc_update_bits(codec,
TOMTOM_A_CDC_CONN_CLSH_CTL,
0x0C, zoh_mux_val);
break;
case SND_SOC_DAPM_POST_PMD:
snd_soc_update_bits(codec, TOMTOM_A_CDC_CONN_CLSH_CTL,
0x0C, 0x00);
break;
}
return 0;
}
static int tomtom_codec_enable_anc_ear(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *kcontrol, int event)
{
struct snd_soc_codec *codec = w->codec;
int ret = 0;
switch (event) {
case SND_SOC_DAPM_PRE_PMU:
ret = tomtom_codec_enable_anc(w, kcontrol, event);
msleep(50);
snd_soc_update_bits(codec, TOMTOM_A_RX_EAR_EN, 0x10, 0x10);
break;
case SND_SOC_DAPM_POST_PMU:
ret = tomtom_codec_enable_ear_pa(w, kcontrol, event);
break;
case SND_SOC_DAPM_PRE_PMD:
snd_soc_update_bits(codec, TOMTOM_A_RX_EAR_EN, 0x10, 0x00);
msleep(40);
ret |= tomtom_codec_enable_anc(w, kcontrol, event);
break;
case SND_SOC_DAPM_POST_PMD:
ret = tomtom_codec_enable_ear_pa(w, kcontrol, event);
break;
}
return ret;
}
/* Todo: Have seperate dapm widgets for I2S and Slimbus.
* Might Need to have callbacks registered only for slimbus
*/
static const struct snd_soc_dapm_widget tomtom_dapm_widgets[] = {
/*RX stuff */
SND_SOC_DAPM_OUTPUT("EAR"),
SND_SOC_DAPM_PGA_E("EAR PA", TOMTOM_A_RX_EAR_EN, 4, 0, NULL, 0,
tomtom_codec_enable_ear_pa, SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("DAC1", TOMTOM_A_RX_EAR_EN, 6, 0, dac1_switch,
ARRAY_SIZE(dac1_switch), tomtom_codec_ear_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF1 PB", "AIF1 Playback", 0, SND_SOC_NOPM,
AIF1_PB, 0, tomtom_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF2 PB", "AIF2 Playback", 0, SND_SOC_NOPM,
AIF2_PB, 0, tomtom_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_IN_E("AIF3 PB", "AIF3 Playback", 0, SND_SOC_NOPM,
AIF3_PB, 0, tomtom_codec_enable_slimrx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("SLIM RX1 MUX", SND_SOC_NOPM, TOMTOM_RX1, 0,
&slim_rx_mux[TOMTOM_RX1]),
SND_SOC_DAPM_MUX("SLIM RX2 MUX", SND_SOC_NOPM, TOMTOM_RX2, 0,
&slim_rx_mux[TOMTOM_RX2]),
SND_SOC_DAPM_MUX("SLIM RX3 MUX", SND_SOC_NOPM, TOMTOM_RX3, 0,
&slim_rx_mux[TOMTOM_RX3]),
SND_SOC_DAPM_MUX("SLIM RX4 MUX", SND_SOC_NOPM, TOMTOM_RX4, 0,
&slim_rx_mux[TOMTOM_RX4]),
SND_SOC_DAPM_MUX("SLIM RX5 MUX", SND_SOC_NOPM, TOMTOM_RX5, 0,
&slim_rx_mux[TOMTOM_RX5]),
SND_SOC_DAPM_MUX("SLIM RX6 MUX", SND_SOC_NOPM, TOMTOM_RX6, 0,
&slim_rx_mux[TOMTOM_RX6]),
SND_SOC_DAPM_MUX("SLIM RX7 MUX", SND_SOC_NOPM, TOMTOM_RX7, 0,
&slim_rx_mux[TOMTOM_RX7]),
SND_SOC_DAPM_MUX("SLIM RX8 MUX", SND_SOC_NOPM, TOMTOM_RX8, 0,
&slim_rx_mux[TOMTOM_RX8]),
SND_SOC_DAPM_MIXER("SLIM RX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX3", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX4", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX5", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX6", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX7", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("SLIM RX8", SND_SOC_NOPM, 0, 0, NULL, 0),
/* Headphone */
SND_SOC_DAPM_OUTPUT("HEADPHONE"),
SND_SOC_DAPM_PGA_E("HPHL", TOMTOM_A_RX_HPH_CNP_EN, 5, 0, NULL, 0,
tomtom_hph_pa_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER_E("HPHL DAC", TOMTOM_A_RX_HPH_L_DAC_CTL, 7, 0,
hphl_switch, ARRAY_SIZE(hphl_switch), tomtom_hphl_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("HPHR", TOMTOM_A_RX_HPH_CNP_EN, 4, 0, NULL, 0,
tomtom_hph_pa_event, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("HPHR DAC", NULL, TOMTOM_A_RX_HPH_R_DAC_CTL, 7, 0,
tomtom_hphr_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
/* Speaker */
SND_SOC_DAPM_OUTPUT("LINEOUT1"),
SND_SOC_DAPM_OUTPUT("LINEOUT2"),
SND_SOC_DAPM_OUTPUT("LINEOUT3"),
SND_SOC_DAPM_OUTPUT("LINEOUT4"),
SND_SOC_DAPM_OUTPUT("SPK_OUT"),
SND_SOC_DAPM_PGA_E("LINEOUT1 PA", TOMTOM_A_RX_LINE_CNP_EN, 0, 0, NULL,
0, tomtom_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT2 PA", TOMTOM_A_RX_LINE_CNP_EN, 1, 0, NULL,
0, tomtom_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT3 PA", TOMTOM_A_RX_LINE_CNP_EN, 2, 0, NULL,
0, tomtom_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("LINEOUT4 PA", TOMTOM_A_RX_LINE_CNP_EN, 3, 0, NULL,
0, tomtom_codec_enable_lineout, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("SPK PA", SND_SOC_NOPM, 0, 0 , NULL,
0, tomtom_codec_enable_spk_pa,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_PGA_E("SPK2 PA", SND_SOC_NOPM, 0, 0 , NULL,
0, tomtom_codec_enable_spk_pa,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("LINEOUT1 DAC", NULL, TOMTOM_A_RX_LINE_1_DAC_CTL, 7,
0, tomtom_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("LINEOUT2 DAC", NULL, TOMTOM_A_RX_LINE_2_DAC_CTL, 7,
0, tomtom_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("LINEOUT3 DAC", NULL, TOMTOM_A_RX_LINE_3_DAC_CTL, 7,
0, tomtom_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SWITCH("LINEOUT3 DAC GROUND", SND_SOC_NOPM, 0, 0,
&lineout3_ground_switch),
SND_SOC_DAPM_DAC_E("LINEOUT4 DAC", NULL, TOMTOM_A_RX_LINE_4_DAC_CTL, 7,
0, tomtom_lineout_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SWITCH("LINEOUT4 DAC GROUND", SND_SOC_NOPM, 0, 0,
&lineout4_ground_switch),
SND_SOC_DAPM_DAC_E("SPK DAC", NULL, TOMTOM_A_CDC_BOOST_TRGR_EN, 0, 0,
tomtom_spk_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_DAC_E("SPK2 DAC", NULL, TOMTOM_A_CDC_BOOST_TRGR_EN, 1, 0,
tomtom_spk_dac_event,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("VDD_SPKDRV", SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_vdd_spkr,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("VDD_SPKDRV2", SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_vdd_spkr2,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("MICBIAS_REGULATOR", SND_SOC_NOPM,
ON_DEMAND_MICBIAS, 0,
tomtom_codec_enable_on_demand_supply,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MIXER("RX1 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX2 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX7 MIX1", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX1 MIX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX2 MIX2", SND_SOC_NOPM, 0, 0, NULL, 0),
SND_SOC_DAPM_MIXER_E("RX3 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 2, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX4 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 3, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX5 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 4, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX6 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 5, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX7 MIX2", TOMTOM_A_CDC_CLK_RX_B1_CTL, 6, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER_E("RX8 MIX1", TOMTOM_A_CDC_CLK_RX_B1_CTL, 7, 0, NULL,
0, tomtom_codec_enable_interpolator, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX_E("RX1 INTERP", TOMTOM_A_CDC_CLK_RX_B1_CTL, 0, 0,
&rx1_interp_mux, tomtom_codec_enable_interpolator,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MUX_E("RX2 INTERP", TOMTOM_A_CDC_CLK_RX_B1_CTL, 1, 0,
&rx2_interp_mux, tomtom_codec_enable_interpolator,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_MIXER("RX1 CHAIN", TOMTOM_A_CDC_RX1_B6_CTL, 5, 0, NULL, 0),
SND_SOC_DAPM_MIXER("RX2 CHAIN", TOMTOM_A_CDC_RX2_B6_CTL, 5, 0, NULL, 0),
SND_SOC_DAPM_MUX("RX1 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX1 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX1 MIX1 INP3", SND_SOC_NOPM, 0, 0,
&rx_mix1_inp3_mux),
SND_SOC_DAPM_MUX("RX2 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx2_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX2 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx2_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX3 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx3_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX3 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx3_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX4 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx4_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX4 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx4_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX5 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx5_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX5 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx5_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX6 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx6_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX6 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx6_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX7 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx7_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX7 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx7_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX8 MIX1 INP1", SND_SOC_NOPM, 0, 0,
&rx8_mix1_inp1_mux),
SND_SOC_DAPM_MUX("RX8 MIX1 INP2", SND_SOC_NOPM, 0, 0,
&rx8_mix1_inp2_mux),
SND_SOC_DAPM_MUX("RX1 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx1_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX1 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx1_mix2_inp2_mux),
SND_SOC_DAPM_MUX("RX2 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx2_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX2 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx2_mix2_inp2_mux),
SND_SOC_DAPM_MUX("RX7 MIX2 INP1", SND_SOC_NOPM, 0, 0,
&rx7_mix2_inp1_mux),
SND_SOC_DAPM_MUX("RX7 MIX2 INP2", SND_SOC_NOPM, 0, 0,
&rx7_mix2_inp2_mux),
SND_SOC_DAPM_MUX("RDAC5 MUX", SND_SOC_NOPM, 0, 0,
&rx_dac5_mux),
SND_SOC_DAPM_MUX("RDAC7 MUX", SND_SOC_NOPM, 0, 0,
&rx_dac7_mux),
SND_SOC_DAPM_MUX("MAD_SEL MUX", SND_SOC_NOPM, 0, 0,
&mad_sel_mux),
SND_SOC_DAPM_MUX_E("CLASS_H_DSM MUX", SND_SOC_NOPM, 0, 0,
&class_h_dsm_mux, tomtom_codec_dsm_mux_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("RX_BIAS", SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_rx_bias, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("CDC_I2S_RX_CONN", WCD9XXX_A_CDC_CLK_OTHR_CTL, 5, 0,
NULL, 0),
/* TX */
SND_SOC_DAPM_SUPPLY("CDC_CONN", WCD9XXX_A_CDC_CLK_OTHR_CTL, 2, 0, NULL,
0),
SND_SOC_DAPM_SUPPLY("LDO_H", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_ldo_h,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
/*
* DAPM 'LDO_H Standalone' is to be powered by mbhc driver after
* acquring codec_resource lock.
* So call __tomtom_codec_enable_ldo_h instead and avoid deadlock.
*/
SND_SOC_DAPM_SUPPLY("LDO_H Standalone", SND_SOC_NOPM, 7, 0,
__tomtom_codec_enable_ldo_h,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SUPPLY("COMP0_CLK", SND_SOC_NOPM, 0, 0,
tomtom_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_SUPPLY("COMP1_CLK", SND_SOC_NOPM, 1, 0,
tomtom_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_SUPPLY("COMP2_CLK", SND_SOC_NOPM, 2, 0,
tomtom_config_compander, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_INPUT("AMIC1"),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 External", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal1", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS1 Internal2", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_INPUT("AMIC3"),
SND_SOC_DAPM_INPUT("AMIC4"),
SND_SOC_DAPM_INPUT("AMIC5"),
SND_SOC_DAPM_INPUT("AMIC6"),
SND_SOC_DAPM_MUX_E("DEC1 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 0, 0,
&dec1_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC2 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 1, 0,
&dec2_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC3 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 2, 0,
&dec3_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC4 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 3, 0,
&dec4_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC5 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 4, 0,
&dec5_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC6 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 5, 0,
&dec6_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC7 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 6, 0,
&dec7_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC8 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B1_CTL, 7, 0,
&dec8_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC9 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 0, 0,
&dec9_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX_E("DEC10 MUX", TOMTOM_A_CDC_CLK_TX_CLK_EN_B2_CTL, 1, 0,
&dec10_mux, tomtom_codec_enable_dec,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("ANC1 MUX", SND_SOC_NOPM, 0, 0, &anc1_mux),
SND_SOC_DAPM_MUX("ANC2 MUX", SND_SOC_NOPM, 0, 0, &anc2_mux),
SND_SOC_DAPM_OUTPUT("ANC HEADPHONE"),
SND_SOC_DAPM_PGA_E("ANC HPHL", SND_SOC_NOPM, 5, 0, NULL, 0,
tomtom_codec_enable_anc_hph,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD |
SND_SOC_DAPM_POST_PMD | SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_PGA_E("ANC HPHR", SND_SOC_NOPM, 4, 0, NULL, 0,
tomtom_codec_enable_anc_hph, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMD |
SND_SOC_DAPM_POST_PMU),
SND_SOC_DAPM_OUTPUT("ANC EAR"),
SND_SOC_DAPM_PGA_E("ANC EAR PA", SND_SOC_NOPM, 0, 0, NULL, 0,
tomtom_codec_enable_anc_ear,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_PRE_PMD |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MUX("ANC1 FB MUX", SND_SOC_NOPM, 0, 0, &anc1_fb_mux),
SND_SOC_DAPM_INPUT("AMIC2"),
SND_SOC_DAPM_MICBIAS_E(DAPM_MICBIAS2_EXTERNAL_STANDALONE, SND_SOC_NOPM,
7, 0, tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 External", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal1", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal2", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS2 Internal3", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 External", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal1", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS3 Internal2", SND_SOC_NOPM, 7, 0,
tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_MICBIAS_E("MIC BIAS4 External", SND_SOC_NOPM, 7,
0, tomtom_codec_enable_micbias,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF1 CAP", "AIF1 Capture", 0, SND_SOC_NOPM,
AIF1_CAP, 0, tomtom_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF2 CAP", "AIF2 Capture", 0, SND_SOC_NOPM,
AIF2_CAP, 0, tomtom_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF3 CAP", "AIF3 Capture", 0, SND_SOC_NOPM,
AIF3_CAP, 0, tomtom_codec_enable_slimtx,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF4 VI", "VIfeed", 0, SND_SOC_NOPM,
AIF4_VIFEED, 0, tomtom_codec_enable_slimvi_feedback,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_AIF_OUT_E("AIF4 MAD", "AIF4 MAD TX", 0,
SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_mad,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_SWITCH("MADONOFF", SND_SOC_NOPM, 0, 0,
&aif4_mad_switch),
SND_SOC_DAPM_INPUT("MADINPUT"),
SND_SOC_DAPM_INPUT("MAD_CPE_INPUT"),
SND_SOC_DAPM_MIXER("AIF1_CAP Mixer", SND_SOC_NOPM, AIF1_CAP, 0,
aif1_cap_mixer, ARRAY_SIZE(aif1_cap_mixer)),
SND_SOC_DAPM_MIXER("AIF4_VI Mixer", SND_SOC_NOPM, AIF4_VIFEED, 0,
aif4_vi_mixer, ARRAY_SIZE(aif4_vi_mixer)),
SND_SOC_DAPM_MIXER("AIF2_CAP Mixer", SND_SOC_NOPM, AIF2_CAP, 0,
aif2_cap_mixer, ARRAY_SIZE(aif2_cap_mixer)),
SND_SOC_DAPM_MIXER("AIF3_CAP Mixer", SND_SOC_NOPM, AIF3_CAP, 0,
aif3_cap_mixer, ARRAY_SIZE(aif3_cap_mixer)),
SND_SOC_DAPM_MUX("SLIM TX1 MUX", SND_SOC_NOPM, TOMTOM_TX1, 0,
&sb_tx1_mux),
SND_SOC_DAPM_MUX("SLIM TX2 MUX", SND_SOC_NOPM, TOMTOM_TX2, 0,
&sb_tx2_mux),
SND_SOC_DAPM_MUX("SLIM TX3 MUX", SND_SOC_NOPM, TOMTOM_TX3, 0,
&sb_tx3_mux),
SND_SOC_DAPM_MUX("SLIM TX4 MUX", SND_SOC_NOPM, TOMTOM_TX4, 0,
&sb_tx4_mux),
SND_SOC_DAPM_MUX("SLIM TX5 MUX", SND_SOC_NOPM, TOMTOM_TX5, 0,
&sb_tx5_mux),
SND_SOC_DAPM_MUX("SLIM TX6 MUX", SND_SOC_NOPM, TOMTOM_TX6, 0,
&sb_tx6_mux),
SND_SOC_DAPM_MUX("SLIM TX7 MUX", SND_SOC_NOPM, TOMTOM_TX7, 0,
&sb_tx7_mux),
SND_SOC_DAPM_MUX("SLIM TX8 MUX", SND_SOC_NOPM, TOMTOM_TX8, 0,
&sb_tx8_mux),
SND_SOC_DAPM_MUX("SLIM TX9 MUX", SND_SOC_NOPM, TOMTOM_TX9, 0,
&sb_tx9_mux),
SND_SOC_DAPM_MUX("SLIM TX10 MUX", SND_SOC_NOPM, TOMTOM_TX10, 0,
&sb_tx10_mux),
/* Digital Mic Inputs */
SND_SOC_DAPM_ADC_E("DMIC1", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC2", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC3", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC4", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC5", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("DMIC6", NULL, SND_SOC_NOPM, 0, 0,
tomtom_codec_enable_dmic, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/* Sidetone */
SND_SOC_DAPM_MUX("IIR1 INP1 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp1_mux),
SND_SOC_DAPM_MUX("IIR1 INP2 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp2_mux),
SND_SOC_DAPM_MUX("IIR1 INP3 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp3_mux),
SND_SOC_DAPM_MUX("IIR1 INP4 MUX", SND_SOC_NOPM, 0, 0, &iir1_inp4_mux),
SND_SOC_DAPM_MIXER_E("IIR1", TOMTOM_A_CDC_CLK_SD_CTL, 0, 0, NULL, 0,
tomtom_codec_set_iir_gain, SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_MUX("IIR2 INP1 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp1_mux),
SND_SOC_DAPM_MUX("IIR2 INP2 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp2_mux),
SND_SOC_DAPM_MUX("IIR2 INP3 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp3_mux),
SND_SOC_DAPM_MUX("IIR2 INP4 MUX", SND_SOC_NOPM, 0, 0, &iir2_inp4_mux),
SND_SOC_DAPM_MIXER_E("IIR2", TOMTOM_A_CDC_CLK_SD_CTL, 1, 0, NULL, 0,
tomtom_codec_set_iir_gain, SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_PRE_PMD),
/* AUX PGA */
SND_SOC_DAPM_ADC_E("AUX_PGA_Left", NULL, TOMTOM_A_RX_AUX_SW_CTL, 7, 0,
tomtom_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("AUX_PGA_Right", NULL, TOMTOM_A_RX_AUX_SW_CTL, 6, 0,
tomtom_codec_enable_aux_pga, SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMD),
/* Lineout, ear and HPH PA Mixers */
SND_SOC_DAPM_MIXER("EAR_PA_MIXER", SND_SOC_NOPM, 0, 0,
ear_pa_mix, ARRAY_SIZE(ear_pa_mix)),
SND_SOC_DAPM_MIXER("HPHL_PA_MIXER", SND_SOC_NOPM, 0, 0,
hphl_pa_mix, ARRAY_SIZE(hphl_pa_mix)),
SND_SOC_DAPM_MIXER("HPHR_PA_MIXER", SND_SOC_NOPM, 0, 0,
hphr_pa_mix, ARRAY_SIZE(hphr_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT1_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout1_pa_mix, ARRAY_SIZE(lineout1_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT2_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout2_pa_mix, ARRAY_SIZE(lineout2_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT3_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout3_pa_mix, ARRAY_SIZE(lineout3_pa_mix)),
SND_SOC_DAPM_MIXER("LINEOUT4_PA_MIXER", SND_SOC_NOPM, 0, 0,
lineout4_pa_mix, ARRAY_SIZE(lineout4_pa_mix)),
SND_SOC_DAPM_INPUT("VIINPUT"),
};
static irqreturn_t tomtom_slimbus_irq(int irq, void *data)
{
struct tomtom_priv *priv = data;
struct snd_soc_codec *codec = priv->codec;
unsigned long status = 0;
int i, j, port_id, k;
u32 bit;
u8 val, int_val = 0;
bool tx, cleared;
unsigned short reg = 0;
for (i = TOMTOM_SLIM_PGD_PORT_INT_STATUS_RX_0, j = 0;
i <= TOMTOM_SLIM_PGD_PORT_INT_STATUS_TX_1; i++, j++) {
val = wcd9xxx_interface_reg_read(codec->control_data, i);
status |= ((u32)val << (8 * j));
}
for_each_set_bit(j, &status, 32) {
tx = (j >= 16 ? true : false);
port_id = (tx ? j - 16 : j);
val = wcd9xxx_interface_reg_read(codec->control_data,
TOMTOM_SLIM_PGD_PORT_INT_RX_SOURCE0 + j);
if (val) {
if (!tx)
reg = TOMTOM_SLIM_PGD_PORT_INT_EN0 +
(port_id / 8);
else
reg = TOMTOM_SLIM_PGD_PORT_INT_TX_EN0 +
(port_id / 8);
int_val = wcd9xxx_interface_reg_read(
codec->control_data, reg);
/*
* Ignore interrupts for ports for which the
* interrupts are not specifically enabled.
*/
if (!(int_val & (1 << (port_id % 8))))
continue;
}
if (val & TOMTOM_SLIM_IRQ_OVERFLOW)
pr_err_ratelimited(
"%s: overflow error on %s port %d, value %x\n",
__func__, (tx ? "TX" : "RX"), port_id, val);
if (val & TOMTOM_SLIM_IRQ_UNDERFLOW)
pr_err_ratelimited(
"%s: underflow error on %s port %d, value %x\n",
__func__, (tx ? "TX" : "RX"), port_id, val);
if ((val & TOMTOM_SLIM_IRQ_OVERFLOW) ||
(val & TOMTOM_SLIM_IRQ_UNDERFLOW)) {
if (!tx)
reg = TOMTOM_SLIM_PGD_PORT_INT_EN0 +
(port_id / 8);
else
reg = TOMTOM_SLIM_PGD_PORT_INT_TX_EN0 +
(port_id / 8);
int_val = wcd9xxx_interface_reg_read(
codec->control_data, reg);
if (int_val & (1 << (port_id % 8))) {
int_val = int_val ^ (1 << (port_id % 8));
wcd9xxx_interface_reg_write(codec->control_data,
reg, int_val);
}
}
if (val & TOMTOM_SLIM_IRQ_PORT_CLOSED) {
/*
* INT SOURCE register starts from RX to TX
* but port number in the ch_mask is in opposite way
*/
bit = (tx ? j - 16 : j + 16);
pr_debug("%s: %s port %d closed value %x, bit %u\n",
__func__, (tx ? "TX" : "RX"), port_id, val,
bit);
for (k = 0, cleared = false; k < NUM_CODEC_DAIS; k++) {
pr_debug("%s: priv->dai[%d].ch_mask = 0x%lx\n",
__func__, k, priv->dai[k].ch_mask);
if (test_and_clear_bit(bit,
&priv->dai[k].ch_mask)) {
cleared = true;
if (!priv->dai[k].ch_mask)
wake_up(&priv->dai[k].dai_wait);
/*
* There are cases when multiple DAIs
* might be using the same slimbus
* channel. Hence don't break here.
*/
}
}
WARN(!cleared,
"Couldn't find slimbus %s port %d for closing\n",
(tx ? "TX" : "RX"), port_id);
}
wcd9xxx_interface_reg_write(codec->control_data,
TOMTOM_SLIM_PGD_PORT_INT_CLR_RX_0 +
(j / 8),
1 << (j % 8));
}
return IRQ_HANDLED;
}
static int tomtom_handle_pdata(struct tomtom_priv *tomtom)
{
struct snd_soc_codec *codec = tomtom->codec;
struct wcd9xxx_pdata *pdata = tomtom->resmgr.pdata;
int k1, k2, k3, dec, rc = 0;
u8 leg_mode, txfe_bypass, txfe_buff, flag;
u8 i = 0, j = 0;
u8 val_txfe = 0, value = 0;
u8 dmic_ctl_val, mad_dmic_ctl_val;
u8 anc_ctl_value = 0;
u32 def_dmic_rate;
u16 tx_dmic_ctl_reg;
if (!pdata) {
pr_err("%s: NULL pdata\n", __func__);
rc = -ENODEV;
goto done;
}
leg_mode = pdata->amic_settings.legacy_mode;
txfe_bypass = pdata->amic_settings.txfe_enable;
txfe_buff = pdata->amic_settings.txfe_buff;
flag = pdata->amic_settings.use_pdata;
/* Make sure settings are correct */
if ((pdata->micbias.ldoh_v > WCD9XXX_LDOH_3P0_V) ||
(pdata->micbias.bias1_cfilt_sel > WCD9XXX_CFILT3_SEL) ||
(pdata->micbias.bias2_cfilt_sel > WCD9XXX_CFILT3_SEL) ||
(pdata->micbias.bias3_cfilt_sel > WCD9XXX_CFILT3_SEL) ||
(pdata->micbias.bias4_cfilt_sel > WCD9XXX_CFILT3_SEL)) {
rc = -EINVAL;
goto done;
}
/* figure out k value */
k1 = wcd9xxx_resmgr_get_k_val(&tomtom->resmgr,
pdata->micbias.cfilt1_mv);
k2 = wcd9xxx_resmgr_get_k_val(&tomtom->resmgr,
pdata->micbias.cfilt2_mv);
k3 = wcd9xxx_resmgr_get_k_val(&tomtom->resmgr,
pdata->micbias.cfilt3_mv);
if (IS_ERR_VALUE(k1) || IS_ERR_VALUE(k2) || IS_ERR_VALUE(k3)) {
rc = -EINVAL;
goto done;
}
/* Set voltage level and always use LDO */
snd_soc_update_bits(codec, TOMTOM_A_LDO_H_MODE_1, 0x0C,
(pdata->micbias.ldoh_v << 2));
snd_soc_update_bits(codec, TOMTOM_A_MICB_CFILT_1_VAL, 0xFC, (k1 << 2));
snd_soc_update_bits(codec, TOMTOM_A_MICB_CFILT_2_VAL, 0xFC, (k2 << 2));
snd_soc_update_bits(codec, TOMTOM_A_MICB_CFILT_3_VAL, 0xFC, (k3 << 2));
snd_soc_update_bits(codec, TOMTOM_A_MICB_1_CTL, 0x60,
(pdata->micbias.bias1_cfilt_sel << 5));
snd_soc_update_bits(codec, TOMTOM_A_MICB_2_CTL, 0x60,
(pdata->micbias.bias2_cfilt_sel << 5));
snd_soc_update_bits(codec, TOMTOM_A_MICB_3_CTL, 0x60,
(pdata->micbias.bias3_cfilt_sel << 5));
snd_soc_update_bits(codec, tomtom->resmgr.reg_addr->micb_4_ctl, 0x60,
(pdata->micbias.bias4_cfilt_sel << 5));
for (i = 0; i < 6; j++, i += 2) {
if (flag & (0x01 << i)) {
val_txfe = (txfe_bypass & (0x01 << i)) ? 0x20 : 0x00;
val_txfe = val_txfe |
((txfe_buff & (0x01 << i)) ? 0x10 : 0x00);
snd_soc_update_bits(codec,
TOMTOM_A_TX_1_2_TEST_EN + j * 10,
0x30, val_txfe);
}
if (flag & (0x01 << (i + 1))) {
val_txfe = (txfe_bypass &
(0x01 << (i + 1))) ? 0x02 : 0x00;
val_txfe |= (txfe_buff &
(0x01 << (i + 1))) ? 0x01 : 0x00;
snd_soc_update_bits(codec,
TOMTOM_A_TX_1_2_TEST_EN + j * 10,
0x03, val_txfe);
}
}
if (flag & 0x40) {
value = (leg_mode & 0x40) ? 0x10 : 0x00;
value = value | ((txfe_bypass & 0x40) ? 0x02 : 0x00);
value = value | ((txfe_buff & 0x40) ? 0x01 : 0x00);
snd_soc_update_bits(codec, TOMTOM_A_TX_7_MBHC_EN,
0x13, value);
}
if (pdata->ocp.use_pdata) {
/* not defined in CODEC specification */
if (pdata->ocp.hph_ocp_limit == 1 ||
pdata->ocp.hph_ocp_limit == 5) {
rc = -EINVAL;
goto done;
}
snd_soc_update_bits(codec, TOMTOM_A_RX_COM_OCP_CTL,
0x0F, pdata->ocp.num_attempts);
snd_soc_write(codec, TOMTOM_A_RX_COM_OCP_COUNT,
((pdata->ocp.run_time << 4) | pdata->ocp.wait_time));
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_OCP_CTL,
0xE0, (pdata->ocp.hph_ocp_limit << 5));
}
for (i = 0; i < ARRAY_SIZE(pdata->regulator); i++) {
if (pdata->regulator[i].name &&
!strcmp(pdata->regulator[i].name, "CDC_VDDA_RX")) {
if (pdata->regulator[i].min_uV == 1800000 &&
pdata->regulator[i].max_uV == 1800000) {
snd_soc_write(codec, TOMTOM_A_BIAS_REF_CTL,
0x1C);
} else if (pdata->regulator[i].min_uV == 2200000 &&
pdata->regulator[i].max_uV == 2200000) {
snd_soc_write(codec, TOMTOM_A_BIAS_REF_CTL,
0x1E);
} else {
pr_err("%s: unsupported CDC_VDDA_RX voltage\n"
"min %d, max %d\n", __func__,
pdata->regulator[i].min_uV,
pdata->regulator[i].max_uV);
rc = -EINVAL;
}
break;
}
}
/* Set micbias capless mode with tail current */
value = (pdata->micbias.bias1_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x16);
snd_soc_update_bits(codec, TOMTOM_A_MICB_1_CTL, 0x1E, value);
value = (pdata->micbias.bias2_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x16);
snd_soc_update_bits(codec, TOMTOM_A_MICB_2_CTL, 0x1E, value);
value = (pdata->micbias.bias3_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x16);
snd_soc_update_bits(codec, TOMTOM_A_MICB_3_CTL, 0x1E, value);
value = (pdata->micbias.bias4_cap_mode == MICBIAS_EXT_BYP_CAP ?
0x00 : 0x16);
snd_soc_update_bits(codec, TOMTOM_A_MICB_4_CTL, 0x1E, value);
/* Set the DMIC sample rate */
switch (pdata->mclk_rate) {
case TOMTOM_MCLK_CLK_9P6MHZ:
def_dmic_rate =
WCD9XXX_DMIC_SAMPLE_RATE_4P8MHZ;
break;
case TOMTOM_MCLK_CLK_12P288MHZ:
def_dmic_rate =
WCD9XXX_DMIC_SAMPLE_RATE_4P096MHZ;
break;
default:
/* should never happen */
pr_err("%s: Invalid mclk_rate %d\n",
__func__, pdata->mclk_rate);
rc = -EINVAL;
goto done;
}
if (pdata->dmic_sample_rate ==
WCD9XXX_DMIC_SAMPLE_RATE_UNDEFINED) {
pr_info("%s: dmic_rate invalid default = %d\n",
__func__, def_dmic_rate);
pdata->dmic_sample_rate = def_dmic_rate;
}
if (pdata->mad_dmic_sample_rate ==
WCD9XXX_DMIC_SAMPLE_RATE_UNDEFINED) {
pr_info("%s: mad_dmic_rate invalid default = %d\n",
__func__, def_dmic_rate);
/*
* use dmic_sample_rate as the default for MAD
* if mad dmic sample rate is undefined
*/
pdata->mad_dmic_sample_rate = pdata->dmic_sample_rate;
}
/*
* Default the DMIC clk rates to mad_dmic_sample_rate,
* whereas, the anc/txfe dmic rates to dmic_sample_rate
* since the anc/txfe are independent of mad block.
*/
mad_dmic_ctl_val = tomtom_get_dmic_clk_val(tomtom->codec,
pdata->mclk_rate,
pdata->mad_dmic_sample_rate);
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B1_CTL,
0xE0, mad_dmic_ctl_val << 5);
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B2_CTL,
0x70, mad_dmic_ctl_val << 4);
snd_soc_update_bits(codec, TOMTOM_A_DMIC_B2_CTL,
0x0E, mad_dmic_ctl_val << 1);
dmic_ctl_val = tomtom_get_dmic_clk_val(tomtom->codec,
pdata->mclk_rate,
pdata->dmic_sample_rate);
if (dmic_ctl_val == WCD9330_DMIC_CLK_DIV_2)
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_ON;
else
anc_ctl_value = WCD9XXX_ANC_DMIC_X2_OFF;
for (dec = 0; dec < NUM_DECIMATORS; dec++) {
tx_dmic_ctl_reg =
TOMTOM_A_CDC_TX1_DMIC_CTL + (8 * dec);
snd_soc_update_bits(codec, tx_dmic_ctl_reg,
0x07, dmic_ctl_val);
}
snd_soc_update_bits(codec, TOMTOM_A_CDC_ANC1_B2_CTL,
0x1, anc_ctl_value);
snd_soc_update_bits(codec, TOMTOM_A_CDC_ANC2_B2_CTL,
0x1, anc_ctl_value);
done:
return rc;
}
static const struct wcd9xxx_reg_mask_val tomtom_reg_defaults[] = {
/* set MCLk to 9.6 */
TOMTOM_REG_VAL(TOMTOM_A_CHIP_CTL, 0x02),
/* EAR PA deafults */
TOMTOM_REG_VAL(TOMTOM_A_RX_EAR_CMBUFF, 0x05),
/* RX deafults */
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX1_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX2_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX3_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX4_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX5_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX6_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX7_B5_CTL, 0x79),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX8_B5_CTL, 0x79),
/* RX1 and RX2 defaults */
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX1_B6_CTL, 0xA0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX2_B6_CTL, 0xA0),
/* RX3 to RX7 defaults */
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX3_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX4_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX5_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX6_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX7_B6_CTL, 0x80),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX8_B6_CTL, 0x80),
/* MAD registers */
TOMTOM_REG_VAL(TOMTOM_A_MAD_ANA_CTRL, 0xF1),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_MAIN_CTL_1, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_MAIN_CTL_2, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_1, 0x00),
/* Set SAMPLE_TX_EN bit */
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_2, 0x03),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_3, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_4, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_5, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_6, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_7, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_CTL_8, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_IIR_CTL_PTR, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_AUDIO_IIR_CTL_VAL, 0x40),
TOMTOM_REG_VAL(TOMTOM_A_CDC_DEBUG_B7_CTL, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_CLK_OTHR_RESET_B1_CTL, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_CLK_OTHR_CTL, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_INP_SEL, 0x01),
/* Set HPH Path to low power mode */
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_BIAS_PA, 0x57),
/* BUCK default */
TOMTOM_REG_VAL(TOMTOM_A_BUCK_CTRL_CCL_4, 0x51),
TOMTOM_REG_VAL(TOMTOM_A_BUCK_CTRL_CCL_1, 0x5B),
};
/*
* Don't update TOMTOM_A_CHIP_CTL, TOMTOM_A_BUCK_CTRL_CCL_1 and
* TOMTOM_A_RX_EAR_CMBUFF as those are updated in tomtom_reg_defaults
*/
static const struct wcd9xxx_reg_mask_val tomtom_1_0_reg_defaults[] = {
TOMTOM_REG_VAL(TOMTOM_A_TX_1_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_2_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_1_2_ADC_IB, 0x44),
TOMTOM_REG_VAL(TOMTOM_A_TX_3_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_4_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_3_4_ADC_IB, 0x44),
TOMTOM_REG_VAL(TOMTOM_A_TX_5_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_6_GAIN, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_TX_5_6_ADC_IB, 0x44),
TOMTOM_REG_VAL(WCD9XXX_A_BUCK_MODE_3, 0xCE),
TOMTOM_REG_VAL(WCD9XXX_A_BUCK_CTRL_VCL_1, 0x8),
TOMTOM_REG_VAL(TOMTOM_A_BUCK_CTRL_CCL_4, 0x51),
TOMTOM_REG_VAL(TOMTOM_A_NCP_DTEST, 0x10),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_CHOP_CTL, 0xA4),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_OCP_CTL, 0x69),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_CNP_WG_CTL, 0xDA),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_CNP_WG_TIME, 0x15),
TOMTOM_REG_VAL(TOMTOM_A_RX_EAR_BIAS_PA, 0x76),
TOMTOM_REG_VAL(TOMTOM_A_RX_EAR_CNP, 0xC0),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_BIAS_PA, 0x78),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_1_TEST, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_2_TEST, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_3_TEST, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_RX_LINE_4_TEST, 0x2),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV1_OCP_CTL, 0x97),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV1_CLIP_DET, 0x1),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV1_IEC, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV2_OCP_CTL, 0x97),
TOMTOM_REG_VAL(TOMTOM_A_SPKR_DRV2_CLIP_DET, 0x1),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX1_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX2_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX3_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX4_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX5_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX6_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX7_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX8_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX9_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX10_MUX_CTL, 0x4A),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX1_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX2_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX3_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX4_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX5_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX6_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX7_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX8_B4_CTL, 0xB),
TOMTOM_REG_VAL(TOMTOM_A_CDC_VBAT_GAIN_UPD_MON, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_PA_RAMP_B1_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_PA_RAMP_B2_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_PA_RAMP_B3_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_PA_RAMP_B4_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_SPKR_CLIPDET_B1_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_SPKR2_CLIPDET_B1_CTL, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_COMP0_B4_CTL, 0x37),
TOMTOM_REG_VAL(TOMTOM_A_CDC_COMP0_B5_CTL, 0x7f),
TOMTOM_REG_VAL(TOMTOM_A_CDC_COMP0_B5_CTL, 0x7f),
};
static const struct wcd9xxx_reg_mask_val tomtom_2_0_reg_defaults[] = {
TOMTOM_REG_VAL(TOMTOM_A_CDC_MAD_MAIN_CTL_2, 0x32),
TOMTOM_REG_VAL(TOMTOM_A_RCO_CTRL, 0x10),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_L_TEST, 0x0A),
TOMTOM_REG_VAL(TOMTOM_A_RX_HPH_R_TEST, 0x0A),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE0, 0xC3),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_DATA0, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX_I2S_SCK_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX_I2S_WS_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX_I2S_SCK_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX_I2S_WS_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE1, 0xE0),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE2, 0x03),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTCK_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTDI_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTMS_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTDO_MODE, 0x04),
TOMTOM_REG_VAL(TOMTOM_A_CDC_JTRST_MODE, 0x04),
};
static const struct wcd9xxx_reg_mask_val tomtom_2_0_reg_i2c_defaults[] = {
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE0, 0x00),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX_I2S_SCK_MODE, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_TX_I2S_WS_MODE, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX_I2S_SCK_MODE, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_CDC_RX_I2S_WS_MODE, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE1, 0x0),
TOMTOM_REG_VAL(TOMTOM_A_PIN_CTL_OE2, 0x0),
};
static void tomtom_update_reg_defaults(struct snd_soc_codec *codec)
{
u32 i;
struct wcd9xxx *tomtom_core = dev_get_drvdata(codec->dev->parent);
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
for (i = 0; i < ARRAY_SIZE(tomtom_reg_defaults); i++)
snd_soc_write(codec, tomtom_reg_defaults[i].reg,
tomtom_reg_defaults[i].val);
for (i = 0; i < ARRAY_SIZE(tomtom_1_0_reg_defaults); i++)
snd_soc_write(codec, tomtom_1_0_reg_defaults[i].reg,
tomtom_1_0_reg_defaults[i].val);
if (!TOMTOM_IS_1_0(tomtom_core->version)) {
for (i = 0; i < ARRAY_SIZE(tomtom_2_0_reg_defaults); i++)
snd_soc_write(codec, tomtom_2_0_reg_defaults[i].reg,
tomtom_2_0_reg_defaults[i].val);
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
for (i = 0; i < ARRAY_SIZE(tomtom_2_0_reg_i2c_defaults);
i++)
snd_soc_write(codec,
tomtom_2_0_reg_i2c_defaults[i].reg,
tomtom_2_0_reg_i2c_defaults[i].val);
}
}
}
static const struct wcd9xxx_reg_mask_val tomtom_codec_reg_init_val[] = {
/* Initialize current threshold to 350MA
* number of wait and run cycles to 4096
*/
{TOMTOM_A_RX_HPH_OCP_CTL, 0xE1, 0x61},
{TOMTOM_A_RX_COM_OCP_COUNT, 0xFF, 0xFF},
{TOMTOM_A_RX_HPH_L_TEST, 0x01, 0x01},
{TOMTOM_A_RX_HPH_R_TEST, 0x01, 0x01},
/* Initialize gain registers to use register gain */
{TOMTOM_A_RX_HPH_L_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_HPH_R_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_LINE_1_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_LINE_2_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_LINE_3_GAIN, 0x20, 0x20},
{TOMTOM_A_RX_LINE_4_GAIN, 0x20, 0x20},
{TOMTOM_A_SPKR_DRV1_GAIN, 0x04, 0x04},
{TOMTOM_A_SPKR_DRV2_GAIN, 0x04, 0x04},
/* Use 16 bit sample size for TX1 to TX6 */
{TOMTOM_A_CDC_CONN_TX_SB_B1_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B2_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B3_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B4_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B5_CTL, 0x30, 0x20},
{TOMTOM_A_CDC_CONN_TX_SB_B6_CTL, 0x30, 0x20},
/* Use 16 bit sample size for TX7 to TX10 */
{TOMTOM_A_CDC_CONN_TX_SB_B7_CTL, 0x60, 0x40},
{TOMTOM_A_CDC_CONN_TX_SB_B8_CTL, 0x60, 0x40},
{TOMTOM_A_CDC_CONN_TX_SB_B9_CTL, 0x60, 0x40},
{TOMTOM_A_CDC_CONN_TX_SB_B10_CTL, 0x60, 0x40},
/*enable HPF filter for TX paths */
{TOMTOM_A_CDC_TX1_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX2_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX3_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX4_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX5_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX6_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX7_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX8_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX9_MUX_CTL, 0x8, 0x0},
{TOMTOM_A_CDC_TX10_MUX_CTL, 0x8, 0x0},
/* Compander zone selection */
{TOMTOM_A_CDC_COMP0_B4_CTL, 0x3F, 0x37},
{TOMTOM_A_CDC_COMP1_B4_CTL, 0x3F, 0x37},
{TOMTOM_A_CDC_COMP2_B4_CTL, 0x3F, 0x37},
{TOMTOM_A_CDC_COMP0_B5_CTL, 0x7F, 0x7F},
{TOMTOM_A_CDC_COMP1_B5_CTL, 0x7F, 0x7F},
{TOMTOM_A_CDC_COMP2_B5_CTL, 0x7F, 0x7F},
/*
* Setup wavegen timer to 20msec and disable chopper
* as default. This corresponds to Compander OFF
*/
{TOMTOM_A_RX_HPH_CNP_WG_CTL, 0xFF, 0xDB},
{TOMTOM_A_RX_HPH_CNP_WG_TIME, 0xFF, 0x58},
{TOMTOM_A_RX_HPH_BIAS_WG_OCP, 0xFF, 0x1A},
{TOMTOM_A_RX_HPH_CHOP_CTL, 0xFF, 0x24},
/* Choose max non-overlap time for NCP */
{TOMTOM_A_NCP_CLK, 0xFF, 0xFC},
/* Program the 0.85 volt VBG_REFERENCE */
{TOMTOM_A_BIAS_CURR_CTL_2, 0xFF, 0x04},
/* set MAD input MIC to DMIC1 */
{TOMTOM_A_CDC_MAD_INP_SEL, 0x0F, 0x08},
{TOMTOM_A_INTR_MODE, 0x04, 0x04},
};
static const struct wcd9xxx_reg_mask_val tomtom_codec_2_0_reg_init_val[] = {
{TOMTOM_A_RX_HPH_L_TEST, 0x08, 0x00},
{TOMTOM_A_RX_HPH_R_TEST, 0x08, 0x00},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR_MIN_CLIP_THRESHOLD, 0xFF, 0x00},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR2_MIN_CLIP_THRESHOLD, 0xFF, 0x00},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR_BOOST_GATING, 0x01, 0x01},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR2_BOOST_GATING, 0x01, 0x01},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR_B1_CTL, 0x01, 0x00},
{TOMTOM_A_CDC_CLIP_ADJ_SPKR2_B1_CTL, 0x01, 0x00},
};
static void tomtom_codec_init_reg(struct snd_soc_codec *codec)
{
u32 i;
struct wcd9xxx *tomtom_core = dev_get_drvdata(codec->dev->parent);
for (i = 0; i < ARRAY_SIZE(tomtom_codec_reg_init_val); i++)
snd_soc_update_bits(codec, tomtom_codec_reg_init_val[i].reg,
tomtom_codec_reg_init_val[i].mask,
tomtom_codec_reg_init_val[i].val);
if (!TOMTOM_IS_1_0(tomtom_core->version)) {
for (i = 0; i < ARRAY_SIZE(tomtom_codec_2_0_reg_init_val); i++)
snd_soc_update_bits(codec,
tomtom_codec_2_0_reg_init_val[i].reg,
tomtom_codec_2_0_reg_init_val[i].mask,
tomtom_codec_2_0_reg_init_val[i].val);
}
}
static void tomtom_slim_interface_init_reg(struct snd_soc_codec *codec)
{
int i;
for (i = 0; i < WCD9XXX_SLIM_NUM_PORT_REG; i++)
wcd9xxx_interface_reg_write(codec->control_data,
TOMTOM_SLIM_PGD_PORT_INT_EN0 + i,
0xFF);
}
static int tomtom_setup_irqs(struct tomtom_priv *tomtom)
{
int ret = 0;
struct snd_soc_codec *codec = tomtom->codec;
struct wcd9xxx *wcd9xxx = codec->control_data;
struct wcd9xxx_core_resource *core_res =
&wcd9xxx->core_res;
ret = wcd9xxx_request_irq(core_res, WCD9XXX_IRQ_SLIMBUS,
tomtom_slimbus_irq, "SLIMBUS Slave", tomtom);
if (ret)
pr_err("%s: Failed to request irq %d\n", __func__,
WCD9XXX_IRQ_SLIMBUS);
else
tomtom_slim_interface_init_reg(codec);
return ret;
}
static void tomtom_cleanup_irqs(struct tomtom_priv *tomtom)
{
struct snd_soc_codec *codec = tomtom->codec;
struct wcd9xxx *wcd9xxx = codec->control_data;
struct wcd9xxx_core_resource *core_res =
&wcd9xxx->core_res;
wcd9xxx_free_irq(core_res, WCD9XXX_IRQ_SLIMBUS, tomtom);
}
static
struct firmware_cal *tomtom_get_hwdep_fw_cal(struct snd_soc_codec *codec,
enum wcd_cal_type type)
{
struct tomtom_priv *tomtom;
struct firmware_cal *hwdep_cal;
if (!codec) {
pr_err("%s: NULL codec pointer\n", __func__);
return NULL;
}
tomtom = snd_soc_codec_get_drvdata(codec);
hwdep_cal = wcdcal_get_fw_cal(tomtom->fw_data, type);
if (!hwdep_cal) {
dev_err(codec->dev, "%s: cal not sent by %d\n",
__func__, type);
return NULL;
} else {
return hwdep_cal;
}
}
int tomtom_hs_detect(struct snd_soc_codec *codec,
struct wcd9xxx_mbhc_config *mbhc_cfg)
{
int rc;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
if (mbhc_cfg->insert_detect) {
rc = wcd9xxx_mbhc_start(&tomtom->mbhc, mbhc_cfg);
if (!rc)
tomtom->mbhc_started = true;
} else {
/* MBHC is disabled, so disable Auto pulldown */
snd_soc_update_bits(codec, TOMTOM_A_MBHC_INSERT_DETECT2, 0xC0,
0x00);
snd_soc_update_bits(codec, TOMTOM_A_MICB_CFILT_2_CTL, 0x01,
0x00);
tomtom->mbhc.mbhc_cfg = NULL;
tomtom->mbhc_started = false;
rc = 0;
}
wcd9xxx_clsh_post_init(&tomtom->clsh_d, tomtom->mbhc_started);
return rc;
}
EXPORT_SYMBOL(tomtom_hs_detect);
void tomtom_hs_detect_exit(struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
wcd9xxx_mbhc_stop(&tomtom->mbhc);
tomtom->mbhc_started = false;
}
EXPORT_SYMBOL(tomtom_hs_detect_exit);
void tomtom_event_register(
int (*machine_event_cb)(struct snd_soc_codec *codec,
enum wcd9xxx_codec_event),
struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
tomtom->machine_codec_event_cb = machine_event_cb;
}
EXPORT_SYMBOL(tomtom_event_register);
void tomtom_register_ext_clk_cb(
int (*codec_ext_clk_en)(struct snd_soc_codec *codec,
int enable, bool dapm),
int (*get_ext_clk_cnt) (void),
struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
tomtom->codec_ext_clk_en_cb = codec_ext_clk_en;
tomtom->codec_get_ext_clk_cnt = get_ext_clk_cnt;
}
EXPORT_SYMBOL(tomtom_register_ext_clk_cb);
static void tomtom_init_slim_slave_cfg(struct snd_soc_codec *codec)
{
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
struct afe_param_cdc_slimbus_slave_cfg *cfg;
struct wcd9xxx *wcd9xxx = codec->control_data;
uint64_t eaddr = 0;
cfg = &priv->slimbus_slave_cfg;
cfg->minor_version = 1;
cfg->tx_slave_port_offset = 0;
cfg->rx_slave_port_offset = 16;
memcpy(&eaddr, &wcd9xxx->slim->e_addr, sizeof(wcd9xxx->slim->e_addr));
WARN_ON(sizeof(wcd9xxx->slim->e_addr) != 6);
cfg->device_enum_addr_lsw = eaddr & 0xFFFFFFFF;
cfg->device_enum_addr_msw = eaddr >> 32;
pr_debug("%s: slimbus logical address 0x%llx\n", __func__, eaddr);
}
static int tomtom_device_down(struct wcd9xxx *wcd9xxx)
{
int count;
struct snd_soc_codec *codec;
struct tomtom_priv *priv;
codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv);
priv = snd_soc_codec_get_drvdata(codec);
wcd_cpe_ssr_event(priv->cpe_core, WCD_CPE_BUS_DOWN_EVENT);
snd_soc_card_change_online_state(codec->card, 0);
set_bit(BUS_DOWN, &priv->status_mask);
for (count = 0; count < NUM_CODEC_DAIS; count++)
priv->dai[count].bus_down_in_recovery = true;
return 0;
}
static int wcd9xxx_prepare_static_pa(struct wcd9xxx_mbhc *mbhc,
struct list_head *lh)
{
int i;
struct snd_soc_codec *codec = mbhc->codec;
u32 delay;
const struct wcd9xxx_reg_mask_val reg_set_paon[] = {
{TOMTOM_A_TX_COM_BIAS, 0xff, 0xF0},
{WCD9XXX_A_CDC_RX1_B6_CTL, 0xff, 0x81},
{WCD9XXX_A_CDC_CLK_RX_B1_CTL, 0x01, 0x01},
{WCD9XXX_A_BUCK_MODE_2, 0xff, 0xEF},
{WCD9XXX_A_BUCK_MODE_2, 0xff, 0xEE},
{TOMTOM_A_NCP_DTEST, 0xff, 0x20},
{WCD9XXX_A_CDC_CLK_OTHR_CTL, 0xff, 0x21},
{WCD9XXX_A_CDC_RX2_B6_CTL, 0xff, 0x81},
{WCD9XXX_A_CDC_CLK_RX_B1_CTL, 0x02, 0x02},
{WCD9XXX_A_BUCK_MODE_2, 0xff, 0xAE},
{WCD9XXX_A_BUCK_MODE_2, 0xff, 0xAA},
{WCD9XXX_A_NCP_CLK, 0xff, 0x9C},
{WCD9XXX_A_NCP_CLK, 0xff, 0xFC},
{WCD9XXX_A_RX_COM_BIAS, 0xff, 0xA0},
{WCD9XXX_A_BUCK_MODE_3, 0xff, 0xC6},
{WCD9XXX_A_BUCK_MODE_4, 0xff, 0xE6},
{WCD9XXX_A_BUCK_MODE_5, 0xff, 0x02},
{WCD9XXX_A_BUCK_MODE_1, 0xff, 0xA1},
/* Add a delay of 1ms after this reg write */
{WCD9XXX_A_NCP_STATIC, 0xff, 0x28},
{WCD9XXX_A_NCP_EN, 0xff, 0xFF},
/* Add a delay of 1ms after this reg write */
/* set HPHL */
{WCD9XXX_A_RX_HPH_L_TEST, 0xff, 0x00},
{TOMTOM_A_RX_HPH_L_PA_CTL, 0xff, 0x42},
{TOMTOM_A_RX_HPH_BIAS_LDO, 0xff, 0x8C},
{TOMTOM_A_RX_HPH_CHOP_CTL, 0xff, 0xA4},
{WCD9XXX_A_RX_HPH_L_GAIN, 0xff, 0xE0},
{WCD9XXX_A_RX_HPH_L_GAIN, 0xff, 0xEC},
/* set HPHR */
{WCD9XXX_A_RX_HPH_R_TEST, 0xff, 0x00},
{TOMTOM_A_RX_HPH_R_PA_CTL, 0xff, 0x42},
{WCD9XXX_A_RX_HPH_R_GAIN, 0xff, 0x20},
{WCD9XXX_A_RX_HPH_R_GAIN, 0xff, 0x2C},
/* set HPH PAs */
{WCD9XXX_A_RX_HPH_BIAS_WG_OCP, 0xff, 0x2A},
{WCD9XXX_A_RX_HPH_CNP_WG_CTL, 0xff, 0xDA},
{WCD9XXX_A_RX_HPH_CNP_WG_TIME, 0xff, 0x15},
{WCD9XXX_A_CDC_CLSH_B1_CTL, 0xff, 0xE6},
{WCD9XXX_A_RX_HPH_L_DAC_CTL, 0xff, 0x40},
{WCD9XXX_A_RX_HPH_L_DAC_CTL, 0xff, 0xC0},
{WCD9XXX_A_RX_HPH_R_DAC_CTL, 0xff, 0x40},
{WCD9XXX_A_RX_HPH_R_DAC_CTL, 0xff, 0xC0},
{TOMTOM_A_RX_HPH_L_ATEST, 0xff, 0x00},
{TOMTOM_A_RX_HPH_R_ATEST, 0xff, 0x00},
};
for (i = 0; i < ARRAY_SIZE(reg_set_paon); i++) {
/*
* Some of the codec registers like BUCK_MODE_1
* and NCP_EN requires 1ms wait time for them
* to take effect. Other register writes for
* PA configuration do not require any wait time.
*/
if (reg_set_paon[i].reg == WCD9XXX_A_BUCK_MODE_1 ||
reg_set_paon[i].reg == WCD9XXX_A_NCP_EN)
delay = 1000;
else
delay = 0;
wcd9xxx_soc_update_bits_push(codec, lh,
reg_set_paon[i].reg,
reg_set_paon[i].mask,
reg_set_paon[i].val, delay);
}
pr_debug("%s: PAs are prepared\n", __func__);
return 0;
}
static int wcd9xxx_enable_static_pa(struct wcd9xxx_mbhc *mbhc, bool enable,
u8 hph_pa)
{
struct snd_soc_codec *codec = mbhc->codec;
const int wg_time = snd_soc_read(codec, WCD9XXX_A_RX_HPH_CNP_WG_TIME) *
TOMTOM_WG_TIME_FACTOR_US;
u8 mask = (hph_pa << 4);
u8 pa_en = enable ? mask : ~mask;
snd_soc_update_bits(codec, WCD9XXX_A_RX_HPH_CNP_EN, mask, pa_en);
/* Wait for wave gen time to avoid pop noise */
usleep_range(wg_time, wg_time + WCD9XXX_USLEEP_RANGE_MARGIN_US);
pr_debug("%s: PAs are %s as static mode (wg_time %d)\n", __func__,
enable ? "enabled" : "disabled", wg_time);
return 0;
}
static int tomtom_setup_zdet(struct wcd9xxx_mbhc *mbhc,
enum mbhc_impedance_detect_stages stage)
{
int ret = 0;
struct snd_soc_codec *codec = mbhc->codec;
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
#define __wr(reg, mask, value) \
do { \
ret = wcd9xxx_soc_update_bits_push(codec, \
&tomtom->reg_save_restore, \
reg, mask, value, 0); \
if (ret < 0) \
return ret; \
} while (0)
switch (stage) {
case MBHC_ZDET_PRE_MEASURE:
INIT_LIST_HEAD(&tomtom->reg_save_restore);
wcd9xxx_prepare_static_pa(mbhc, &tomtom->reg_save_restore);
/* Set HPH_MBHC for zdet */
__wr(WCD9XXX_A_MBHC_HPH, 0xff, 0xC4);
usleep_range(10, 10 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
wcd9xxx_enable_static_pa(mbhc, HPH_PA_ENABLE, HPH_PA_L_R);
/* save old value of registers and write the new value */
__wr(WCD9XXX_A_RX_HPH_OCP_CTL, 0xff, 0x69);
__wr(WCD9XXX_A_CDC_RX1_B6_CTL, 0xff, 0x80);
__wr(WCD9XXX_A_CDC_RX2_B6_CTL, 0xff, 0x80);
/* Enable MBHC MUX, Set MUX current to 37.5uA and ADC7 */
__wr(WCD9XXX_A_MBHC_SCALING_MUX_1, 0xff, 0xC0);
__wr(WCD9XXX_A_MBHC_SCALING_MUX_2, 0xff, 0xF0);
__wr(TOMTOM_A_TX_7_TXFE_CLKDIV, 0xff, 0x8B);
__wr(WCD9XXX_A_TX_7_MBHC_TEST_CTL, 0xff, 0x78);
__wr(WCD9XXX_A_TX_7_MBHC_EN, 0xff, 0x8C);
__wr(WCD9XXX_A_CDC_MBHC_B1_CTL, 0xff, 0xDC);
/* Reset MBHC and set it up for STA */
__wr(WCD9XXX_A_CDC_MBHC_CLK_CTL, 0xff, 0x0A);
snd_soc_write(codec, WCD9XXX_A_CDC_MBHC_EN_CTL, 0x00);
__wr(WCD9XXX_A_CDC_MBHC_CLK_CTL, 0xff, 0x02);
__wr(WCD9XXX_A_CDC_MBHC_TIMER_B5_CTL, 0xff, 0x80);
__wr(WCD9XXX_A_CDC_MBHC_TIMER_B4_CTL, 0xff, 0x25);
/* Wait for ~50us to let MBHC hardware settle down */
usleep_range(50, 50 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_POST_MEASURE:
/* 0x69 for 105 number of samples for PA RAMP */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x69);
/* Program the PA Ramp to FS_16K, L shift 1 */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL,
0x1 << 4 | 0x6);
/* Reset the PA Ramp */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x1C);
/*
* Connect the PA Ramp to PA chain and release reset with
* keep it connected.
*/
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x1F);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x03);
/* Start the PA ramp on HPH L and R */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x05);
/* Ramp generator takes ~30ms */
usleep_range(TOMTOM_HPH_PA_RAMP_DELAY,
TOMTOM_HPH_PA_RAMP_DELAY +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
/*
* Set the multiplication factor for zdet calculation
* based on the Ramp voltage and Gain used
*/
tomtom->zdet_gain_mul_fact = TOMTOM_ZDET_MUL_FACTOR_1X;
break;
case MBHC_ZDET_GAIN_0:
/* Set Gain at 1x */
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_ATEST, 0x00);
snd_soc_write(codec, TOMTOM_A_RX_HPH_R_ATEST, 0x00);
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_PA_CTL, 0x42);
/* Allow 100us for gain registers to settle */
usleep_range(100,
100 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_GAIN_UPDATE_1X:
/*
* Set the multiplication factor for zdet calculation
* based on the Gain value used
*/
tomtom->zdet_gain_mul_fact = TOMTOM_ZDET_MUL_FACTOR_1X;
break;
case MBHC_ZDET_GAIN_1:
/* Set Gain at 10x */
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_ATEST, 0x10);
snd_soc_write(codec, TOMTOM_A_RX_HPH_R_ATEST, 0x00);
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_PA_CTL, 0x42);
/* Allow 100us for gain registers to settle */
usleep_range(100,
100 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
/*
* Set the multiplication factor for zdet calculation
* based on the Gain value used
*/
tomtom->zdet_gain_mul_fact = TOMTOM_ZDET_MUL_FACTOR_10X;
break;
case MBHC_ZDET_GAIN_2:
/* Set Gain at 100x */
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_ATEST, 0x00);
snd_soc_write(codec, TOMTOM_A_RX_HPH_R_ATEST, 0x10);
snd_soc_write(codec, TOMTOM_A_RX_HPH_L_PA_CTL, 0x43);
/* Allow 100us for gain registers to settle */
usleep_range(100,
100 + WCD9XXX_USLEEP_RANGE_MARGIN_US);
/*
* Set the multiplication factor for zdet calculation
* based on the Gain value used
*/
tomtom->zdet_gain_mul_fact = TOMTOM_ZDET_MUL_FACTOR_100X;
break;
case MBHC_ZDET_RAMP_DISABLE:
/* Ramp HPH L & R back to Zero */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x00);
/* 0x69 for 105 number of samples for PA RAMP */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x69);
/* Program the PA Ramp to FS_16K, L shift 1 */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL,
0x1 << 4 | 0x6);
/* Reset the PA Ramp */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x17);
/*
* Connect the PA Ramp to PA chain and release reset with
* keep it connected.
*/
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x03);
/* Start the PA ramp on HPH L and R */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x0A);
/* Ramp generator takes ~30ms to settle down */
usleep_range(TOMTOM_HPH_PA_RAMP_DELAY,
TOMTOM_HPH_PA_RAMP_DELAY +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_HPHR_RAMP_DISABLE:
/* Ramp HPHR back to Zero */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x69);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL,
0x1 << 4 | 0x6);
/* Reset the PA Ramp */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x17);
/*
* Connect the PA Ramp to PA chain and release reset with
* keep it connected.
*/
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x03);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x08);
/* Ramp generator takes ~30ms to settle down */
usleep_range(TOMTOM_HPH_PA_RAMP_DELAY,
TOMTOM_HPH_PA_RAMP_DELAY +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_HPHL_RAMP_DISABLE:
/* Ramp back to Zero */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x69);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL,
0x1 << 4 | 0x6);
/* Reset the PA Ramp */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x17);
/*
* Connect the PA Ramp to PA chain and release reset with
* keep it connected.
*/
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x03);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x02);
/* Ramp generator takes ~30ms to settle down */
usleep_range(TOMTOM_HPH_PA_RAMP_DELAY,
TOMTOM_HPH_PA_RAMP_DELAY +
WCD9XXX_USLEEP_RANGE_MARGIN_US);
break;
case MBHC_ZDET_HPHR_PA_DISABLE:
/* Disable PA */
wcd9xxx_enable_static_pa(mbhc, HPH_PA_DISABLE, HPH_PA_R);
break;
case MBHC_ZDET_PA_DISABLE:
/* Disable PA */
if (!mbhc->hph_pa_dac_state &&
(!(test_bit(MBHC_EVENT_PA_HPHL, &mbhc->event_state) ||
test_bit(MBHC_EVENT_PA_HPHR, &mbhc->event_state))))
wcd9xxx_enable_static_pa(mbhc, HPH_PA_DISABLE,
HPH_PA_L_R);
else if (!(snd_soc_read(codec, WCD9XXX_A_RX_HPH_CNP_EN) & 0x10))
wcd9xxx_enable_static_pa(mbhc, HPH_PA_ENABLE, HPH_PA_R);
/* Turn off PA ramp generator */
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B1_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B2_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B3_CTL, 0x00);
snd_soc_write(codec, WCD9XXX_A_CDC_PA_RAMP_B4_CTL, 0x00);
/* Restore registers */
wcd9xxx_restore_registers(codec, &tomtom->reg_save_restore);
break;
}
#undef __wr
return ret;
}
/* Calculate final impedance values for HPH left and right based on formulae */
static void tomtom_compute_impedance(struct wcd9xxx_mbhc *mbhc, s16 *l, s16 *r,
uint32_t *zl, uint32_t *zr)
{
s64 zln, zrn;
int zld, zrd;
s64 rl = 0, rr = 0;
struct snd_soc_codec *codec;
struct tomtom_priv *tomtom;
if (!mbhc) {
pr_err("%s: Invalid parameters mbhc = %pK\n",
__func__, mbhc);
return;
}
codec = mbhc->codec;
tomtom = snd_soc_codec_get_drvdata(codec);
if (l && zl) {
zln = (s64) (l[1] - l[0]) * tomtom->zdet_gain_mul_fact;
zld = (l[2] - l[0]);
if (zld)
rl = div_s64(zln, zld);
else
/* If L0 and L2 are same, Z has to be on Zone 3.
* Assign a default value so that atleast the value
* is read again with Ramp-up
*/
rl = TOMTOM_ZDET_ZONE_3_DEFAULT_VAL;
/* 32-bit LSBs are enough to hold Impedance values */
*zl = (u32) rl;
}
if (r && zr) {
zrn = (s64) (r[1] - r[0]) * tomtom->zdet_gain_mul_fact;
zrd = (r[2] - r[0]);
if (zrd)
rr = div_s64(zrn, zrd);
else
/* If R0 and R2 are same, Z has to be on Zone 3.
* Assign a default value so that atleast the value
* is read again with Ramp-up
*/
rr = TOMTOM_ZDET_ZONE_3_DEFAULT_VAL;
/* 32-bit LSBs are enough to hold Impedance values */
*zr = (u32) rr;
}
}
/*
* Calculate error approximation of impedance values for HPH left
* and HPH right based on QFuse values
*/
static void tomtom_zdet_error_approx(struct wcd9xxx_mbhc *mbhc, uint32_t *zl,
uint32_t *zr)
{
struct snd_soc_codec *codec;
struct tomtom_priv *tomtom;
s8 q1_t, q2_t;
s8 q1_m, q2_m;
s8 q1, q2;
u8 div_shift;
int rl_alpha = 0, rr_alpha = 0;
int rl_beta = 0, rr_beta = 0;
u64 rl = 0, rr = 0;
const int mult_factor = TOMTOM_ZDET_ERROR_APPROX_MUL_FACTOR;
const int shift = TOMTOM_ZDET_ERROR_APPROX_SHIFT;
if (!zl || !zr || !mbhc) {
pr_err("%s: Invalid parameters zl = %pK zr = %pK, mbhc = %pK\n",
__func__, zl, zr, mbhc);
return;
}
codec = mbhc->codec;
tomtom = snd_soc_codec_get_drvdata(codec);
if ((tomtom->zdet_gain_mul_fact == TOMTOM_ZDET_MUL_FACTOR_1X) ||
(tomtom->zdet_gain_mul_fact == TOMTOM_ZDET_MUL_FACTOR_10X)) {
q1_t = ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT0) &
0x3) << 0x5);
q1_t |= ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT1) &
0xF8) >> 0x3);
q2_t = ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT1) &
0x7) << 0x4);
q2_t |= ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT2) &
0xF0) >> 0x4);
/* Take out the numeric part of the Qfuse value */
q1_m = q1_t & 0x3F;
q2_m = q2_t & 0x3F;
/* Check the sign part of the Qfuse and adjust value */
q1 = (q1_t & 0x40) ? -q1_m : q1_m;
q2 = (q2_t & 0x40) ? -q2_m : q2_m;
div_shift = 1;
} else {
q1_t = ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT2) &
0xF) << 0x2);
q1_t |= ((snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT3) &
0xC0) >> 0x6);
q2_t = (snd_soc_read(codec, TOMTOM_A_QFUSE_DATA_OUT3) & 0x3F);
/* Take out the numeric part of the Qfuse value */
q1_m = q1_t & 0x1F;
q2_m = q2_t & 0x1F;
/* Check the sign part of the Qfuse and adjust value */
q1 = (q1_t & 0x20) ? -q1_m : q1_m;
q2 = (q2_t & 0x20) ? -q2_m : q2_m;
div_shift = 0;
}
dev_dbg(codec->dev, "%s: qfuse1 = %d, qfuse2 = %d\n",
__func__, q1, q2);
if (!q1 && !q2) {
dev_dbg(codec->dev, "%s: qfuse1 and qfuse2 are 0. Exiting\n",
__func__);
return;
}
/*
* Use multiplication and shift to avoid floating point math
* The Z value is calculated with the below formulae using
* the Qfuse value-
* zl = zl * [1 - {(Q1 / div) / 100}] (Include sign for Q1)
* zr = zr * [1 - {(Q2 / div) / 100}] (Include sign for Q2)
* We multiply by 65536 and shift 16 times to get the approx result
* div = 4 for 1x gain, div = 2 for 10x/100x gain
*/
/* Q1/4 */
rl_alpha = q1 >> div_shift;
rl_alpha = 100 - rl_alpha;
/* {rl_alpha/100} * 65536 */
rl_beta = rl_alpha * mult_factor;
rl = (u64) *zl * rl_beta;
/* rl/65536 */
rl = (u64) rl >> shift;
rr_alpha = q2 >> div_shift;
rr_alpha = 100 - rr_alpha;
rr_beta = rr_alpha * mult_factor;
rr = (u64) *zr * rr_beta;
rr = (u64) rr >> shift;
dev_dbg(codec->dev, "%s: rl = 0x%llx (%lld) \t rr = 0x%llx (%lld)\n",
__func__, rl, rl, rr, rr);
*zl = (u32) rl;
*zr = (u32) rr;
}
static enum wcd9xxx_cdc_type tomtom_get_cdc_type(void)
{
return WCD9XXX_CDC_TYPE_TOMTOM;
}
static bool tomtom_mbhc_ins_rem_status(struct snd_soc_codec *codec)
{
return !(snd_soc_read(codec, WCD9XXX_A_MBHC_INSERT_DET_STATUS) &
(1 << 4));
}
static void tomtom_mbhc_micb_pulldown_ctrl(struct wcd9xxx_mbhc *mbhc,
bool enable)
{
struct snd_soc_codec *codec = mbhc->codec;
if (!enable) {
/* Remove automatic pulldown on micbias */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.cfilt_ctl,
0x01, 0x00);
} else {
/* Enable automatic pulldown on micbias */
snd_soc_update_bits(codec, mbhc->mbhc_bias_regs.cfilt_ctl,
0x01, 0x01);
}
}
static void tomtom_codec_hph_auto_pull_down(struct snd_soc_codec *codec,
bool enable)
{
struct wcd9xxx *tomtom_core = dev_get_drvdata(codec->dev->parent);
if (TOMTOM_IS_1_0(tomtom_core->version))
return;
dev_dbg(codec->dev, "%s: %s auto pull down\n", __func__,
enable ? "enable" : "disable");
if (enable) {
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_L_TEST, 0x08, 0x08);
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_R_TEST, 0x08, 0x08);
} else {
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_L_TEST, 0x08, 0x00);
snd_soc_update_bits(codec, TOMTOM_A_RX_HPH_R_TEST, 0x08, 0x00);
}
}
static int tomtom_codec_enable_ext_mb_source(struct snd_soc_codec *codec,
bool turn_on, bool use_dapm)
{
int ret = 0;
if (!use_dapm)
return ret;
if (turn_on)
ret = snd_soc_dapm_force_enable_pin(&codec->dapm,
"MICBIAS_REGULATOR");
else
ret = snd_soc_dapm_disable_pin(&codec->dapm,
"MICBIAS_REGULATOR");
snd_soc_dapm_sync(&codec->dapm);
if (ret)
dev_err(codec->dev, "%s: Failed to %s external micbias source\n",
__func__, turn_on ? "enable" : "disabled");
else
dev_dbg(codec->dev, "%s: %s external micbias source\n",
__func__, turn_on ? "Enabled" : "Disabled");
return ret;
}
static const struct wcd9xxx_mbhc_cb mbhc_cb = {
.get_cdc_type = tomtom_get_cdc_type,
.setup_zdet = tomtom_setup_zdet,
.compute_impedance = tomtom_compute_impedance,
.zdet_error_approx = tomtom_zdet_error_approx,
.insert_rem_status = tomtom_mbhc_ins_rem_status,
.micbias_pulldown_ctrl = tomtom_mbhc_micb_pulldown_ctrl,
.codec_rco_ctrl = tomtom_codec_internal_rco_ctrl,
.hph_auto_pulldown_ctrl = tomtom_codec_hph_auto_pull_down,
.get_hwdep_fw_cal = tomtom_get_hwdep_fw_cal,
.enable_mb_source = tomtom_codec_enable_ext_mb_source,
};
static const struct wcd9xxx_mbhc_intr cdc_intr_ids = {
.poll_plug_rem = WCD9XXX_IRQ_MBHC_REMOVAL,
.shortavg_complete = WCD9XXX_IRQ_MBHC_SHORT_TERM,
.potential_button_press = WCD9XXX_IRQ_MBHC_PRESS,
.button_release = WCD9XXX_IRQ_MBHC_RELEASE,
.dce_est_complete = WCD9XXX_IRQ_MBHC_POTENTIAL,
.insertion = WCD9XXX_IRQ_MBHC_INSERTION,
.hph_left_ocp = WCD9XXX_IRQ_HPH_PA_OCPL_FAULT,
.hph_right_ocp = WCD9XXX_IRQ_HPH_PA_OCPR_FAULT,
.hs_jack_switch = WCD9330_IRQ_MBHC_JACK_SWITCH,
};
static int tomtom_post_reset_cb(struct wcd9xxx *wcd9xxx)
{
int ret = 0;
struct snd_soc_codec *codec;
struct tomtom_priv *tomtom;
int rco_clk_rate;
codec = (struct snd_soc_codec *)(wcd9xxx->ssr_priv);
tomtom = snd_soc_codec_get_drvdata(codec);
/*
* Delay is needed for settling time
* for the register configuration
*/
msleep(50);
snd_soc_card_change_online_state(codec->card, 1);
clear_bit(BUS_DOWN, &tomtom->status_mask);
mutex_lock(&codec->mutex);
tomtom_update_reg_defaults(codec);
if (wcd9xxx->mclk_rate == TOMTOM_MCLK_CLK_12P288MHZ)
snd_soc_update_bits(codec, TOMTOM_A_CHIP_CTL, 0x06, 0x0);
else if (wcd9xxx->mclk_rate == TOMTOM_MCLK_CLK_9P6MHZ)
snd_soc_update_bits(codec, TOMTOM_A_CHIP_CTL, 0x06, 0x2);
tomtom_codec_init_reg(codec);
codec->cache_sync = true;
snd_soc_cache_sync(codec);
codec->cache_sync = false;
ret = tomtom_handle_pdata(tomtom);
if (IS_ERR_VALUE(ret))
pr_err("%s: bad pdata\n", __func__);
tomtom_init_slim_slave_cfg(codec);
tomtom_slim_interface_init_reg(codec);
wcd_cpe_ssr_event(tomtom->cpe_core, WCD_CPE_BUS_UP_EVENT);
wcd9xxx_resmgr_post_ssr(&tomtom->resmgr);
if (tomtom->mbhc_started) {
wcd9xxx_mbhc_deinit(&tomtom->mbhc);
tomtom->mbhc_started = false;
rco_clk_rate = TOMTOM_MCLK_CLK_9P6MHZ;
ret = wcd9xxx_mbhc_init(&tomtom->mbhc, &tomtom->resmgr, codec,
tomtom_enable_mbhc_micbias,
&mbhc_cb, &cdc_intr_ids,
rco_clk_rate, TOMTOM_ZDET_SUPPORTED);
if (ret)
pr_err("%s: mbhc init failed %d\n", __func__, ret);
else
tomtom_hs_detect(codec, tomtom->mbhc.mbhc_cfg);
}
if (tomtom->machine_codec_event_cb)
tomtom->machine_codec_event_cb(codec,
WCD9XXX_CODEC_EVENT_CODEC_UP);
tomtom_cleanup_irqs(tomtom);
ret = tomtom_setup_irqs(tomtom);
if (ret)
pr_err("%s: Failed to setup irq: %d\n", __func__, ret);
/*
* After SSR, the qfuse sensing is lost.
* Perform qfuse sensing again after SSR
* handling is finished.
*/
tomtom_enable_qfuse_sensing(codec);
mutex_unlock(&codec->mutex);
return ret;
}
void *tomtom_get_afe_config(struct snd_soc_codec *codec,
enum afe_config_type config_type)
{
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
switch (config_type) {
case AFE_SLIMBUS_SLAVE_CONFIG:
return &priv->slimbus_slave_cfg;
case AFE_CDC_REGISTERS_CONFIG:
return &tomtom_audio_reg_cfg;
case AFE_SLIMBUS_SLAVE_PORT_CONFIG:
return &tomtom_slimbus_slave_port_cfg;
case AFE_AANC_VERSION:
return &tomtom_cdc_aanc_version;
case AFE_CLIP_BANK_SEL:
return &clip_bank_sel;
case AFE_CDC_CLIP_REGISTERS_CONFIG:
return &tomtom_clip_reg_cfg;
default:
pr_err("%s: Unknown config_type 0x%x\n", __func__, config_type);
return NULL;
}
}
static struct wcd9xxx_reg_address tomtom_reg_address = {
.micb_4_mbhc = TOMTOM_A_MICB_4_MBHC,
.micb_4_int_rbias = TOMTOM_A_MICB_4_INT_RBIAS,
.micb_4_ctl = TOMTOM_A_MICB_4_CTL,
};
static int wcd9xxx_ssr_register(struct wcd9xxx *control,
int (*device_down_cb)(struct wcd9xxx *wcd9xxx),
int (*device_up_cb)(struct wcd9xxx *wcd9xxx),
void *priv)
{
control->dev_down = device_down_cb;
control->post_reset = device_up_cb;
control->ssr_priv = priv;
return 0;
}
static const struct snd_soc_dapm_widget tomtom_1_dapm_widgets[] = {
SND_SOC_DAPM_ADC_E("ADC1", NULL, TOMTOM_A_TX_1_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC2", NULL, TOMTOM_A_TX_2_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU |
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC3", NULL, TOMTOM_A_TX_3_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC4", NULL, TOMTOM_A_TX_4_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC5", NULL, TOMTOM_A_TX_5_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
SND_SOC_DAPM_ADC_E("ADC6", NULL, TOMTOM_A_TX_6_GAIN, 7, 0,
tomtom_codec_enable_adc,
SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMU |
SND_SOC_DAPM_POST_PMD),
};
static struct regulator *tomtom_codec_find_regulator(struct snd_soc_codec *cdc,
const char *name)
{
int i;
struct wcd9xxx *core = dev_get_drvdata(cdc->dev->parent);
for (i = 0; i < core->num_of_supplies; i++) {
if (core->supplies[i].supply &&
!strcmp(core->supplies[i].supply, name))
return core->supplies[i].consumer;
}
return NULL;
}
static struct wcd_cpe_core *tomtom_codec_get_cpe_core(
struct snd_soc_codec *codec)
{
struct tomtom_priv *priv = snd_soc_codec_get_drvdata(codec);
return priv->cpe_core;
}
static int tomtom_codec_fll_enable(struct snd_soc_codec *codec,
bool enable)
{
struct wcd9xxx *wcd9xxx;
if (!codec || !codec->control_data) {
pr_err("%s: Invalid codec handle, %pK\n",
__func__, codec);
return -EINVAL;
}
wcd9xxx = codec->control_data;
dev_dbg(codec->dev, "%s: %s, mclk_rate = %d\n",
__func__, (enable ? "enable" : "disable"),
wcd9xxx->mclk_rate);
switch (wcd9xxx->mclk_rate) {
case TOMTOM_MCLK_CLK_9P6MHZ:
snd_soc_update_bits(codec, TOMTOM_A_FLL_NREF,
0x1F, 0x15);
snd_soc_update_bits(codec, TOMTOM_A_FLL_KDCO_TUNE,
0x07, 0x06);
snd_soc_write(codec, TOMTOM_A_FLL_LOCK_THRESH, 0xD1);
snd_soc_write(codec, TOMTOM_A_FLL_LOCK_DET_COUNT,
0x40);
break;
case TOMTOM_MCLK_CLK_12P288MHZ:
snd_soc_update_bits(codec, TOMTOM_A_FLL_NREF,
0x1F, 0x11);
snd_soc_update_bits(codec, TOMTOM_A_FLL_KDCO_TUNE,
0x07, 0x05);
snd_soc_write(codec, TOMTOM_A_FLL_LOCK_THRESH, 0xB1);
snd_soc_write(codec, TOMTOM_A_FLL_LOCK_DET_COUNT,
0x40);
break;
}
return 0;
}
static int tomtom_codec_slim_reserve_bw(struct snd_soc_codec *codec,
u32 bw_ops, bool commit)
{
struct wcd9xxx *wcd9xxx;
if (!codec) {
pr_err("%s: Invalid handle to codec\n",
__func__);
return -EINVAL;
}
wcd9xxx = dev_get_drvdata(codec->dev->parent);
if (!wcd9xxx) {
dev_err(codec->dev, "%s: Invalid parent drv_data\n",
__func__);
return -EINVAL;
}
return wcd9xxx_slim_reserve_bw(wcd9xxx, bw_ops, commit);
}
static int tomtom_codec_vote_max_bw(struct snd_soc_codec *codec,
bool vote)
{
u32 bw_ops;
if (vote)
bw_ops = SLIM_BW_CLK_GEAR_9;
else
bw_ops = SLIM_BW_UNVOTE;
return tomtom_codec_slim_reserve_bw(codec,
bw_ops, true);
}
static const struct wcd9xxx_resmgr_cb resmgr_cb = {
.cdc_rco_ctrl = tomtom_codec_internal_rco_ctrl,
};
static int tomtom_cpe_err_irq_control(struct snd_soc_codec *codec,
enum cpe_err_irq_cntl_type cntl_type, u8 *status)
{
switch (cntl_type) {
case CPE_ERR_IRQ_MASK:
snd_soc_update_bits(codec,
TOMTOM_A_SVASS_INT_MASK,
0x3F, 0x3F);
break;
case CPE_ERR_IRQ_UNMASK:
snd_soc_update_bits(codec,
TOMTOM_A_SVASS_INT_MASK,
0x3F, 0x0C);
break;
case CPE_ERR_IRQ_CLEAR:
snd_soc_update_bits(codec,
TOMTOM_A_SVASS_INT_CLR,
0x3F, 0x3F);
break;
case CPE_ERR_IRQ_STATUS:
if (!status)
return -EINVAL;
*status = snd_soc_read(codec,
TOMTOM_A_SVASS_INT_STATUS);
break;
}
return 0;
}
static const struct wcd_cpe_cdc_cb cpe_cb = {
.cdc_clk_en = tomtom_codec_internal_rco_ctrl,
.cpe_clk_en = tomtom_codec_fll_enable,
.lab_cdc_ch_ctl = tomtom_codec_enable_slimtx_mad,
.cdc_ext_clk = tomtom_codec_mclk_enable,
.bus_vote_bw = tomtom_codec_vote_max_bw,
.cpe_err_irq_control = tomtom_cpe_err_irq_control,
};
static struct cpe_svc_init_param cpe_svc_params = {
.version = 0,
.query_freq_plans_cb = NULL,
.change_freq_plan_cb = NULL,
};
static int tomtom_cpe_initialize(struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
struct wcd_cpe_params cpe_params;
memset(&cpe_params, 0,
sizeof(struct wcd_cpe_params));
cpe_params.codec = codec;
cpe_params.get_cpe_core = tomtom_codec_get_cpe_core;
cpe_params.cdc_cb = &cpe_cb;
cpe_params.dbg_mode = cpe_debug_mode;
cpe_params.cdc_major_ver = CPE_SVC_CODEC_TOMTOM;
cpe_params.cdc_minor_ver = CPE_SVC_CODEC_V1P0;
cpe_params.cdc_id = CPE_SVC_CODEC_TOMTOM;
cpe_params.cdc_irq_info.cpe_engine_irq =
WCD9330_IRQ_SVASS_ENGINE;
cpe_params.cdc_irq_info.cpe_err_irq =
WCD9330_IRQ_SVASS_ERR_EXCEPTION;
cpe_params.cdc_irq_info.cpe_fatal_irqs =
TOMTOM_CPE_FATAL_IRQS;
cpe_svc_params.context = codec;
cpe_params.cpe_svc_params = &cpe_svc_params;
tomtom->cpe_core = wcd_cpe_init("cpe", codec,
&cpe_params);
if (IS_ERR_OR_NULL(tomtom->cpe_core)) {
dev_err(codec->dev,
"%s: Failed to enable CPE\n",
__func__);
return -EINVAL;
}
return 0;
}
static int tomtom_codec_probe(struct snd_soc_codec *codec)
{
struct wcd9xxx *control;
struct tomtom_priv *tomtom;
struct wcd9xxx_pdata *pdata;
struct wcd9xxx *wcd9xxx;
struct snd_soc_dapm_context *dapm = &codec->dapm;
int ret = 0;
int i, rco_clk_rate;
void *ptr = NULL;
struct wcd9xxx_core_resource *core_res;
struct clk *wcd_ext_clk = NULL;
codec->control_data = dev_get_drvdata(codec->dev->parent);
control = codec->control_data;
wcd9xxx_ssr_register(control, tomtom_device_down,
tomtom_post_reset_cb, (void *)codec);
dev_info(codec->dev, "%s()\n", __func__);
tomtom = devm_kzalloc(codec->dev, sizeof(struct tomtom_priv),
GFP_KERNEL);
if (!tomtom) {
dev_err(codec->dev, "Failed to allocate private data\n");
return -ENOMEM;
}
for (i = 0; i < NUM_DECIMATORS; i++) {
tx_hpf_work[i].tomtom = tomtom;
tx_hpf_work[i].decimator = i + 1;
tx_hpf_work[i].tx_hpf_bypass = false;
INIT_DELAYED_WORK(&tx_hpf_work[i].dwork,
tx_hpf_corner_freq_callback);
}
snd_soc_codec_set_drvdata(codec, tomtom);
/* codec resmgr module init */
wcd9xxx = codec->control_data;
if (!of_find_property(wcd9xxx->dev->of_node, "clock-names", NULL)) {
dev_dbg(wcd9xxx->dev, "%s: codec not using audio-ext-clk driver\n",
__func__);
} else {
wcd_ext_clk = clk_get(wcd9xxx->dev, "wcd_clk");
if (IS_ERR(wcd_ext_clk)) {
dev_err(codec->dev, "%s: clk get %s failed\n",
__func__, "wcd_ext_clk");
goto err_nomem_slimch;
}
}
tomtom->wcd_ext_clk = wcd_ext_clk;
core_res = &wcd9xxx->core_res;
pdata = dev_get_platdata(codec->dev->parent);
ret = wcd9xxx_resmgr_init(&tomtom->resmgr, codec, core_res, pdata,
&pdata->micbias, &tomtom_reg_address,
&resmgr_cb, WCD9XXX_CDC_TYPE_TOMTOM);
if (ret) {
pr_err("%s: wcd9xxx init failed %d\n", __func__, ret);
goto err_nomem_slimch;
}
tomtom->clsh_d.buck_mv = tomtom_codec_get_buck_mv(codec);
/* TomTom does not support dynamic switching of vdd_cp */
tomtom->clsh_d.is_dynamic_vdd_cp = false;
wcd9xxx_clsh_init(&tomtom->clsh_d, &tomtom->resmgr);
rco_clk_rate = TOMTOM_MCLK_CLK_9P6MHZ;
tomtom->fw_data = kzalloc(sizeof(*(tomtom->fw_data)), GFP_KERNEL);
if (!tomtom->fw_data) {
dev_err(codec->dev, "Failed to allocate fw_data\n");
goto err_nomem_slimch;
}
set_bit(WCD9XXX_ANC_CAL, tomtom->fw_data->cal_bit);
set_bit(WCD9XXX_MAD_CAL, tomtom->fw_data->cal_bit);
set_bit(WCD9XXX_MBHC_CAL, tomtom->fw_data->cal_bit);
ret = wcd_cal_create_hwdep(tomtom->fw_data,
WCD9XXX_CODEC_HWDEP_NODE, codec);
if (ret < 0) {
dev_err(codec->dev, "%s hwdep failed %d\n", __func__, ret);
goto err_hwdep;
}
/* init and start mbhc */
ret = wcd9xxx_mbhc_init(&tomtom->mbhc, &tomtom->resmgr, codec,
tomtom_enable_mbhc_micbias,
&mbhc_cb, &cdc_intr_ids,
rco_clk_rate, TOMTOM_ZDET_SUPPORTED);
if (ret) {
pr_err("%s: mbhc init failed %d\n", __func__, ret);
goto err_hwdep;
}
tomtom->codec = codec;
for (i = 0; i < COMPANDER_MAX; i++) {
tomtom->comp_enabled[i] = 0;
tomtom->comp_fs[i] = COMPANDER_FS_48KHZ;
}
tomtom->intf_type = wcd9xxx_get_intf_type();
tomtom->aux_pga_cnt = 0;
tomtom->aux_l_gain = 0x1F;
tomtom->aux_r_gain = 0x1F;
tomtom->ldo_h_users = 0;
tomtom->micb_2_users = 0;
tomtom->micb_3_users = 0;
tomtom_update_reg_defaults(codec);
pr_debug("%s: MCLK Rate = %x\n", __func__, wcd9xxx->mclk_rate);
if (wcd9xxx->mclk_rate == TOMTOM_MCLK_CLK_12P288MHZ) {
snd_soc_update_bits(codec, TOMTOM_A_CHIP_CTL, 0x06, 0x0);
snd_soc_update_bits(codec, TOMTOM_A_RX_COM_TIMER_DIV,
0x01, 0x01);
} else if (wcd9xxx->mclk_rate == TOMTOM_MCLK_CLK_9P6MHZ)
snd_soc_update_bits(codec, TOMTOM_A_CHIP_CTL, 0x06, 0x2);
tomtom_codec_init_reg(codec);
ret = tomtom_handle_pdata(tomtom);
if (IS_ERR_VALUE(ret)) {
pr_err("%s: bad pdata\n", __func__);
goto err_hwdep;
}
tomtom->spkdrv_reg = tomtom_codec_find_regulator(codec,
WCD9XXX_VDD_SPKDRV_NAME);
tomtom->spkdrv2_reg = tomtom_codec_find_regulator(codec,
WCD9XXX_VDD_SPKDRV2_NAME);
tomtom->micbias_reg = tomtom_codec_find_regulator(codec,
on_demand_supply_name[ON_DEMAND_MICBIAS]);
ptr = kmalloc((sizeof(tomtom_rx_chs) +
sizeof(tomtom_tx_chs)), GFP_KERNEL);
if (!ptr) {
pr_err("%s: no mem for slim chan ctl data\n", __func__);
ret = -ENOMEM;
goto err_hwdep;
}
if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_I2C) {
snd_soc_dapm_new_controls(dapm, tomtom_dapm_i2s_widgets,
ARRAY_SIZE(tomtom_dapm_i2s_widgets));
snd_soc_dapm_add_routes(dapm, audio_i2s_map,
ARRAY_SIZE(audio_i2s_map));
for (i = 0; i < ARRAY_SIZE(tomtom_i2s_dai); i++)
INIT_LIST_HEAD(&tomtom->dai[i].wcd9xxx_ch_list);
} else if (tomtom->intf_type == WCD9XXX_INTERFACE_TYPE_SLIMBUS) {
for (i = 0; i < NUM_CODEC_DAIS; i++) {
INIT_LIST_HEAD(&tomtom->dai[i].wcd9xxx_ch_list);
init_waitqueue_head(&tomtom->dai[i].dai_wait);
}
tomtom_slimbus_slave_port_cfg.slave_dev_intfdev_la =
control->slim_slave->laddr;
tomtom_slimbus_slave_port_cfg.slave_dev_pgd_la =
control->slim->laddr;
tomtom_slimbus_slave_port_cfg.slave_port_mapping[0] =
TOMTOM_MAD_SLIMBUS_TX_PORT;
tomtom_init_slim_slave_cfg(codec);
}
snd_soc_dapm_new_controls(dapm, tomtom_1_dapm_widgets,
ARRAY_SIZE(tomtom_1_dapm_widgets));
snd_soc_add_codec_controls(codec,
tomtom_1_x_analog_gain_controls,
ARRAY_SIZE(tomtom_1_x_analog_gain_controls));
snd_soc_add_codec_controls(codec, impedance_detect_controls,
ARRAY_SIZE(impedance_detect_controls));
snd_soc_add_codec_controls(codec, hph_type_detect_controls,
ARRAY_SIZE(hph_type_detect_controls));
control->num_rx_port = TOMTOM_RX_MAX;
control->rx_chs = ptr;
memcpy(control->rx_chs, tomtom_rx_chs, sizeof(tomtom_rx_chs));
control->num_tx_port = TOMTOM_TX_MAX;
control->tx_chs = ptr + sizeof(tomtom_rx_chs);
memcpy(control->tx_chs, tomtom_tx_chs, sizeof(tomtom_tx_chs));
snd_soc_dapm_sync(dapm);
ret = tomtom_setup_irqs(tomtom);
if (ret) {
pr_err("%s: tomtom irq setup failed %d\n", __func__, ret);
goto err_pdata;
}
atomic_set(&kp_tomtom_priv, (unsigned long)tomtom);
mutex_lock(&dapm->codec->mutex);
snd_soc_dapm_disable_pin(dapm, "ANC HPHL");
snd_soc_dapm_disable_pin(dapm, "ANC HPHR");
snd_soc_dapm_disable_pin(dapm, "ANC HEADPHONE");
snd_soc_dapm_disable_pin(dapm, "ANC EAR PA");
snd_soc_dapm_disable_pin(dapm, "ANC EAR");
mutex_unlock(&dapm->codec->mutex);
snd_soc_dapm_sync(dapm);
codec->ignore_pmdown_time = 1;
ret = tomtom_cpe_initialize(codec);
if (ret) {
dev_info(codec->dev,
"%s: cpe initialization failed, ret = %d\n",
__func__, ret);
/* Do not fail probe if CPE failed */
ret = 0;
}
return ret;
err_pdata:
kfree(ptr);
err_hwdep:
kfree(tomtom->fw_data);
err_nomem_slimch:
devm_kfree(codec->dev, tomtom);
return ret;
}
static int tomtom_codec_remove(struct snd_soc_codec *codec)
{
struct tomtom_priv *tomtom = snd_soc_codec_get_drvdata(codec);
WCD9XXX_BG_CLK_LOCK(&tomtom->resmgr);
atomic_set(&kp_tomtom_priv, 0);
WCD9XXX_BG_CLK_UNLOCK(&tomtom->resmgr);
if (tomtom->wcd_ext_clk)
clk_put(tomtom->wcd_ext_clk);
tomtom_cleanup_irqs(tomtom);
/* cleanup MBHC */
wcd9xxx_mbhc_deinit(&tomtom->mbhc);
/* cleanup resmgr */
wcd9xxx_resmgr_deinit(&tomtom->resmgr);
tomtom->spkdrv_reg = NULL;
tomtom->spkdrv2_reg = NULL;
devm_kfree(codec->dev, tomtom);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_tomtom = {
.probe = tomtom_codec_probe,
.remove = tomtom_codec_remove,
.read = tomtom_read,
.write = tomtom_write,
.readable_register = tomtom_readable,
.volatile_register = tomtom_volatile,
.reg_cache_size = TOMTOM_CACHE_SIZE,
.reg_cache_default = tomtom_reset_reg_defaults,
.reg_word_size = 1,
.controls = tomtom_snd_controls,
.num_controls = ARRAY_SIZE(tomtom_snd_controls),
.dapm_widgets = tomtom_dapm_widgets,
.num_dapm_widgets = ARRAY_SIZE(tomtom_dapm_widgets),
.dapm_routes = audio_map,
.num_dapm_routes = ARRAY_SIZE(audio_map),
};
#ifdef CONFIG_PM
static int tomtom_suspend(struct device *dev)
{
dev_dbg(dev, "%s: system suspend\n", __func__);
return 0;
}
static int tomtom_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct tomtom_priv *tomtom = platform_get_drvdata(pdev);
if (!tomtom) {
dev_err(dev, "%s: tomtom private data is NULL\n", __func__);
return -EINVAL;
}
dev_dbg(dev, "%s: system resume\n", __func__);
/* Notify */
wcd9xxx_resmgr_notifier_call(&tomtom->resmgr,
WCD9XXX_EVENT_POST_RESUME);
return 0;
}
static const struct dev_pm_ops tomtom_pm_ops = {
.suspend = tomtom_suspend,
.resume = tomtom_resume,
};
#endif
static int tomtom_probe(struct platform_device *pdev)
{
int ret = 0;
if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_SLIMBUS)
ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tomtom,
tomtom_dai, ARRAY_SIZE(tomtom_dai));
else if (wcd9xxx_get_intf_type() == WCD9XXX_INTERFACE_TYPE_I2C)
ret = snd_soc_register_codec(&pdev->dev, &soc_codec_dev_tomtom,
tomtom_i2s_dai, ARRAY_SIZE(tomtom_i2s_dai));
return ret;
}
static int tomtom_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
static struct platform_driver tomtom_codec_driver = {
.probe = tomtom_probe,
.remove = tomtom_remove,
.driver = {
.name = "tomtom_codec",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &tomtom_pm_ops,
#endif
},
};
static int __init tomtom_codec_init(void)
{
return platform_driver_register(&tomtom_codec_driver);
}
static void __exit tomtom_codec_exit(void)
{
platform_driver_unregister(&tomtom_codec_driver);
}
module_init(tomtom_codec_init);
module_exit(tomtom_codec_exit);
MODULE_DESCRIPTION("TomTom codec driver");
MODULE_LICENSE("GPL v2");
| Java |
function playAudioVisualize(track) {
var bars = 50;
var waveResolution = 128;
var style = "bars"; //set default style upon loading here
var audio = new Audio();
var canvas, source, context, analyser, fFrequencyData, barX, barWidth, barHeight, red, green, blue, ctx;
audio.controls = true;
audio.src = track;
audio.loop = false;
audio.autoplay = false;
window.addEventListener("load", initPlayer, false);
function initPlayer() {
document.getElementById('audio-container').appendChild(audio);
context = new AudioContext();
analyser = context.createAnalyser();
canvas = document.getElementById('audio-display');
canvas.addEventListener("click", toggleStyle);
ctx = canvas.getContext('2d');
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
drawFrames();
function toggleStyle() {
style = (style === "wave" ? "bars" : "wave");
}
}
var k = 0; //keep track of total number of frames drawn
function drawFrames() {
window.requestAnimationFrame(drawFrames);
analyser.fftsize = 128;
fFrequencyData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fFrequencyData);
ctx.clearRect(0,0,canvas.width,canvas.height);
numBarsBars = 16;
//calculate average frequency for color
var total = 0;
for(var j = 0; j < fFrequencyData.length; j++) {
total += fFrequencyData[j];
}
var avg = total / fFrequencyData.length;
avg = avg / 1.2;
//bar style visual representation
function drawBars(numBars) {
for(var i = 0; i < numBars; i++) {
barX = i * (canvas.width / numBars);
barWidth = (canvas.width / numBars - 1);
barHeight = -(fFrequencyData[i] / 2);
//reduce frequency of color changing to avoid flickering
if(k % 15 === 0) {
getColors();
k = 0;
}
ctx.fillStyle = 'rgb('+red+','+green+','+blue+')';
ctx.fillRect(barX, canvas.height, barWidth, barHeight);
}
}
//waveform visualization
function drawWave(resolution, lineWidth) {
ctx.beginPath();
ctx.lineWidth = lineWidth;
var barX, barY;
for(var i = 0; i < resolution; i++) {
barX = i * (Math.ceil(canvas.width / resolution));
barY = -(fFrequencyData[i] / 2);
getColors();
k = 0;
ctx.strokeStyle = 'rgb('+red+','+green+','+blue+')';
ctx.lineTo(barX, barY + canvas.height );
ctx.stroke();
}
}
function getColors() {
//can edit these values to get overall different coloration!!
red = Math.round(Math.sin(avg/29.0 + 6.1) * 127 + 128);
green = Math.round(Math.sin(avg/42.0 - 7.4) * 127 + 128);
blue = Math.round(Math.sin(avg/34.0 - 3.8) * 127 + 128);
}
if(style === "wave") {
drawWave(waveResolution, 2);
}
if(style === "bars") {
drawBars(bars);
}
k++;
}
}
| Java |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="shortcut icon" type="image/x-icon" href="../../../../../../../favicon.ico" />
<title>CircleOptions | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../../../../../assets/css/default.css" rel="stylesheet" type="text/css">
<!-- FULLSCREEN STYLESHEET -->
<link href="../../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../../../../../assets/js/android_3p-bundle.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../../../../../";
var metaTags = [];
var devsite = false;
</script>
<script src="../../../../../../../assets/js/docs.js" type="text/javascript"></script>
<!-- RESOURCES LIBRARY -->
<script src="http://androiddevdocs-staging.appspot.com/ytblogger_lists_unified.js" type="text/javascript"></script>
<script src="../../../../../../../jd_lists_unified.js" type="text/javascript"></script>
<script src="../../../../../../../assets/js/jd_tag_helpers.js" type="text/javascript"></script>
<link href="../../../../../../../assets/css/resourcecards.css" rel="stylesheet" type="text/css" />
<script src="../../../../../../../assets/js/resourcecards.js" type="text/javascript"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5831155-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body class="gc-documentation
develop" itemscope itemtype="http://schema.org/Article">
<div id="doc-api-level" class="" style="display:none"></div>
<a name="top"></a>
<a name="top"></a>
<!-- Header -->
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../../../../../index.html">
<img src="../../../../../../../assets/images/dac_logo.png" width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../../../../../design/index.html"
zh-tw-lang="設計"
zh-cn-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../../../../../develop/index.html"
zh-tw-lang="開發"
zh-cn-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../../../../../distribute/index.html"
zh-tw-lang="發佈"
zh-cn-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<!-- New Search -->
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../../../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<br class="clearfix" />
</div>
<div class="bottom"></div>
</div>
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div>
</div>
<div class="search_filtered_wrapper reference">
<div class="suggest-card reference no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
<div class="search_filtered_wrapper docs">
<div class="suggest-card dummy no-display"> </div>
<div class="suggest-card develop no-display">
<ul class="search_filtered">
</ul>
<div class="child-card guides no-display">
</div>
<div class="child-card training no-display">
</div>
<div class="child-card samples no-display">
</div>
</div>
<div class="suggest-card design no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card distribute no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
</div>
<!-- /New Search>
<!-- Expanded quicknav -->
<div id="quicknav" class="col-9">
<ul>
<li class="design">
<ul>
<li><a href="../../../../../../../design/index.html">Get Started</a></li>
<li><a href="../../../../../../../design/style/index.html">Style</a></li>
<li><a href="../../../../../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../../../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../../../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../../../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
<ul><li><a href="../../../../../../../sdk/index.html">Get the SDK</a></li></ul>
</li>
<li><a href="../../../../../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../../../../../distribute/index.html">Google Play</a></li>
<li><a href="../../../../../../../distribute/googleplay/publish/index.html">Publishing</a></li>
<li><a href="../../../../../../../distribute/googleplay/promote/index.html">Promoting</a></li>
<li><a href="../../../../../../../distribute/googleplay/quality/index.html">App Quality</a></li>
<li><a href="../../../../../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li>
<li><a href="../../../../../../../distribute/open.html">Open Distribution</a></li>
</ul>
</li>
</ul>
</div>
<!-- /Expanded quicknav -->
</div>
</div>
<!-- /Header -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li class="training"><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li class="guide"><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li class="reference"><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li class="tools"><a href="../../../../../../../tools/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li class="google"><a href="../../../../../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav -->
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled"
title="Select your target API level to dim unavailable APIs">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/package-summary.html">com.google.android.gms.ads</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/doubleclick/package-summary.html">com.google.android.gms.ads.doubleclick</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/identifier/package-summary.html">com.google.android.gms.ads.identifier</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/package-summary.html">com.google.android.gms.ads.mediation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/admob/package-summary.html">com.google.android.gms.ads.mediation.admob</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/customevent/package-summary.html">com.google.android.gms.ads.mediation.customevent</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/search/package-summary.html">com.google.android.gms.ads.search</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/package-summary.html">com.google.android.gms.analytics</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appstate/package-summary.html">com.google.android.gms.appstate</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/cast/package-summary.html">com.google.android.gms.cast</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/annotation/package-summary.html">com.google.android.gms.common.annotation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/api/package-summary.html">com.google.android.gms.common.api</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/package-summary.html">com.google.android.gms.drive</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/events/package-summary.html">com.google.android.gms.drive.events</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/metadata/package-summary.html">com.google.android.gms.drive.metadata</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/query/package-summary.html">com.google.android.gms.drive.query</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/widget/package-summary.html">com.google.android.gms.drive.widget</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/package-summary.html">com.google.android.gms.games</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/achievement/package-summary.html">com.google.android.gms.games.achievement</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/leaderboard/package-summary.html">com.google.android.gms.games.leaderboard</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/package-summary.html">com.google.android.gms.games.multiplayer</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/realtime/package-summary.html">com.google.android.gms.games.multiplayer.realtime</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/turnbased/package-summary.html">com.google.android.gms.games.multiplayer.turnbased</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/request/package-summary.html">com.google.android.gms.games.request</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/gcm/package-summary.html">com.google.android.gms.gcm</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/package-summary.html">com.google.android.gms.identity.intents</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/model/package-summary.html">com.google.android.gms.identity.intents.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/location/package-summary.html">com.google.android.gms.location</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li>
<li class="selected api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/tagmanager/package-summary.html">com.google.android.gms.tagmanager</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/package-summary.html">com.google.android.gms.wallet</a></li>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileProvider.html">TileProvider</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/BitmapDescriptor.html">BitmapDescriptor</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/BitmapDescriptorFactory.html">BitmapDescriptorFactory</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CameraPosition.html">CameraPosition</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CameraPosition.Builder.html">CameraPosition.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Circle.html">Circle</a></li>
<li class="selected api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/GroundOverlay.html">GroundOverlay</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/GroundOverlayOptions.html">GroundOverlayOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLngBounds.html">LatLngBounds</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLngBounds.Builder.html">LatLngBounds.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Marker.html">Marker</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/MarkerOptions.html">MarkerOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polygon.html">Polygon</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/PolygonOptions.html">PolygonOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html">Polyline</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/PolylineOptions.html">PolylineOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Tile.html">Tile</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileOverlay.html">TileOverlay</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileOverlayOptions.html">TileOverlayOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/UrlTileProvider.html">UrlTileProvider</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/VisibleRegion.html">VisibleRegion</a></li>
</ul>
</li>
<li><h2>Exceptions</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/RuntimeRemoteException.html">RuntimeRemoteException</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../../../");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<div class="col-12" id="doc-col">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#inhconstants">Inherited Constants</a>
| <a href="#lfields">Fields</a>
| <a href="#pubctors">Ctors</a>
| <a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
final
class
<h1 itemprop="name">CircleOptions</h1>
extends <a href="http://developer.android.com/reference/java/lang/Object.html">Object</a><br/>
implements
<a href="http://developer.android.com/reference/android/os/Parcelable.html">Parcelable</a>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell"><a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a></td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.google.android.gms.maps.model.CircleOptions</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p itemprop="articleBody">Defines options for a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/Circle.html">Circle</a></code>.
<h3>Developer Guide</h3>
<p>
For more information, read the <a
href="https://developers.google.com/maps/documentation/android/shapes">Shapes</a>
developer guide.
</p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<table id="inhconstants" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Constants</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-constants-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-constants-android.os.Parcelable-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>From interface
android.os.Parcelable
<div id="inherited-constants-android.os.Parcelable">
<div id="inherited-constants-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-constants-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol">CONTENTS_FILE_DESCRIPTOR</td>
<td class="jd-descrcol" width="100%"></td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-typecol">int</td>
<td class="jd-linkcol">PARCELABLE_WRITE_RETURN_VALUE</td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
</div>
</div>
</td></tr>
</table>
<!-- =========== FIELD SUMMARY =========== -->
<table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
public
static
final
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptionsCreator.html">CircleOptionsCreator</a></nobr></td>
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#CREATOR">CREATOR</a></td>
<td class="jd-descrcol" width="100%"></td>
</tr>
</table>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#CircleOptions()">CircleOptions</a></span>()</nobr>
<div class="jd-descrdiv">Creates circle options.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#center(com.google.android.gms.maps.model.LatLng)">center</a></span>(<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a> center)</nobr>
<div class="jd-descrdiv">Sets the center using a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#fillColor(int)">fillColor</a></span>(int color)</nobr>
<div class="jd-descrdiv">Sets the fill color.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getCenter()">getCenter</a></span>()</nobr>
<div class="jd-descrdiv">Returns the center as a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getFillColor()">getFillColor</a></span>()</nobr>
<div class="jd-descrdiv">Returns the fill color.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
double</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getRadius()">getRadius</a></span>()</nobr>
<div class="jd-descrdiv">Returns the circle's radius, in meters.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getStrokeColor()">getStrokeColor</a></span>()</nobr>
<div class="jd-descrdiv">Returns the stroke color.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
float</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getStrokeWidth()">getStrokeWidth</a></span>()</nobr>
<div class="jd-descrdiv">Returns the stroke width.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
float</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#getZIndex()">getZIndex</a></span>()</nobr>
<div class="jd-descrdiv">Returns the zIndex.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#isVisible()">isVisible</a></span>()</nobr>
<div class="jd-descrdiv">Checks whether the circle is visible.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#radius(double)">radius</a></span>(double radius)</nobr>
<div class="jd-descrdiv">Sets the radius in meters.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#strokeColor(int)">strokeColor</a></span>(int color)</nobr>
<div class="jd-descrdiv">Sets the stroke color.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#strokeWidth(float)">strokeWidth</a></span>(float width)</nobr>
<div class="jd-descrdiv">Sets the stroke width.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#visible(boolean)">visible</a></span>(boolean visible)</nobr>
<div class="jd-descrdiv">Sets the visibility.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html#zIndex(float)">zIndex</a></span>(float zIndex)</nobr>
<div class="jd-descrdiv">Sets the zIndex.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
<a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a>
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">clone</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">equals</span>(<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a> arg0)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">finalize</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
<a href="http://developer.android.com/reference/java/lang/Class.html">Class</a><?></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">getClass</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">hashCode</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notify</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notifyAll</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/String.html">String</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">toString</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0, int arg1)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-android.os.Parcelable" class="jd-expando-trigger closed"
><img id="inherited-methods-android.os.Parcelable-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From interface
<a href="http://developer.android.com/reference/android/os/Parcelable.html">android.os.Parcelable</a>
<div id="inherited-methods-android.os.Parcelable">
<div id="inherited-methods-android.os.Parcelable-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-android.os.Parcelable-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">describeContents</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
abstract
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">writeToParcel</span>(<a href="http://developer.android.com/reference/android/os/Parcel.html">Parcel</a> arg0, int arg1)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- ========= FIELD DETAIL ======== -->
<h2>Fields</h2>
<A NAME="CREATOR"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
static
final
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptionsCreator.html">CircleOptionsCreator</a>
</span>
CREATOR
</h4>
<div class="api-level">
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2>Public Constructors</h2>
<A NAME="CircleOptions()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">CircleOptions</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Creates circle options.
</p></div>
</div>
</div>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<A NAME="center(com.google.android.gms.maps.model.LatLng)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">center</span>
<span class="normal">(<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a> center)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the center using a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.
<p>The center must not be null.</p>
<p>This method is mandatory because there is no default center.</p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>center</td>
<td>The geographic center as a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="fillColor(int)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">fillColor</span>
<span class="normal">(int color)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the fill color.
<p>The fill color is the color inside the circle, in the integer
format specified by <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code>.
If TRANSPARENT is used then no fill is drawn.
<p>By default the fill color is transparent (<code>0x00000000</code>).</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>color</td>
<td>color in the <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code> format</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="getCenter()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a>
</span>
<span class="sympad">getCenter</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the center as a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The geographic center as a <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>.
</li></ul>
</div>
</div>
</div>
<A NAME="getFillColor()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getFillColor</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the fill color.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The color in the <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code> format.
</li></ul>
</div>
</div>
</div>
<A NAME="getRadius()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
double
</span>
<span class="sympad">getRadius</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the circle's radius, in meters.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The radius in meters.
</li></ul>
</div>
</div>
</div>
<A NAME="getStrokeColor()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getStrokeColor</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the stroke color.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The color in the <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code> format.
</li></ul>
</div>
</div>
</div>
<A NAME="getStrokeWidth()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
float
</span>
<span class="sympad">getStrokeWidth</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the stroke width.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The width in screen pixels.
</li></ul>
</div>
</div>
</div>
<A NAME="getZIndex()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
float
</span>
<span class="sympad">getZIndex</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns the zIndex.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>The zIndex value.
</li></ul>
</div>
</div>
</div>
<A NAME="isVisible()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
boolean
</span>
<span class="sympad">isVisible</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Checks whether the circle is visible.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>True if the circle is visible; false if it is invisible.
</li></ul>
</div>
</div>
</div>
<A NAME="radius(double)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">radius</span>
<span class="normal">(double radius)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the radius in meters.
<p>The radius must be zero or greater. The default radius is zero.</p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>radius</td>
<td>radius in meters</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="strokeColor(int)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">strokeColor</span>
<span class="normal">(int color)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the stroke color.
<p>The stroke color is the color of this circle's outline, in the integer
format specified by <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code>.
If TRANSPARENT is used then no outline is drawn.</p>
<p>By default the stroke color is black (<code>0xff000000</code>).</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>color</td>
<td>color in the <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code> format</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="strokeWidth(float)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">strokeWidth</span>
<span class="normal">(float width)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the stroke width.
<p>The stroke width is the width (in screen pixels) of the circle's
outline. It must be zero or greater. If it is zero then no outline is
drawn.</p>
<p>The default width is 10 pixels.</p></p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>width</td>
<td>width in screen pixels</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="visible(boolean)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">visible</span>
<span class="normal">(boolean visible)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the visibility.
<p>If this circle is not visible then it is not drawn, but all other
state is preserved.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>visible</td>
<td>false to make this circle invisible</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<A NAME="zIndex(float)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a>
</span>
<span class="sympad">zIndex</span>
<span class="normal">(float zIndex)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the zIndex.
<p>Overlays (such as circles) with higher zIndices are drawn above
those with lower indices.
<p>By default the zIndex is 0.0.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>zIndex</td>
<td>zIndex value</td>
</tr>
</table>
</div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></code> object
</li></ul>
</div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<A NAME="navbar_top"></A>
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="../../../../../../../license.html">
Content License</a>.
</div>
<div id="build_info">
Android r —
<script src="../../../../../../../timestamp.js" type="text/javascript"></script>
<script>document.write(BUILD_TIMESTAMP)</script>
</div>
<div id="footerlinks">
<p>
<a href="../../../../../../../about/index.html">About Android</a> |
<a href="../../../../../../../legal.html">Legal</a> |
<a href="../../../../../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
</body>
</html>
| Java |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest10564")
public class BenchmarkTest10564 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.util.Map<String,String[]> map = request.getParameterMap();
String param = "";
if (!map.isEmpty()) {
param = map.get("foo")[0];
}
String bar = new Test().doSomething(param);
Object[] obj = { "a", "b"};
response.getWriter().printf(java.util.Locale.US,bar,obj);
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(1); // condition 'B', which is safe
// Simple case statement that assigns param to bar on conditions 'A' or 'C'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bob";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bob's your uncle";
break;
}
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| Java |
/* Copyright (C) 2007-2013 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
* \author Victor Julien <victor@inliniac.net>
*
* Reference:
* Judy Novak, Steve Sturges: Target-Based TCP Stream Reassembly August, 2007
*
*/
#include "suricata-common.h"
#include "suricata.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "threads.h"
#include "conf.h"
#include "flow-util.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-host-os-info.h"
#include "util-unittest-helper.h"
#include "util-byte.h"
#include "stream-tcp.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "util-debug.h"
#include "app-layer-protos.h"
#include "app-layer.h"
#include "app-layer-events.h"
#include "detect-engine-state.h"
#include "util-profiling.h"
#define PSEUDO_PACKET_PAYLOAD_SIZE 65416 /* 64 Kb minus max IP and TCP header */
#ifdef DEBUG
static SCMutex segment_pool_memuse_mutex;
static uint64_t segment_pool_memuse = 0;
static uint64_t segment_pool_memcnt = 0;
#endif
/* We define several pools with prealloced segments with fixed size
* payloads. We do this to prevent having to do an SCMalloc call for every
* data segment we receive, which would be a large performance penalty.
* The cost is in memory of course. The number of pools and the properties
* of the pools are determined by the yaml. */
static int segment_pool_num = 0;
static Pool **segment_pool = NULL;
static SCMutex *segment_pool_mutex = NULL;
static uint16_t *segment_pool_pktsizes = NULL;
#ifdef DEBUG
static SCMutex segment_pool_cnt_mutex;
static uint64_t segment_pool_cnt = 0;
#endif
/* index to the right pool for all packet sizes. */
static uint16_t segment_pool_idx[65536]; /* O(1) lookups of the pool */
static int check_overlap_different_data = 0;
/* Memory use counter */
SC_ATOMIC_DECLARE(uint64_t, ra_memuse);
/* prototypes */
static int HandleSegmentStartsBeforeListSegment(ThreadVars *, TcpReassemblyThreadCtx *,
TcpStream *, TcpSegment *, TcpSegment *, Packet *);
static int HandleSegmentStartsAtSameListSegment(ThreadVars *, TcpReassemblyThreadCtx *,
TcpStream *, TcpSegment *, TcpSegment *, Packet *);
static int HandleSegmentStartsAfterListSegment(ThreadVars *, TcpReassemblyThreadCtx *,
TcpStream *, TcpSegment *, TcpSegment *, Packet *);
void StreamTcpSegmentDataReplace(TcpSegment *, TcpSegment *, uint32_t, uint16_t);
void StreamTcpSegmentDataCopy(TcpSegment *, TcpSegment *);
TcpSegment* StreamTcpGetSegment(ThreadVars *tv, TcpReassemblyThreadCtx *, uint16_t);
void StreamTcpCreateTestPacket(uint8_t *, uint8_t, uint8_t, uint8_t);
void StreamTcpReassemblePseudoPacketCreate(TcpStream *, Packet *, PacketQueue *);
static int StreamTcpSegmentDataCompare(TcpSegment *dst_seg, TcpSegment *src_seg,
uint32_t start_point, uint16_t len);
void StreamTcpReassembleConfigEnableOverlapCheck(void)
{
check_overlap_different_data = 1;
}
/**
* \brief Function to Increment the memory usage counter for the TCP reassembly
* segments
*
* \param size Size of the TCP segment and its payload length memory allocated
*/
void StreamTcpReassembleIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(ra_memuse, size);
return;
}
/**
* \brief Function to Decrease the memory usage counter for the TCP reassembly
* segments
*
* \param size Size of the TCP segment and its payload length memory allocated
*/
void StreamTcpReassembleDecrMemuse(uint64_t size)
{
(void) SC_ATOMIC_SUB(ra_memuse, size);
return;
}
void StreamTcpReassembleMemuseCounter(ThreadVars *tv, TcpReassemblyThreadCtx *rtv)
{
uint64_t smemuse = SC_ATOMIC_GET(ra_memuse);
if (tv != NULL && rtv != NULL)
SCPerfCounterSetUI64(rtv->counter_tcp_reass_memuse, tv->sc_perf_pca, smemuse);
return;
}
/**
* \brief Function to Check the reassembly memory usage counter against the
* allowed max memory usgae for TCP segments.
*
* \param size Size of the TCP segment and its payload length memory allocated
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpReassembleCheckMemcap(uint32_t size)
{
if (stream_config.reassembly_memcap == 0 ||
(uint64_t)((uint64_t)size + SC_ATOMIC_GET(ra_memuse)) <= stream_config.reassembly_memcap)
return 1;
return 0;
}
/** \brief alloc a tcp segment pool entry */
void *TcpSegmentPoolAlloc()
{
if (StreamTcpReassembleCheckMemcap((uint32_t)sizeof(TcpSegment)) == 0) {
return NULL;
}
TcpSegment *seg = NULL;
seg = SCMalloc(sizeof (TcpSegment));
if (unlikely(seg == NULL))
return NULL;
return seg;
}
int TcpSegmentPoolInit(void *data, void *payload_len)
{
TcpSegment *seg = (TcpSegment *) data;
uint16_t size = *((uint16_t *) payload_len);
/* do this before the can bail, so TcpSegmentPoolCleanup
* won't have uninitialized memory to consider. */
memset(seg, 0, sizeof (TcpSegment));
if (StreamTcpReassembleCheckMemcap((uint32_t)size + (uint32_t)sizeof(TcpSegment)) == 0) {
return 0;
}
seg->pool_size = size;
seg->payload_len = seg->pool_size;
seg->payload = SCMalloc(seg->payload_len);
if (seg->payload == NULL) {
return 0;
}
#ifdef DEBUG
SCMutexLock(&segment_pool_memuse_mutex);
segment_pool_memuse += seg->payload_len;
segment_pool_memcnt++;
SCLogDebug("segment_pool_memcnt %"PRIu64"", segment_pool_memcnt);
SCMutexUnlock(&segment_pool_memuse_mutex);
#endif
StreamTcpReassembleIncrMemuse((uint32_t)seg->pool_size + sizeof(TcpSegment));
return 1;
}
/** \brief clean up a tcp segment pool entry */
void TcpSegmentPoolCleanup(void *ptr)
{
if (ptr == NULL)
return;
TcpSegment *seg = (TcpSegment *) ptr;
StreamTcpReassembleDecrMemuse((uint32_t)seg->pool_size + sizeof(TcpSegment));
#ifdef DEBUG
SCMutexLock(&segment_pool_memuse_mutex);
segment_pool_memuse -= seg->pool_size;
segment_pool_memcnt--;
SCLogDebug("segment_pool_memcnt %"PRIu64"", segment_pool_memcnt);
SCMutexUnlock(&segment_pool_memuse_mutex);
#endif
SCFree(seg->payload);
return;
}
/**
* \brief Function to return the segment back to the pool.
*
* \param seg Segment which will be returned back to the pool.
*/
void StreamTcpSegmentReturntoPool(TcpSegment *seg)
{
if (seg == NULL)
return;
seg->next = NULL;
seg->prev = NULL;
uint16_t idx = segment_pool_idx[seg->pool_size];
SCMutexLock(&segment_pool_mutex[idx]);
PoolReturn(segment_pool[idx], (void *) seg);
SCLogDebug("segment_pool[%"PRIu16"]->empty_stack_size %"PRIu32"",
idx,segment_pool[idx]->empty_stack_size);
SCMutexUnlock(&segment_pool_mutex[idx]);
#ifdef DEBUG
SCMutexLock(&segment_pool_cnt_mutex);
segment_pool_cnt--;
SCMutexUnlock(&segment_pool_cnt_mutex);
#endif
}
/**
* \brief return all segments in this stream into the pool(s)
*
* \param stream the stream to cleanup
*/
void StreamTcpReturnStreamSegments (TcpStream *stream)
{
TcpSegment *seg = stream->seg_list;
TcpSegment *next_seg;
if (seg == NULL)
return;
while (seg != NULL) {
next_seg = seg->next;
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
}
stream->seg_list = NULL;
stream->seg_list_tail = NULL;
}
typedef struct SegmentSizes_
{
uint16_t pktsize;
uint32_t prealloc;
} SegmentSizes;
/* sort small to big */
static int SortByPktsize(const void *a, const void *b)
{
const SegmentSizes *s0 = a;
const SegmentSizes *s1 = b;
return s0->pktsize - s1->pktsize;
}
int StreamTcpReassemblyConfig(char quiet)
{
Pool **my_segment_pool = NULL;
SCMutex *my_segment_lock = NULL;
uint16_t *my_segment_pktsizes = NULL;
SegmentSizes sizes[256];
memset(&sizes, 0x00, sizeof(sizes));
int npools = 0;
ConfNode *segs = ConfGetNode("stream.reassembly.segments");
if (segs != NULL) {
ConfNode *seg;
TAILQ_FOREACH(seg, &segs->head, next) {
ConfNode *segsize = ConfNodeLookupChild(seg,"size");
if (segsize == NULL)
continue;
ConfNode *segpre = ConfNodeLookupChild(seg,"prealloc");
if (segpre == NULL)
continue;
if (npools >= 256) {
SCLogError(SC_ERR_INVALID_ARGUMENT, "too many segment packet "
"pools defined, max is 256");
return -1;
}
SCLogDebug("segsize->val %s", segsize->val);
SCLogDebug("segpre->val %s", segpre->val);
uint16_t pktsize = 0;
if (ByteExtractStringUint16(&pktsize, 10, strlen(segsize->val),
segsize->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "segment packet size "
"of %s is invalid", segsize->val);
return -1;
}
uint32_t prealloc = 0;
if (ByteExtractStringUint32(&prealloc, 10, strlen(segpre->val),
segpre->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "segment prealloc of "
"%s is invalid", segpre->val);
return -1;
}
sizes[npools].pktsize = pktsize;
sizes[npools].prealloc = prealloc;
SCLogDebug("pktsize %u, prealloc %u", sizes[npools].pktsize,
sizes[npools].prealloc);
npools++;
}
}
SCLogDebug("npools %d", npools);
if (npools > 0) {
/* sort the array as the index code below relies on it */
qsort(&sizes, npools, sizeof(sizes[0]), SortByPktsize);
if (sizes[npools - 1].pktsize != 0xffff) {
sizes[npools].pktsize = 0xffff;
sizes[npools].prealloc = 8;
npools++;
SCLogInfo("appended a segment pool for pktsize 65536");
}
} else if (npools == 0) {
/* defaults */
sizes[0].pktsize = 4;
sizes[0].prealloc = 256;
sizes[1].pktsize = 16;
sizes[1].prealloc = 512;
sizes[2].pktsize = 112;
sizes[2].prealloc = 512;
sizes[3].pktsize = 248;
sizes[3].prealloc = 512;
sizes[4].pktsize = 512;
sizes[4].prealloc = 512;
sizes[5].pktsize = 768;
sizes[5].prealloc = 1024;
sizes[6].pktsize = 1448;
sizes[6].prealloc = 1024;
sizes[7].pktsize = 0xffff;
sizes[7].prealloc = 128;
npools = 8;
}
int i = 0;
for (i = 0; i < npools; i++) {
SCLogDebug("pktsize %u, prealloc %u", sizes[i].pktsize, sizes[i].prealloc);
}
my_segment_pool = SCMalloc(npools * sizeof(Pool *));
if (my_segment_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "malloc failed");
return -1;
}
my_segment_lock = SCMalloc(npools * sizeof(SCMutex));
if (my_segment_lock == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "malloc failed");
SCFree(my_segment_pool);
return -1;
}
my_segment_pktsizes = SCMalloc(npools * sizeof(uint16_t));
if (my_segment_pktsizes == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "malloc failed");
SCFree(my_segment_lock);
SCFree(my_segment_pool);
return -1;
}
uint32_t my_segment_poolsizes[npools];
for (i = 0; i < npools; i++) {
my_segment_pktsizes[i] = sizes[i].pktsize;
my_segment_poolsizes[i] = sizes[i].prealloc;
SCMutexInit(&my_segment_lock[i], NULL);
/* setup the pool */
SCMutexLock(&my_segment_lock[i]);
my_segment_pool[i] = PoolInit(0, my_segment_poolsizes[i], 0,
TcpSegmentPoolAlloc, TcpSegmentPoolInit,
(void *) &my_segment_pktsizes[i],
TcpSegmentPoolCleanup, NULL);
SCMutexUnlock(&my_segment_lock[i]);
if (my_segment_pool[i] == NULL) {
SCLogError(SC_ERR_INITIALIZATION, "couldn't set up segment pool "
"for packet size %u. Memcap too low?", my_segment_pktsizes[i]);
exit(EXIT_FAILURE);
}
SCLogDebug("my_segment_pktsizes[i] %u, my_segment_poolsizes[i] %u",
my_segment_pktsizes[i], my_segment_poolsizes[i]);
if (!quiet)
SCLogInfo("segment pool: pktsize %u, prealloc %u",
my_segment_pktsizes[i], my_segment_poolsizes[i]);
}
uint16_t idx = 0;
uint16_t u16 = 0;
while (1) {
if (idx <= my_segment_pktsizes[u16]) {
segment_pool_idx[idx] = u16;
if (my_segment_pktsizes[u16] == idx)
u16++;
}
if (idx == 0xffff)
break;
idx++;
}
/* set the globals */
segment_pool = my_segment_pool;
segment_pool_mutex = my_segment_lock;
segment_pool_pktsizes = my_segment_pktsizes;
segment_pool_num = npools;
uint32_t stream_chunk_prealloc = 250;
ConfNode *chunk = ConfGetNode("stream.reassembly.chunk-prealloc");
if (chunk) {
uint32_t prealloc = 0;
if (ByteExtractStringUint32(&prealloc, 10, strlen(chunk->val), chunk->val) == -1)
{
SCLogError(SC_ERR_INVALID_ARGUMENT, "chunk-prealloc of "
"%s is invalid", chunk->val);
return -1;
}
stream_chunk_prealloc = prealloc;
}
if (!quiet)
SCLogInfo("stream.reassembly \"chunk-prealloc\": %u", stream_chunk_prealloc);
StreamMsgQueuesInit(stream_chunk_prealloc);
intmax_t zero_copy_size = 128;
if (ConfGetInt("stream.reassembly.zero-copy-size", &zero_copy_size) == 1) {
if (zero_copy_size < 0 || zero_copy_size > 0xffff) {
SCLogError(SC_ERR_INVALID_ARGUMENT, "stream.reassembly.zero-copy-size of "
"%"PRIiMAX" is invalid: valid values are 0 to 65535", zero_copy_size);
return -1;
}
}
stream_config.zero_copy_size = (uint16_t)zero_copy_size;
if (!quiet)
SCLogInfo("stream.reassembly \"zero-copy-size\": %u", stream_config.zero_copy_size);
return 0;
}
int StreamTcpReassembleInit(char quiet)
{
/* init the memcap/use tracker */
SC_ATOMIC_INIT(ra_memuse);
if (StreamTcpReassemblyConfig(quiet) < 0)
return -1;
#ifdef DEBUG
SCMutexInit(&segment_pool_memuse_mutex, NULL);
SCMutexInit(&segment_pool_cnt_mutex, NULL);
#endif
return 0;
}
#ifdef DEBUG
static uint32_t dbg_app_layer_gap;
static uint32_t dbg_app_layer_gap_candidate;
#endif
void StreamTcpReassembleFree(char quiet)
{
uint16_t u16 = 0;
for (u16 = 0; u16 < segment_pool_num; u16++) {
SCMutexLock(&segment_pool_mutex[u16]);
if (quiet == FALSE) {
PoolPrintSaturation(segment_pool[u16]);
SCLogDebug("segment_pool[u16]->empty_stack_size %"PRIu32", "
"segment_pool[u16]->alloc_stack_size %"PRIu32", alloced "
"%"PRIu32"", segment_pool[u16]->empty_stack_size,
segment_pool[u16]->alloc_stack_size,
segment_pool[u16]->allocated);
if (segment_pool[u16]->max_outstanding > segment_pool[u16]->allocated) {
SCLogInfo("TCP segment pool of size %u had a peak use of %u segments, "
"more than the prealloc setting of %u", segment_pool_pktsizes[u16],
segment_pool[u16]->max_outstanding, segment_pool[u16]->allocated);
}
}
PoolFree(segment_pool[u16]);
SCMutexUnlock(&segment_pool_mutex[u16]);
SCMutexDestroy(&segment_pool_mutex[u16]);
}
SCFree(segment_pool);
SCFree(segment_pool_mutex);
SCFree(segment_pool_pktsizes);
segment_pool = NULL;
segment_pool_mutex = NULL;
segment_pool_pktsizes = NULL;
StreamMsgQueuesDeinit(quiet);
#ifdef DEBUG
SCLogDebug("segment_pool_cnt %"PRIu64"", segment_pool_cnt);
SCLogDebug("segment_pool_memuse %"PRIu64"", segment_pool_memuse);
SCLogDebug("segment_pool_memcnt %"PRIu64"", segment_pool_memcnt);
SCMutexDestroy(&segment_pool_memuse_mutex);
SCMutexDestroy(&segment_pool_cnt_mutex);
SCLogInfo("dbg_app_layer_gap %u", dbg_app_layer_gap);
SCLogInfo("dbg_app_layer_gap_candidate %u", dbg_app_layer_gap_candidate);
#endif
}
TcpReassemblyThreadCtx *StreamTcpReassembleInitThreadCtx(ThreadVars *tv)
{
SCEnter();
TcpReassemblyThreadCtx *ra_ctx = SCMalloc(sizeof(TcpReassemblyThreadCtx));
if (unlikely(ra_ctx == NULL))
return NULL;
memset(ra_ctx, 0x00, sizeof(TcpReassemblyThreadCtx));
ra_ctx->app_tctx = AppLayerGetCtxThread(tv);
SCReturnPtr(ra_ctx, "TcpReassemblyThreadCtx");
}
void StreamTcpReassembleFreeThreadCtx(TcpReassemblyThreadCtx *ra_ctx)
{
SCEnter();
AppLayerDestroyCtxThread(ra_ctx->app_tctx);
#ifdef DEBUG
SCLogDebug("reassembly fast path stats: fp1 %"PRIu64" fp2 %"PRIu64" sp %"PRIu64,
ra_ctx->fp1, ra_ctx->fp2, ra_ctx->sp);
#endif
SCFree(ra_ctx);
SCReturn;
}
void PrintList2(TcpSegment *seg)
{
TcpSegment *prev_seg = NULL;
if (seg == NULL)
return;
uint32_t next_seq = seg->seq;
while (seg != NULL) {
if (SEQ_LT(next_seq,seg->seq)) {
SCLogDebug("missing segment(s) for %" PRIu32 " bytes of data",
(seg->seq - next_seq));
}
SCLogDebug("seg %10"PRIu32" len %" PRIu16 ", seg %p, prev %p, next %p",
seg->seq, seg->payload_len, seg, seg->prev, seg->next);
if (seg->prev != NULL && SEQ_LT(seg->seq,seg->prev->seq)) {
/* check for SEQ_LT cornercase where a - b is exactly 2147483648,
* which makes the marco return TRUE in both directions. This is
* a hack though, we're going to check next how we end up with
* a segment list with seq differences that big */
if (!(SEQ_LT(seg->prev->seq,seg->seq))) {
SCLogDebug("inconsistent list: SEQ_LT(seg->seq,seg->prev->seq)) =="
" TRUE, seg->seq %" PRIu32 ", seg->prev->seq %" PRIu32 ""
"", seg->seq, seg->prev->seq);
}
}
if (SEQ_LT(seg->seq,next_seq)) {
SCLogDebug("inconsistent list: SEQ_LT(seg->seq,next_seq)) == TRUE, "
"seg->seq %" PRIu32 ", next_seq %" PRIu32 "", seg->seq,
next_seq);
}
if (prev_seg != seg->prev) {
SCLogDebug("inconsistent list: prev_seg %p != seg->prev %p",
prev_seg, seg->prev);
}
next_seq = seg->seq + seg->payload_len;
SCLogDebug("next_seq is now %"PRIu32"", next_seq);
prev_seg = seg;
seg = seg->next;
}
}
void PrintList(TcpSegment *seg)
{
TcpSegment *prev_seg = NULL;
TcpSegment *head_seg = seg;
if (seg == NULL)
return;
uint32_t next_seq = seg->seq;
while (seg != NULL) {
if (SEQ_LT(next_seq,seg->seq)) {
SCLogDebug("missing segment(s) for %" PRIu32 " bytes of data",
(seg->seq - next_seq));
}
SCLogDebug("seg %10"PRIu32" len %" PRIu16 ", seg %p, prev %p, next %p, flags 0x%02x",
seg->seq, seg->payload_len, seg, seg->prev, seg->next, seg->flags);
if (seg->prev != NULL && SEQ_LT(seg->seq,seg->prev->seq)) {
/* check for SEQ_LT cornercase where a - b is exactly 2147483648,
* which makes the marco return TRUE in both directions. This is
* a hack though, we're going to check next how we end up with
* a segment list with seq differences that big */
if (!(SEQ_LT(seg->prev->seq,seg->seq))) {
SCLogDebug("inconsistent list: SEQ_LT(seg->seq,seg->prev->seq)) == "
"TRUE, seg->seq %" PRIu32 ", seg->prev->seq %" PRIu32 "",
seg->seq, seg->prev->seq);
PrintList2(head_seg);
abort();
}
}
if (SEQ_LT(seg->seq,next_seq)) {
SCLogDebug("inconsistent list: SEQ_LT(seg->seq,next_seq)) == TRUE, "
"seg->seq %" PRIu32 ", next_seq %" PRIu32 "", seg->seq,
next_seq);
PrintList2(head_seg);
abort();
}
if (prev_seg != seg->prev) {
SCLogDebug("inconsistent list: prev_seg %p != seg->prev %p",
prev_seg, seg->prev);
PrintList2(head_seg);
abort();
}
next_seq = seg->seq + seg->payload_len;
SCLogDebug("next_seq is now %"PRIu32"", next_seq);
prev_seg = seg;
seg = seg->next;
}
}
/**
* \internal
* \brief Get the active ra_base_seq, considering stream gaps
*
* \retval seq the active ra_base_seq
*/
static inline uint32_t StreamTcpReassembleGetRaBaseSeq(TcpStream *stream)
{
if (!(stream->flags & STREAMTCP_STREAM_FLAG_GAP)) {
SCReturnUInt(stream->ra_app_base_seq);
} else {
SCReturnUInt(stream->ra_raw_base_seq);
}
}
/**
* \internal
* \brief Function to handle the insertion newly arrived segment,
* The packet is handled based on its target OS.
*
* \param stream The given TCP stream to which this new segment belongs
* \param seg Newly arrived segment
* \param p received packet
*
* \retval 0 success
* \retval -1 error -- either we hit a memory issue (OOM/memcap) or we received
* a segment before ra_base_seq.
*/
int StreamTcpReassembleInsertSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpStream *stream, TcpSegment *seg, Packet *p)
{
SCEnter();
TcpSegment *list_seg = stream->seg_list;
TcpSegment *next_list_seg = NULL;
#if DEBUG
PrintList(stream->seg_list);
#endif
int ret_value = 0;
char return_seg = FALSE;
/* before our ra_app_base_seq we don't insert it in our list,
* or ra_raw_base_seq if in stream gap state */
if (SEQ_LT((TCP_GET_SEQ(p)+p->payload_len),(StreamTcpReassembleGetRaBaseSeq(stream)+1)))
{
SCLogDebug("not inserting: SEQ+payload %"PRIu32", last_ack %"PRIu32", "
"ra_(app|raw)_base_seq %"PRIu32, (TCP_GET_SEQ(p)+p->payload_len),
stream->last_ack, StreamTcpReassembleGetRaBaseSeq(stream)+1);
return_seg = TRUE;
ret_value = -1;
StreamTcpSetEvent(p, STREAM_REASSEMBLY_SEGMENT_BEFORE_BASE_SEQ);
goto end;
}
SCLogDebug("SEQ %"PRIu32", SEQ+payload %"PRIu32", last_ack %"PRIu32", "
"ra_app_base_seq %"PRIu32, TCP_GET_SEQ(p), (TCP_GET_SEQ(p)+p->payload_len),
stream->last_ack, stream->ra_app_base_seq);
if (seg == NULL) {
goto end;
}
/* fast track */
if (list_seg == NULL) {
SCLogDebug("empty list, inserting seg %p seq %" PRIu32 ", "
"len %" PRIu32 "", seg, seg->seq, seg->payload_len);
stream->seg_list = seg;
seg->prev = NULL;
stream->seg_list_tail = seg;
goto end;
}
/* insert the segment in the stream list using this fast track, if seg->seq
is equal or higher than stream->seg_list_tail.*/
if (SEQ_GEQ(seg->seq, (stream->seg_list_tail->seq +
stream->seg_list_tail->payload_len)))
{
stream->seg_list_tail->next = seg;
seg->prev = stream->seg_list_tail;
stream->seg_list_tail = seg;
goto end;
}
/* If the OS policy is not set then set the OS policy for this stream */
if (stream->os_policy == 0) {
StreamTcpSetOSPolicy(stream, p);
}
for (; list_seg != NULL; list_seg = next_list_seg) {
next_list_seg = list_seg->next;
SCLogDebug("seg %p, list_seg %p, list_prev %p list_seg->next %p, "
"segment length %" PRIu32 "", seg, list_seg, list_seg->prev,
list_seg->next, seg->payload_len);
SCLogDebug("seg->seq %"PRIu32", list_seg->seq %"PRIu32"",
seg->seq, list_seg->seq);
/* segment starts before list */
if (SEQ_LT(seg->seq, list_seg->seq)) {
/* seg is entirely before list_seg */
if (SEQ_LEQ((seg->seq + seg->payload_len), list_seg->seq)) {
SCLogDebug("before list seg: seg->seq %" PRIu32 ", list_seg->seq"
" %" PRIu32 ", list_seg->payload_len %" PRIu32 ", "
"list_seg->prev %p", seg->seq, list_seg->seq,
list_seg->payload_len, list_seg->prev);
seg->next = list_seg;
if (list_seg->prev == NULL) {
stream->seg_list = seg;
}
if (list_seg->prev != NULL) {
list_seg->prev->next = seg;
seg->prev = list_seg->prev;
}
list_seg->prev = seg;
goto end;
/* seg overlap with next seg(s) */
} else {
ret_value = HandleSegmentStartsBeforeListSegment(tv, ra_ctx, stream, list_seg, seg, p);
if (ret_value == 1) {
ret_value = 0;
return_seg = TRUE;
goto end;
} else if (ret_value == -1) {
SCLogDebug("HandleSegmentStartsBeforeListSegment failed");
ret_value = -1;
return_seg = TRUE;
goto end;
}
}
/* seg starts at same sequence number as list_seg */
} else if (SEQ_EQ(seg->seq, list_seg->seq)) {
ret_value = HandleSegmentStartsAtSameListSegment(tv, ra_ctx, stream, list_seg, seg, p);
if (ret_value == 1) {
ret_value = 0;
return_seg = TRUE;
goto end;
} else if (ret_value == -1) {
SCLogDebug("HandleSegmentStartsAtSameListSegment failed");
ret_value = -1;
return_seg = TRUE;
goto end;
}
/* seg starts at sequence number higher than list_seg */
} else if (SEQ_GT(seg->seq, list_seg->seq)) {
if (((SEQ_GEQ(seg->seq, (list_seg->seq + list_seg->payload_len))))
&& SEQ_GT((seg->seq + seg->payload_len),
(list_seg->seq + list_seg->payload_len)))
{
SCLogDebug("starts beyond list end, ends after list end: "
"seg->seq %" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu32 " (%" PRIu32 ")",
seg->seq, list_seg->seq, list_seg->payload_len,
list_seg->seq + list_seg->payload_len);
if (list_seg->next == NULL) {
list_seg->next = seg;
seg->prev = list_seg;
stream->seg_list_tail = seg;
goto end;
}
} else {
ret_value = HandleSegmentStartsAfterListSegment(tv, ra_ctx, stream, list_seg, seg, p);
if (ret_value == 1) {
ret_value = 0;
return_seg = TRUE;
goto end;
} else if (ret_value == -1) {
SCLogDebug("HandleSegmentStartsAfterListSegment failed");
ret_value = -1;
return_seg = TRUE;
goto end;
}
}
}
}
end:
if (return_seg == TRUE && seg != NULL) {
StreamTcpSegmentReturntoPool(seg);
}
#ifdef DEBUG
PrintList(stream->seg_list);
#endif
SCReturnInt(ret_value);
}
/**
* \brief Function to handle the newly arrived segment, when newly arrived
* starts with the sequence number lower than the original segment and
* ends at different position relative to original segment.
* The packet is handled based on its target OS.
*
* \param list_seg Original Segment in the stream
* \param seg Newly arrived segment
* \param prev_seg Previous segment in the stream segment list
* \param p Packet
*
* \retval 1 success and done
* \retval 0 success, but not done yet
* \retval -1 error, will *only* happen on memory errors
*/
static int HandleSegmentStartsBeforeListSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpStream *stream, TcpSegment *list_seg, TcpSegment *seg, Packet *p)
{
SCEnter();
uint16_t overlap = 0;
uint16_t packet_length = 0;
uint32_t overlap_point = 0;
char end_before = FALSE;
char end_after = FALSE;
char end_same = FALSE;
char return_after = FALSE;
uint8_t os_policy = stream->os_policy;
#ifdef DEBUG
SCLogDebug("seg->seq %" PRIu32 ", seg->payload_len %" PRIu32 "", seg->seq,
seg->payload_len);
PrintList(stream->seg_list);
#endif
if (SEQ_GT((seg->seq + seg->payload_len), list_seg->seq) &&
SEQ_LT((seg->seq + seg->payload_len),(list_seg->seq +
list_seg->payload_len)))
{
/* seg starts before list seg, ends beyond it but before list end */
end_before = TRUE;
/* [aaaa[abab]bbbb] a = seg, b = list_seg, overlap is the part [abab]
* We know seg->seq + seg->payload_len is bigger than list_seg->seq */
overlap = (seg->seq + seg->payload_len) - list_seg->seq;
overlap_point = list_seg->seq;
SCLogDebug("starts before list seg, ends before list end: seg->seq "
"%" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu16 " overlap is %" PRIu32 ", "
"overlap point %"PRIu32"", seg->seq, list_seg->seq,
list_seg->payload_len, overlap, overlap_point);
} else if (SEQ_EQ((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg fully overlaps list_seg, starts before, at end point
* [aaa[ababab]] where a = seg, b = list_seg
* overlap is [ababab], which is list_seg->payload_len */
overlap = list_seg->payload_len;
end_same = TRUE;
overlap_point = list_seg->seq;
SCLogDebug("starts before list seg, ends at list end: list prev %p"
"seg->seq %" PRIu32 ", list_seg->seq %" PRIu32 ","
"list_seg->payload_len %" PRIu32 " overlap is %" PRIu32 "",
list_seg->prev, seg->seq, list_seg->seq,
list_seg->payload_len, overlap);
/* seg fully overlaps list_seg, starts before, ends after list endpoint */
} else if (SEQ_GT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg fully overlaps list_seg, starts before, ends after list endpoint
* [aaa[ababab]aaa] where a = seg, b = list_seg
* overlap is [ababab] which is list_seg->payload_len */
overlap = list_seg->payload_len;
end_after = TRUE;
overlap_point = list_seg->seq;
SCLogDebug("starts before list seg, ends after list end: seg->seq "
"%" PRIu32 ", seg->payload_len %"PRIu32" list_seg->seq "
"%" PRIu32 ", list_seg->payload_len %" PRIu32 " overlap is"
" %" PRIu32 "", seg->seq, seg->payload_len,
list_seg->seq, list_seg->payload_len, overlap);
}
if (overlap > 0) {
/* handle the case where we need to fill a gap before list_seg first */
if (list_seg->prev != NULL && SEQ_LT((list_seg->prev->seq + list_seg->prev->payload_len), list_seg->seq)) {
SCLogDebug("GAP to fill before list segment, size %u", list_seg->seq - (list_seg->prev->seq + list_seg->prev->payload_len));
uint32_t new_seq = (list_seg->prev->seq + list_seg->prev->payload_len);
if (SEQ_GT(seg->seq, new_seq)) {
new_seq = seg->seq;
}
packet_length = list_seg->seq - new_seq;
if (packet_length > seg->payload_len) {
packet_length = seg->payload_len;
}
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
new_seg->seq = new_seq;
SCLogDebug("new_seg->seq %"PRIu32" and new->payload_len "
"%" PRIu16"", new_seg->seq, new_seg->payload_len);
new_seg->next = list_seg;
new_seg->prev = list_seg->prev;
list_seg->prev->next = new_seg;
list_seg->prev = new_seg;
/* create a new seg, copy the list_seg data over */
StreamTcpSegmentDataCopy(new_seg, seg);
#ifdef DEBUG
PrintList(stream->seg_list);
#endif
}
/* Handling case when the segment starts before the first segment in
* the list */
if (list_seg->prev == NULL) {
if (end_after == TRUE && list_seg->next != NULL &&
SEQ_LT(list_seg->next->seq, (seg->seq + seg->payload_len)))
{
packet_length = (list_seg->seq - seg->seq) + list_seg->payload_len;
} else {
packet_length = seg->payload_len + (list_seg->payload_len - overlap);
return_after = TRUE;
}
SCLogDebug("entered here packet_length %" PRIu32 ", seg->payload_len"
" %" PRIu32 ", list->payload_len %" PRIu32 "",
packet_length, seg->payload_len, list_seg->payload_len);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
new_seg->seq = seg->seq;
new_seg->next = list_seg->next;
new_seg->prev = list_seg->prev;
StreamTcpSegmentDataCopy(new_seg, list_seg);
/* first the data before the list_seg->seq */
uint16_t replace = (uint16_t) (list_seg->seq - seg->seq);
SCLogDebug("copying %"PRIu16" bytes to new_seg", replace);
StreamTcpSegmentDataReplace(new_seg, seg, seg->seq, replace);
/* if any, data after list_seg->seq + list_seg->payload_len */
if (SEQ_GT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)) && return_after == TRUE)
{
replace = (uint16_t)(((seg->seq + seg->payload_len) -
(list_seg->seq +
list_seg->payload_len)));
SCLogDebug("replacing %"PRIu16"", replace);
StreamTcpSegmentDataReplace(new_seg, seg, (list_seg->seq +
list_seg->payload_len), replace);
}
/* update the stream last_seg in case of removal of list_seg */
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
StreamTcpSegmentReturntoPool(list_seg);
list_seg = new_seg;
if (new_seg->prev != NULL) {
new_seg->prev->next = new_seg;
}
if (new_seg->next != NULL) {
new_seg->next->prev = new_seg;
}
stream->seg_list = new_seg;
SCLogDebug("list_seg now %p, stream->seg_list now %p", list_seg,
stream->seg_list);
} else if (end_before == TRUE || end_same == TRUE) {
/* Handling overlapping with more than one segment and filling gap */
if (SEQ_GT(list_seg->seq, (list_seg->prev->seq +
list_seg->prev->payload_len)))
{
SCLogDebug("list_seg->prev %p list_seg->prev->seq %"PRIu32" "
"list_seg->prev->payload_len %"PRIu16"",
list_seg->prev, list_seg->prev->seq,
list_seg->prev->payload_len);
if (SEQ_LT(list_seg->prev->seq, seg->seq)) {
packet_length = list_seg->payload_len + (list_seg->seq -
seg->seq);
} else {
packet_length = list_seg->payload_len + (list_seg->seq -
(list_seg->prev->seq + list_seg->prev->payload_len));
}
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
if (SEQ_GT((list_seg->prev->seq + list_seg->prev->payload_len),
seg->seq))
{
new_seg->seq = (list_seg->prev->seq +
list_seg->prev->payload_len);
} else {
new_seg->seq = seg->seq;
}
SCLogDebug("new_seg->seq %"PRIu32" and new->payload_len "
"%" PRIu16"", new_seg->seq, new_seg->payload_len);
new_seg->next = list_seg->next;
new_seg->prev = list_seg->prev;
StreamTcpSegmentDataCopy(new_seg, list_seg);
uint16_t copy_len = (uint16_t) (list_seg->seq - seg->seq);
SCLogDebug("copy_len %" PRIu32 " (%" PRIu32 " - %" PRIu32 ")",
copy_len, list_seg->seq, seg->seq);
StreamTcpSegmentDataReplace(new_seg, seg, seg->seq, copy_len);
/*update the stream last_seg in case of removal of list_seg*/
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
StreamTcpSegmentReturntoPool(list_seg);
list_seg = new_seg;
if (new_seg->prev != NULL) {
new_seg->prev->next = new_seg;
}
if (new_seg->next != NULL) {
new_seg->next->prev = new_seg;
}
}
} else if (end_after == TRUE) {
if (list_seg->next != NULL) {
if (SEQ_LEQ((seg->seq + seg->payload_len), list_seg->next->seq))
{
if (SEQ_GT(seg->seq, (list_seg->prev->seq +
list_seg->prev->payload_len)))
{
packet_length = list_seg->payload_len + (list_seg->seq -
seg->seq);
} else {
packet_length = list_seg->payload_len + (list_seg->seq -
(list_seg->prev->seq +
list_seg->prev->payload_len));
}
packet_length += (seg->seq + seg->payload_len) -
(list_seg->seq + list_seg->payload_len);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
if (SEQ_GT((list_seg->prev->seq +
list_seg->prev->payload_len), seg->seq))
{
new_seg->seq = (list_seg->prev->seq +
list_seg->prev->payload_len);
} else {
new_seg->seq = seg->seq;
}
SCLogDebug("new_seg->seq %"PRIu32" and new->payload_len "
"%" PRIu16"", new_seg->seq, new_seg->payload_len);
new_seg->next = list_seg->next;
new_seg->prev = list_seg->prev;
/* create a new seg, copy the list_seg data over */
StreamTcpSegmentDataCopy(new_seg, list_seg);
/* copy the part before list_seg */
uint16_t copy_len = list_seg->seq - new_seg->seq;
StreamTcpSegmentDataReplace(new_seg, seg, new_seg->seq,
copy_len);
/* copy the part after list_seg */
copy_len = (seg->seq + seg->payload_len) -
(list_seg->seq + list_seg->payload_len);
StreamTcpSegmentDataReplace(new_seg, seg, (list_seg->seq +
list_seg->payload_len), copy_len);
if (new_seg->prev != NULL) {
new_seg->prev->next = new_seg;
}
if (new_seg->next != NULL) {
new_seg->next->prev = new_seg;
}
/*update the stream last_seg in case of removal of list_seg*/
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
StreamTcpSegmentReturntoPool(list_seg);
list_seg = new_seg;
return_after = TRUE;
}
/* Handle the case, when list_seg is the end of segment list, but
seg is ending after the list_seg. So we need to copy the data
from newly received segment. After copying return the newly
received seg to pool */
} else {
if (SEQ_GT(seg->seq, (list_seg->prev->seq +
list_seg->prev->payload_len)))
{
packet_length = list_seg->payload_len + (list_seg->seq -
seg->seq);
} else {
packet_length = list_seg->payload_len + (list_seg->seq -
(list_seg->prev->seq +
list_seg->prev->payload_len));
}
packet_length += (seg->seq + seg->payload_len) -
(list_seg->seq + list_seg->payload_len);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty",
segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
if (SEQ_GT((list_seg->prev->seq +
list_seg->prev->payload_len), seg->seq))
{
new_seg->seq = (list_seg->prev->seq +
list_seg->prev->payload_len);
} else {
new_seg->seq = seg->seq;
}
SCLogDebug("new_seg->seq %"PRIu32" and new->payload_len "
"%" PRIu16"", new_seg->seq, new_seg->payload_len);
new_seg->next = list_seg->next;
new_seg->prev = list_seg->prev;
/* create a new seg, copy the list_seg data over */
StreamTcpSegmentDataCopy(new_seg, list_seg);
/* copy the part before list_seg */
uint16_t copy_len = list_seg->seq - new_seg->seq;
StreamTcpSegmentDataReplace(new_seg, seg, new_seg->seq,
copy_len);
/* copy the part after list_seg */
copy_len = (seg->seq + seg->payload_len) -
(list_seg->seq + list_seg->payload_len);
StreamTcpSegmentDataReplace(new_seg, seg, (list_seg->seq +
list_seg->payload_len), copy_len);
if (new_seg->prev != NULL) {
new_seg->prev->next = new_seg;
}
/*update the stream last_seg in case of removal of list_seg*/
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
StreamTcpSegmentReturntoPool(list_seg);
list_seg = new_seg;
return_after = TRUE;
}
}
if (check_overlap_different_data &&
!StreamTcpSegmentDataCompare(seg, list_seg, list_seg->seq, overlap)) {
/* interesting, overlap with different data */
StreamTcpSetEvent(p, STREAM_REASSEMBLY_OVERLAP_DIFFERENT_DATA);
}
if (StreamTcpInlineMode()) {
if (StreamTcpInlineSegmentCompare(seg, list_seg) != 0) {
StreamTcpInlineSegmentReplacePacket(p, list_seg);
}
} else {
switch (os_policy) {
case OS_POLICY_SOLARIS:
case OS_POLICY_HPUX11:
if (end_after == TRUE || end_same == TRUE) {
StreamTcpSegmentDataReplace(list_seg, seg, overlap_point,
overlap);
} else {
SCLogDebug("using old data in starts before list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
}
break;
case OS_POLICY_VISTA:
case OS_POLICY_FIRST:
SCLogDebug("using old data in starts before list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
break;
case OS_POLICY_BSD:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
default:
SCLogDebug("replacing old data in starts before list seg "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
StreamTcpSegmentDataReplace(list_seg, seg, overlap_point,
overlap);
break;
}
}
/* To return from for loop as seg is finished with current list_seg
no need to check further (improve performance) */
if (end_before == TRUE || end_same == TRUE || return_after == TRUE) {
SCReturnInt(1);
}
}
SCReturnInt(0);
}
/**
* \brief Function to handle the newly arrived segment, when newly arrived
* starts with the same sequence number as the original segment and
* ends at different position relative to original segment.
* The packet is handled based on its target OS.
*
* \param list_seg Original Segment in the stream
* \param seg Newly arrived segment
* \param prev_seg Previous segment in the stream segment list
*
* \retval 1 success and done
* \retval 0 success, but not done yet
* \retval -1 error, will *only* happen on memory errors
*/
static int HandleSegmentStartsAtSameListSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpStream *stream, TcpSegment *list_seg, TcpSegment *seg, Packet *p)
{
uint16_t overlap = 0;
uint16_t packet_length;
char end_before = FALSE;
char end_after = FALSE;
char end_same = FALSE;
char handle_beyond = FALSE;
uint8_t os_policy = stream->os_policy;
if (SEQ_LT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg->seg == list_seg->seq and list_seg->payload_len > seg->payload_len
* [[ababab]bbbb] where a = seg, b = list_seg
* overlap is the [ababab] part, which equals seg->payload_len. */
overlap = seg->payload_len;
end_before = TRUE;
SCLogDebug("starts at list seq, ends before list end: seg->seq "
"%" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu32 " overlap is %" PRIu32,
seg->seq, list_seg->seq, list_seg->payload_len, overlap);
} else if (SEQ_EQ((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg starts at seq, ends at seq, retransmission.
* both segments are the same, so overlap is either
* seg->payload_len or list_seg->payload_len */
/* check csum, ack, other differences? */
overlap = seg->payload_len;
end_same = TRUE;
SCLogDebug("(retransmission) starts at list seq, ends at list end: "
"seg->seq %" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu32 " overlap is %"PRIu32"",
seg->seq, list_seg->seq, list_seg->payload_len, overlap);
} else if (SEQ_GT((seg->seq + seg->payload_len),
(list_seg->seq + list_seg->payload_len))) {
/* seg starts at seq, ends beyond seq. */
/* seg->seg == list_seg->seq and seg->payload_len > list_seg->payload_len
* [[ababab]aaaa] where a = seg, b = list_seg
* overlap is the [ababab] part, which equals list_seg->payload_len. */
overlap = list_seg->payload_len;
end_after = TRUE;
SCLogDebug("starts at list seq, ends beyond list end: seg->seq "
"%" PRIu32 ", list_seg->seq %" PRIu32 ", "
"list_seg->payload_len %" PRIu32 " overlap is %" PRIu32 "",
seg->seq, list_seg->seq, list_seg->payload_len, overlap);
}
if (overlap > 0) {
/*Handle the case when newly arrived segment ends after original
segment and original segment is the last segment in the list
or the next segment in the list starts after the end of new segment*/
if (end_after == TRUE) {
char fill_gap = FALSE;
if (list_seg->next != NULL) {
/* first see if we have space left to fill up */
if (SEQ_LT((list_seg->seq + list_seg->payload_len),
list_seg->next->seq))
{
fill_gap = TRUE;
}
/* then see if we overlap (partly) with the next seg */
if (SEQ_GT((seg->seq + seg->payload_len), list_seg->next->seq))
{
handle_beyond = TRUE;
}
/* Handle the case, when list_seg is the end of segment list, but
seg is ending after the list_seg. So we need to copy the data
from newly received segment. After copying return the newly
received seg to pool */
} else {
fill_gap = TRUE;
}
SCLogDebug("fill_gap %s, handle_beyond %s", fill_gap?"TRUE":"FALSE",
handle_beyond?"TRUE":"FALSE");
if (fill_gap == TRUE) {
/* if there is a gap after this list_seg we fill it now with a
* new seg */
SCLogDebug("filling gap: list_seg->next->seq %"PRIu32"",
list_seg->next?list_seg->next->seq:0);
if (handle_beyond == TRUE) {
packet_length = list_seg->next->seq -
(list_seg->seq + list_seg->payload_len);
} else {
packet_length = seg->payload_len - list_seg->payload_len;
}
SCLogDebug("packet_length %"PRIu16"", packet_length);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("egment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
return -1;
}
new_seg->payload_len = packet_length;
new_seg->seq = list_seg->seq + list_seg->payload_len;
new_seg->next = list_seg->next;
if (new_seg->next != NULL)
new_seg->next->prev = new_seg;
new_seg->prev = list_seg;
list_seg->next = new_seg;
SCLogDebug("new_seg %p, new_seg->next %p, new_seg->prev %p, "
"list_seg->next %p", new_seg, new_seg->next,
new_seg->prev, list_seg->next);
StreamTcpSegmentDataReplace(new_seg, seg, new_seg->seq,
new_seg->payload_len);
/*update the stream last_seg in case of removal of list_seg*/
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
}
}
if (check_overlap_different_data &&
!StreamTcpSegmentDataCompare(list_seg, seg, seg->seq, overlap)) {
/* interesting, overlap with different data */
StreamTcpSetEvent(p, STREAM_REASSEMBLY_OVERLAP_DIFFERENT_DATA);
}
if (StreamTcpInlineMode()) {
if (StreamTcpInlineSegmentCompare(list_seg, seg) != 0) {
StreamTcpInlineSegmentReplacePacket(p, list_seg);
}
} else {
switch (os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_SOLARIS:
case OS_POLICY_HPUX11:
if (end_after == TRUE || end_same == TRUE) {
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
} else {
SCLogDebug("using old data in starts at list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
}
break;
case OS_POLICY_LAST:
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
break;
case OS_POLICY_LINUX:
if (end_after == TRUE) {
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
} else {
SCLogDebug("using old data in starts at list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
}
break;
case OS_POLICY_BSD:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_MACOS:
case OS_POLICY_FIRST:
default:
SCLogDebug("using old data in starts at list case, list_seg->seq"
" %" PRIu32 " policy %" PRIu32 " overlap %" PRIu32 "",
list_seg->seq, os_policy, overlap);
break;
}
}
/* return 1 if we're done */
if (end_before == TRUE || end_same == TRUE || handle_beyond == FALSE) {
return 1;
}
}
return 0;
}
/**
* \internal
* \brief Function to handle the newly arrived segment, when newly arrived
* starts with the sequence number higher than the original segment and
* ends at different position relative to original segment.
* The packet is handled based on its target OS.
*
* \param list_seg Original Segment in the stream
* \param seg Newly arrived segment
* \param prev_seg Previous segment in the stream segment list
* \retval 1 success and done
* \retval 0 success, but not done yet
* \retval -1 error, will *only* happen on memory errors
*/
static int HandleSegmentStartsAfterListSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpStream *stream, TcpSegment *list_seg, TcpSegment *seg, Packet *p)
{
SCEnter();
uint16_t overlap = 0;
uint16_t packet_length;
char end_before = FALSE;
char end_after = FALSE;
char end_same = FALSE;
char handle_beyond = FALSE;
uint8_t os_policy = stream->os_policy;
if (SEQ_LT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg starts after list, ends before list end
* [bbbb[ababab]bbbb] where a = seg, b = list_seg
* overlap is the part [ababab] which is seg->payload_len */
overlap = seg->payload_len;
end_before = TRUE;
SCLogDebug("starts beyond list seq, ends before list end: seg->seq"
" %" PRIu32 ", list_seg->seq %" PRIu32 ", list_seg->payload_len "
"%" PRIu32 " overlap is %" PRIu32 "", seg->seq, list_seg->seq,
list_seg->payload_len, overlap);
} else if (SEQ_EQ((seg->seq + seg->payload_len),
(list_seg->seq + list_seg->payload_len))) {
/* seg starts after seq, before end, ends at seq
* [bbbb[ababab]] where a = seg, b = list_seg
* overlapping part is [ababab], thus seg->payload_len */
overlap = seg->payload_len;
end_same = TRUE;
SCLogDebug("starts beyond list seq, ends at list end: seg->seq"
" %" PRIu32 ", list_seg->seq %" PRIu32 ", list_seg->payload_len "
"%" PRIu32 " overlap is %" PRIu32 "", seg->seq, list_seg->seq,
list_seg->payload_len, overlap);
} else if (SEQ_LT(seg->seq, list_seg->seq + list_seg->payload_len) &&
SEQ_GT((seg->seq + seg->payload_len), (list_seg->seq +
list_seg->payload_len)))
{
/* seg starts after seq, before end, ends beyond seq.
*
* [bbb[ababab]aaa] where a = seg, b = list_seg.
* overlap is the [ababab] part, which can be get using:
* (list_seg->seq + list_seg->payload_len) - seg->seg */
overlap = (list_seg->seq + list_seg->payload_len) - seg->seq;
end_after = TRUE;
SCLogDebug("starts beyond list seq, ends after list seq end: "
"seg->seq %" PRIu32 ", seg->payload_len %"PRIu16" (%"PRIu32") "
"list_seg->seq %" PRIu32 ", list_seg->payload_len %" PRIu32 " "
"(%"PRIu32") overlap is %" PRIu32 "", seg->seq, seg->payload_len,
seg->seq + seg->payload_len, list_seg->seq, list_seg->payload_len,
list_seg->seq + list_seg->payload_len, overlap);
}
if (overlap > 0) {
/*Handle the case when newly arrived segment ends after original
segment and original segment is the last segment in the list*/
if (end_after == TRUE) {
char fill_gap = FALSE;
if (list_seg->next != NULL) {
/* first see if we have space left to fill up */
if (SEQ_LT((list_seg->seq + list_seg->payload_len),
list_seg->next->seq))
{
fill_gap = TRUE;
}
/* then see if we overlap (partly) with the next seg */
if (SEQ_GT((seg->seq + seg->payload_len), list_seg->next->seq))
{
handle_beyond = TRUE;
}
} else {
fill_gap = TRUE;
}
SCLogDebug("fill_gap %s, handle_beyond %s", fill_gap?"TRUE":"FALSE",
handle_beyond?"TRUE":"FALSE");
if (fill_gap == TRUE) {
/* if there is a gap after this list_seg we fill it now with a
* new seg */
if (list_seg->next != NULL) {
SCLogDebug("filling gap: list_seg->next->seq %"PRIu32"",
list_seg->next?list_seg->next->seq:0);
packet_length = list_seg->next->seq - (list_seg->seq +
list_seg->payload_len);
} else {
packet_length = seg->payload_len - overlap;
}
if (packet_length > (seg->payload_len - overlap)) {
packet_length = seg->payload_len - overlap;
}
SCLogDebug("packet_length %"PRIu16"", packet_length);
TcpSegment *new_seg = StreamTcpGetSegment(tv, ra_ctx, packet_length);
if (new_seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[packet_length]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
new_seg->payload_len = packet_length;
new_seg->seq = list_seg->seq + list_seg->payload_len;
new_seg->next = list_seg->next;
if (new_seg->next != NULL)
new_seg->next->prev = new_seg;
new_seg->prev = list_seg;
list_seg->next = new_seg;
SCLogDebug("new_seg %p, new_seg->next %p, new_seg->prev %p, "
"list_seg->next %p new_seg->seq %"PRIu32"", new_seg,
new_seg->next, new_seg->prev, list_seg->next,
new_seg->seq);
StreamTcpSegmentDataReplace(new_seg, seg, new_seg->seq,
new_seg->payload_len);
/* update the stream last_seg in case of removal of list_seg */
if (stream->seg_list_tail == list_seg)
stream->seg_list_tail = new_seg;
}
}
if (check_overlap_different_data &&
!StreamTcpSegmentDataCompare(list_seg, seg, seg->seq, overlap)) {
/* interesting, overlap with different data */
StreamTcpSetEvent(p, STREAM_REASSEMBLY_OVERLAP_DIFFERENT_DATA);
}
if (StreamTcpInlineMode()) {
if (StreamTcpInlineSegmentCompare(list_seg, seg) != 0) {
StreamTcpInlineSegmentReplacePacket(p, list_seg);
}
} else {
switch (os_policy) {
case OS_POLICY_SOLARIS:
case OS_POLICY_HPUX11:
if (end_after == TRUE) {
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
} else {
SCLogDebug("using old data in starts beyond list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
}
break;
case OS_POLICY_LAST:
StreamTcpSegmentDataReplace(list_seg, seg, seg->seq, overlap);
break;
case OS_POLICY_BSD:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_MACOS:
case OS_POLICY_FIRST:
default: /* DEFAULT POLICY */
SCLogDebug("using old data in starts beyond list case, "
"list_seg->seq %" PRIu32 " policy %" PRIu32 " "
"overlap %" PRIu32 "", list_seg->seq, os_policy,
overlap);
break;
}
}
if (end_before == TRUE || end_same == TRUE || handle_beyond == FALSE) {
SCReturnInt(1);
}
}
SCReturnInt(0);
}
/**
* \brief check if stream in pkt direction has depth reached
*
* \param p packet with *LOCKED* flow
*
* \retval 1 stream has depth reached
* \retval 0 stream does not have depth reached
*/
int StreamTcpReassembleDepthReached(Packet *p)
{
if (p->flow != NULL && p->flow->protoctx != NULL) {
TcpSession *ssn = p->flow->protoctx;
TcpStream *stream;
if (p->flowflags & FLOW_PKT_TOSERVER) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
return (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ? 1 : 0;
}
return 0;
}
/**
* \internal
* \brief Function to Check the reassembly depth valuer against the
* allowed max depth of the stream reassmbly for TCP streams.
*
* \param stream stream direction
* \param seq sequence number where "size" starts
* \param size size of the segment that is added
*
* \retval size Part of the size that fits in the depth, 0 if none
*/
static uint32_t StreamTcpReassembleCheckDepth(TcpStream *stream,
uint32_t seq, uint32_t size)
{
SCEnter();
/* if the configured depth value is 0, it means there is no limit on
reassembly depth. Otherwise carry on my boy ;) */
if (stream_config.reassembly_depth == 0) {
SCReturnUInt(size);
}
/* if the final flag is set, we're not accepting anymore */
if (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) {
SCReturnUInt(0);
}
/* if the ra_base_seq has moved passed the depth window we stop
* checking and just reject the rest of the packets including
* retransmissions. Saves us the hassle of dealing with sequence
* wraps as well */
if (SEQ_GEQ((StreamTcpReassembleGetRaBaseSeq(stream)+1),(stream->isn + stream_config.reassembly_depth))) {
stream->flags |= STREAMTCP_STREAM_FLAG_DEPTH_REACHED;
SCReturnUInt(0);
}
SCLogDebug("full Depth not yet reached: %"PRIu32" <= %"PRIu32,
(StreamTcpReassembleGetRaBaseSeq(stream)+1),
(stream->isn + stream_config.reassembly_depth));
if (SEQ_GEQ(seq, stream->isn) && SEQ_LT(seq, (stream->isn + stream_config.reassembly_depth))) {
/* packet (partly?) fits the depth window */
if (SEQ_LEQ((seq + size),(stream->isn + stream_config.reassembly_depth))) {
/* complete fit */
SCReturnUInt(size);
} else {
/* partial fit, return only what fits */
uint32_t part = (stream->isn + stream_config.reassembly_depth) - seq;
#if DEBUG
BUG_ON(part > size);
#else
if (part > size)
part = size;
#endif
SCReturnUInt(part);
}
}
SCReturnUInt(0);
}
static void StreamTcpStoreStreamChunk(TcpSession *ssn, StreamMsg *smsg, const Packet *p, int streaminline)
{
uint8_t direction = 0;
if ((!streaminline && (p->flowflags & FLOW_PKT_TOSERVER)) ||
( streaminline && (p->flowflags & FLOW_PKT_TOCLIENT)))
{
direction = STREAM_TOCLIENT;
SCLogDebug("stream chunk is to_client");
} else {
direction = STREAM_TOSERVER;
SCLogDebug("stream chunk is to_server");
}
/* store the smsg in the tcp stream */
if (direction == STREAM_TOSERVER) {
SCLogDebug("storing smsg in the to_server");
/* put the smsg in the stream list */
if (ssn->toserver_smsg_head == NULL) {
ssn->toserver_smsg_head = smsg;
ssn->toserver_smsg_tail = smsg;
smsg->next = NULL;
smsg->prev = NULL;
} else {
StreamMsg *cur = ssn->toserver_smsg_tail;
cur->next = smsg;
smsg->prev = cur;
smsg->next = NULL;
ssn->toserver_smsg_tail = smsg;
}
} else {
SCLogDebug("storing smsg in the to_client");
/* put the smsg in the stream list */
if (ssn->toclient_smsg_head == NULL) {
ssn->toclient_smsg_head = smsg;
ssn->toclient_smsg_tail = smsg;
smsg->next = NULL;
smsg->prev = NULL;
} else {
StreamMsg *cur = ssn->toclient_smsg_tail;
cur->next = smsg;
smsg->prev = cur;
smsg->next = NULL;
ssn->toclient_smsg_tail = smsg;
}
}
}
/**
* \brief Insert a packets TCP data into the stream reassembly engine.
*
* \retval 0 good segment, as far as we checked.
* \retval -1 badness, reason to drop in inline mode
*
* If the retval is 0 the segment is inserted correctly, or overlap is handled,
* or it wasn't added because of reassembly depth.
*
*/
int StreamTcpReassembleHandleSegmentHandleData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
if (ssn->data_first_seen_dir == 0) {
if (p->flowflags & FLOW_PKT_TOSERVER) {
ssn->data_first_seen_dir = STREAM_TOSERVER;
} else {
ssn->data_first_seen_dir = STREAM_TOCLIENT;
}
}
/* If we have reached the defined depth for either of the stream, then stop
reassembling the TCP session */
uint32_t size = StreamTcpReassembleCheckDepth(stream, TCP_GET_SEQ(p), p->payload_len);
SCLogDebug("ssn %p: check depth returned %"PRIu32, ssn, size);
if (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) {
/* increment stream depth counter */
SCPerfCounterIncr(ra_ctx->counter_tcp_stream_depth, tv->sc_perf_pca);
stream->flags |= STREAMTCP_STREAM_FLAG_NOREASSEMBLY;
SCLogDebug("ssn %p: reassembly depth reached, "
"STREAMTCP_STREAM_FLAG_NOREASSEMBLY set", ssn);
}
if (size == 0) {
SCLogDebug("ssn %p: depth reached, not reassembling", ssn);
SCReturnInt(0);
}
#if DEBUG
BUG_ON(size > p->payload_len);
#else
if (size > p->payload_len)
size = p->payload_len;
#endif
TcpSegment *seg = StreamTcpGetSegment(tv, ra_ctx, size);
if (seg == NULL) {
SCLogDebug("segment_pool[%"PRIu16"] is empty", segment_pool_idx[size]);
StreamTcpSetEvent(p, STREAM_REASSEMBLY_NO_SEGMENT);
SCReturnInt(-1);
}
memcpy(seg->payload, p->payload, size);
seg->payload_len = size;
seg->seq = TCP_GET_SEQ(p);
/* if raw reassembly is disabled for new segments, flag each
* segment as complete for raw before insert */
if (stream->flags & STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) {
seg->flags |= SEGMENTTCP_FLAG_RAW_PROCESSED;
SCLogDebug("segment %p flagged with SEGMENTTCP_FLAG_RAW_PROCESSED, "
"flags %02x", seg, seg->flags);
}
/* proto detection skipped, but now we do get data. Set event. */
if (stream->seg_list == NULL &&
stream->flags & STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_SKIPPED) {
AppLayerDecoderEventsSetEventRaw(&p->app_layer_events,
APPLAYER_PROTO_DETECTION_SKIPPED);
}
if (StreamTcpReassembleInsertSegment(tv, ra_ctx, stream, seg, p) != 0) {
SCLogDebug("StreamTcpReassembleInsertSegment failed");
SCReturnInt(-1);
}
SCReturnInt(0);
}
static uint8_t StreamGetAppLayerFlags(TcpSession *ssn, TcpStream *stream,
Packet *p)
{
uint8_t flag = 0;
if (!(stream->flags & STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_COMPLETED)) {
flag |= STREAM_START;
}
if (ssn->state == TCP_CLOSED) {
flag |= STREAM_EOF;
}
if (p->flags & PKT_PSEUDO_STREAM_END) {
flag |= STREAM_EOF;
}
if (StreamTcpInlineMode() == 0) {
if (p->flowflags & FLOW_PKT_TOSERVER) {
flag |= STREAM_TOCLIENT;
} else {
flag |= STREAM_TOSERVER;
}
} else {
if (p->flowflags & FLOW_PKT_TOSERVER) {
flag |= STREAM_TOSERVER;
} else {
flag |= STREAM_TOCLIENT;
}
}
if (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) {
flag |= STREAM_DEPTH;
}
return flag;
}
static void StreamTcpSetupMsg(TcpSession *ssn, TcpStream *stream, Packet *p,
StreamMsg *smsg)
{
SCEnter();
smsg->data_len = 0;
SCLogDebug("smsg %p", smsg);
SCReturn;
}
/**
* \brief Check the minimum size limits for reassembly.
*
* \retval 0 don't reassemble yet
* \retval 1 do reassemble
*/
static int StreamTcpReassembleRawCheckLimit(TcpSession *ssn, TcpStream *stream,
Packet *p)
{
SCEnter();
if (stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) {
SCLogDebug("reassembling now as STREAMTCP_STREAM_FLAG_NOREASSEMBLY is set, so not expecting any new packets");
SCReturnInt(1);
}
if (ssn->flags & STREAMTCP_FLAG_TRIGGER_RAW_REASSEMBLY) {
SCLogDebug("reassembling now as STREAMTCP_FLAG_TRIGGER_RAW_REASSEMBLY is set");
ssn->flags &= ~STREAMTCP_FLAG_TRIGGER_RAW_REASSEMBLY;
SCReturnInt(1);
}
if (stream->flags & STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) {
SCLogDebug("reassembling now as STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED is set, "
"so no new segments will be considered");
SCReturnInt(1);
}
/* some states mean we reassemble no matter how much data we have */
if (ssn->state >= TCP_TIME_WAIT)
SCReturnInt(1);
if (p->flags & PKT_PSEUDO_STREAM_END)
SCReturnInt(1);
/* check if we have enough data to send to L7 */
if (p->flowflags & FLOW_PKT_TOCLIENT) {
SCLogDebug("StreamMsgQueueGetMinChunkLen(STREAM_TOSERVER) %"PRIu32,
StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOSERVER));
if (StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOSERVER) >
(stream->last_ack - stream->ra_raw_base_seq)) {
SCLogDebug("toserver min chunk len not yet reached: "
"last_ack %"PRIu32", ra_raw_base_seq %"PRIu32", %"PRIu32" < "
"%"PRIu32"", stream->last_ack, stream->ra_raw_base_seq,
(stream->last_ack - stream->ra_raw_base_seq),
StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOSERVER));
SCReturnInt(0);
}
} else {
SCLogDebug("StreamMsgQueueGetMinChunkLen(STREAM_TOCLIENT) %"PRIu32,
StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOCLIENT));
if (StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOCLIENT) >
(stream->last_ack - stream->ra_raw_base_seq)) {
SCLogDebug("toclient min chunk len not yet reached: "
"last_ack %"PRIu32", ra_base_seq %"PRIu32", %"PRIu32" < "
"%"PRIu32"", stream->last_ack, stream->ra_raw_base_seq,
(stream->last_ack - stream->ra_raw_base_seq),
StreamMsgQueueGetMinChunkLen(FLOW_PKT_TOCLIENT));
SCReturnInt(0);
}
}
SCReturnInt(1);
}
/**
* \brief see if app layer is done with a segment
*
* \retval 1 app layer is done with this segment
* \retval 0 not done yet
*/
#define StreamTcpAppLayerSegmentProcessed(stream, segment) \
(( ( (stream)->flags & STREAMTCP_STREAM_FLAG_GAP ) || \
( (segment)->flags & SEGMENTTCP_FLAG_APPLAYER_PROCESSED ) ? 1 :0 ))
/** \internal
* \brief check if we can remove a segment from our segment list
*
* If a segment is entirely before the oldest smsg, we can discard it. Otherwise
* we keep it around to be able to log it.
*
* \retval 1 yes
* \retval 0 no
*/
static inline int StreamTcpReturnSegmentCheck(const Flow *f, TcpSession *ssn, TcpStream *stream, TcpSegment *seg)
{
if (stream == &ssn->client && ssn->toserver_smsg_head != NULL) {
/* not (seg is entirely before first smsg, skip) */
if (!(SEQ_LEQ(seg->seq + seg->payload_len, ssn->toserver_smsg_head->seq))) {
SCReturnInt(0);
}
} else if (stream == &ssn->server && ssn->toclient_smsg_head != NULL) {
/* not (seg is entirely before first smsg, skip) */
if (!(SEQ_LEQ(seg->seq + seg->payload_len, ssn->toclient_smsg_head->seq))) {
SCReturnInt(0);
}
}
/* if proto detect isn't done, we're not returning */
if (!(StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream))) {
SCReturnInt(0);
}
/* check app layer conditions */
if (!(f->flags & FLOW_NO_APPLAYER_INSPECTION)) {
if (!(StreamTcpAppLayerSegmentProcessed(stream, seg))) {
SCReturnInt(0);
}
}
/* check raw reassembly conditions */
if (!(seg->flags & SEGMENTTCP_FLAG_RAW_PROCESSED)) {
SCReturnInt(0);
}
SCReturnInt(1);
}
static void StreamTcpRemoveSegmentFromStream(TcpStream *stream, TcpSegment *seg)
{
if (seg->prev == NULL) {
stream->seg_list = seg->next;
if (stream->seg_list != NULL)
stream->seg_list->prev = NULL;
} else {
seg->prev->next = seg->next;
if (seg->next != NULL)
seg->next->prev = seg->prev;
}
if (stream->seg_list_tail == seg)
stream->seg_list_tail = seg->prev;
}
/**
* \brief Update the stream reassembly upon receiving a data segment
*
* | left edge | right edge based on sliding window size
* [aaa]
* [aaabbb]
* ...
* [aaabbbcccdddeeefff]
* [bbbcccdddeeefffggg] <- cut off aaa to adhere to the window size
*
* GAP situation: each chunk that is uninterrupted has it's own smsg
* [aaabbb].[dddeeefff]
* [aaa].[ccc].[eeefff]
*
* A flag will be set to indicate where the *NEW* payload starts. This
* is to aid the detection code for alert only sigs.
*
* \todo this function is too long, we need to break it up. It needs it BAD
*/
static int StreamTcpReassembleInlineRaw (TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
SCLogDebug("start p %p, seq %"PRIu32, p, TCP_GET_SEQ(p));
if (ssn->flags & STREAMTCP_FLAG_DISABLE_RAW)
SCReturnInt(0);
if (stream->seg_list == NULL) {
SCReturnInt(0);
}
uint32_t ra_base_seq = stream->ra_raw_base_seq;
StreamMsg *smsg = NULL;
uint16_t smsg_offset = 0;
uint16_t payload_offset = 0;
uint16_t payload_len = 0;
TcpSegment *seg = stream->seg_list;
uint32_t next_seq = ra_base_seq + 1;
int gap = 0;
uint16_t chunk_size = PKT_IS_TOSERVER(p) ?
stream_config.reassembly_toserver_chunk_size :
stream_config.reassembly_toclient_chunk_size;
/* determine the left edge and right edge */
uint32_t right_edge = TCP_GET_SEQ(p) + p->payload_len;
uint32_t left_edge = right_edge - chunk_size;
/* shift the window to the right if the left edge doesn't cover segments */
if (SEQ_GT(seg->seq,left_edge)) {
right_edge += (seg->seq - left_edge);
left_edge = seg->seq;
}
SCLogDebug("left_edge %"PRIu32", right_edge %"PRIu32, left_edge, right_edge);
/* loop through the segments and fill one or more msgs */
for (; seg != NULL && SEQ_LT(seg->seq, right_edge); ) {
SCLogDebug("seg %p", seg);
/* If packets are fully before ra_base_seq, skip them. We do this
* because we've reassembled up to the ra_base_seq point already,
* so we won't do anything with segments before it anyway. */
SCLogDebug("checking for pre ra_base_seq %"PRIu32" seg %p seq %"PRIu32""
" len %"PRIu16", combined %"PRIu32" and right_edge "
"%"PRIu32"", ra_base_seq, seg, seg->seq,
seg->payload_len, seg->seq+seg->payload_len, right_edge);
/* Remove the segments which are completely before the ra_base_seq */
if (SEQ_LT((seg->seq + seg->payload_len), (ra_base_seq - chunk_size)))
{
SCLogDebug("removing pre ra_base_seq %"PRIu32" seg %p seq %"PRIu32""
" len %"PRIu16"", ra_base_seq, seg, seg->seq,
seg->payload_len);
/* only remove if app layer reassembly is ready too */
if (StreamTcpAppLayerSegmentProcessed(stream, seg)) {
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
/* otherwise, just flag it for removal */
} else {
seg->flags |= SEGMENTTCP_FLAG_RAW_PROCESSED;
seg = seg->next;
}
continue;
}
/* if app layer protocol has been detected, then remove all the segments
* which has been previously processed and reassembled
*
* If the stream is in GAP state the app layer flag won't be set */
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream) &&
(seg->flags & SEGMENTTCP_FLAG_RAW_PROCESSED) &&
StreamTcpAppLayerSegmentProcessed(stream, seg))
{
SCLogDebug("segment(%p) of length %"PRIu16" has been processed,"
" so return it to pool", seg, seg->payload_len);
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
continue;
}
/* we've run into a sequence gap, wrap up any existing smsg and
* queue it so the next chunk (if any) is in a new smsg */
if (SEQ_GT(seg->seq, next_seq)) {
/* pass on pre existing smsg (if any) */
if (smsg != NULL && smsg->data_len > 0) {
StreamTcpStoreStreamChunk(ssn, smsg, p, 1);
stream->ra_raw_base_seq = ra_base_seq;
smsg = NULL;
}
gap = 1;
}
/* if the segment ends beyond left_edge we need to consider it */
if (SEQ_GT((seg->seq + seg->payload_len), left_edge)) {
SCLogDebug("seg->seq %" PRIu32 ", seg->payload_len %" PRIu32 ", "
"left_edge %" PRIu32 "", seg->seq,
seg->payload_len, left_edge);
/* handle segments partly before ra_base_seq */
if (SEQ_GT(left_edge, seg->seq)) {
payload_offset = left_edge - seg->seq;
if (SEQ_LT(right_edge, (seg->seq + seg->payload_len))) {
payload_len = (right_edge - seg->seq) - payload_offset;
} else {
payload_len = seg->payload_len - payload_offset;
}
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
BUG_ON((payload_len + payload_offset) > seg->payload_len);
}
} else {
payload_offset = 0;
if (SEQ_LT(right_edge, (seg->seq + seg->payload_len))) {
payload_len = right_edge - seg->seq;
} else {
payload_len = seg->payload_len;
}
}
SCLogDebug("payload_offset is %"PRIu16", payload_len is %"PRIu16""
" and stream->last_ack is %"PRIu32"", payload_offset,
payload_len, stream->last_ack);
if (payload_len == 0) {
SCLogDebug("no payload_len, so bail out");
break;
}
if (smsg == NULL) {
smsg = StreamMsgGetFromPool();
if (smsg == NULL) {
SCLogDebug("stream_msg_pool is empty");
return -1;
}
smsg_offset = 0;
StreamTcpSetupMsg(ssn, stream, p, smsg);
smsg->seq = ra_base_seq + 1;
}
/* copy the data into the smsg */
uint16_t copy_size = sizeof (smsg->data) - smsg_offset;
if (copy_size > payload_len) {
copy_size = payload_len;
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(smsg->data));
}
SCLogDebug("copy_size is %"PRIu16"", copy_size);
memcpy(smsg->data + smsg_offset, seg->payload + payload_offset,
copy_size);
smsg_offset += copy_size;
SCLogDebug("seg total %u, seq %u off %u copy %u, ra_base_seq %u",
(seg->seq + payload_offset + copy_size), seg->seq,
payload_offset, copy_size, ra_base_seq);
if (gap == 0 && SEQ_GT((seg->seq + payload_offset + copy_size),ra_base_seq+1)) {
ra_base_seq += copy_size;
}
SCLogDebug("ra_base_seq %"PRIu32, ra_base_seq);
smsg->data_len += copy_size;
/* queue the smsg if it's full */
if (smsg->data_len == sizeof (smsg->data)) {
StreamTcpStoreStreamChunk(ssn, smsg, p, 1);
stream->ra_raw_base_seq = ra_base_seq;
smsg = NULL;
}
/* if the payload len is bigger than what we copied, we handle the
* rest of the payload next... */
if (copy_size < payload_len) {
SCLogDebug("copy_size %" PRIu32 " < %" PRIu32 "", copy_size,
payload_len);
payload_offset += copy_size;
payload_len -= copy_size;
SCLogDebug("payload_offset is %"PRIu16", seg->payload_len is "
"%"PRIu16" and stream->last_ack is %"PRIu32"",
payload_offset, seg->payload_len, stream->last_ack);
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
/* we need a while loop here as the packets theoretically can be
* 64k */
char segment_done = FALSE;
while (segment_done == FALSE) {
SCLogDebug("new msg at offset %" PRIu32 ", payload_len "
"%" PRIu32 "", payload_offset, payload_len);
/* get a new message
XXX we need a setup function */
smsg = StreamMsgGetFromPool();
if (smsg == NULL) {
SCLogDebug("stream_msg_pool is empty");
SCReturnInt(-1);
}
smsg_offset = 0;
StreamTcpSetupMsg(ssn, stream,p,smsg);
smsg->seq = ra_base_seq + 1;
copy_size = sizeof(smsg->data) - smsg_offset;
if (copy_size > (seg->payload_len - payload_offset)) {
copy_size = (seg->payload_len - payload_offset);
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(smsg->data));
}
SCLogDebug("copy payload_offset %" PRIu32 ", smsg_offset "
"%" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, smsg_offset, copy_size);
memcpy(smsg->data + smsg_offset, seg->payload +
payload_offset, copy_size);
smsg_offset += copy_size;
if (gap == 0 && SEQ_GT((seg->seq + payload_offset + copy_size),ra_base_seq+1)) {
ra_base_seq += copy_size;
}
SCLogDebug("ra_base_seq %"PRIu32, ra_base_seq);
smsg->data_len += copy_size;
SCLogDebug("copied payload_offset %" PRIu32 ", "
"smsg_offset %" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, smsg_offset, copy_size);
if (smsg->data_len == sizeof (smsg->data)) {
StreamTcpStoreStreamChunk(ssn, smsg, p, 1);
stream->ra_raw_base_seq = ra_base_seq;
smsg = NULL;
}
/* see if we have segment payload left to process */
if ((copy_size + payload_offset) < seg->payload_len) {
payload_offset += copy_size;
payload_len -= copy_size;
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
} else {
payload_offset = 0;
segment_done = TRUE;
}
}
}
}
/* done with this segment, return it to the pool */
TcpSegment *next_seg = seg->next;
next_seq = seg->seq + seg->payload_len;
if (SEQ_LT((seg->seq + seg->payload_len), (ra_base_seq - chunk_size))) {
if (seg->flags & SEGMENTTCP_FLAG_APPLAYER_PROCESSED) {
StreamTcpRemoveSegmentFromStream(stream, seg);
SCLogDebug("removing seg %p, seg->next %p", seg, seg->next);
StreamTcpSegmentReturntoPool(seg);
} else {
seg->flags |= SEGMENTTCP_FLAG_RAW_PROCESSED;
}
}
seg = next_seg;
}
/* put the partly filled smsg in the queue */
if (smsg != NULL) {
StreamTcpStoreStreamChunk(ssn, smsg, p, 1);
smsg = NULL;
stream->ra_raw_base_seq = ra_base_seq;
}
/* see if we can clean up some segments */
left_edge = (ra_base_seq + 1) - chunk_size;
SCLogDebug("left_edge %"PRIu32", ra_base_seq %"PRIu32, left_edge, ra_base_seq);
/* loop through the segments to remove unneeded segments */
for (seg = stream->seg_list; seg != NULL && SEQ_LEQ((seg->seq + p->payload_len), left_edge); ) {
SCLogDebug("seg %p seq %"PRIu32", len %"PRIu16", sum %"PRIu32, seg, seg->seq, seg->payload_len, seg->seq+seg->payload_len);
/* only remove if app layer reassembly is ready too */
if (StreamTcpAppLayerSegmentProcessed(stream, seg)) {
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
} else {
break;
}
}
SCLogDebug("stream->ra_raw_base_seq %u", stream->ra_raw_base_seq);
SCReturnInt(0);
}
/** \brief Remove idle TcpSegments from TcpSession
*
* \param f flow
* \param flags direction flags
*/
void StreamTcpPruneSession(Flow *f, uint8_t flags)
{
if (f == NULL || f->protoctx == NULL)
return;
TcpSession *ssn = f->protoctx;
TcpStream *stream = NULL;
if (flags & STREAM_TOSERVER) {
stream = &ssn->client;
} else if (flags & STREAM_TOCLIENT) {
stream = &ssn->server;
} else {
return;
}
/* loop through the segments and fill one or more msgs */
TcpSegment *seg = stream->seg_list;
for (; seg != NULL && SEQ_LT(seg->seq, stream->last_ack);)
{
SCLogDebug("seg %p, SEQ %"PRIu32", LEN %"PRIu16", SUM %"PRIu32", FLAGS %02x",
seg, seg->seq, seg->payload_len,
(uint32_t)(seg->seq + seg->payload_len), seg->flags);
if (StreamTcpReturnSegmentCheck(f, ssn, stream, seg) == 0) {
break;
}
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
continue;
}
}
#ifdef DEBUG
static uint64_t GetStreamSize(TcpStream *stream)
{
if (stream) {
uint64_t size = 0;
uint32_t cnt = 0;
TcpSegment *seg = stream->seg_list;
while (seg) {
cnt++;
size += (uint64_t)seg->payload_len;
seg = seg->next;
}
SCLogDebug("size %"PRIu64", cnt %"PRIu32, size, cnt);
return size;
}
return (uint64_t)0;
}
static void GetSessionSize(TcpSession *ssn, Packet *p)
{
uint64_t size = 0;
if (ssn) {
size = GetStreamSize(&ssn->client);
size += GetStreamSize(&ssn->server);
//if (size > 900000)
// SCLogInfo("size %"PRIu64", packet %"PRIu64, size, p->pcap_cnt);
SCLogDebug("size %"PRIu64", packet %"PRIu64, size, p->pcap_cnt);
}
}
#endif
typedef struct ReassembleData_ {
uint32_t ra_base_seq;
uint32_t data_len;
uint8_t data[4096];
int partial; /* last segment was processed only partially */
uint32_t data_sent; /* data passed on this run */
} ReassembleData;
/** \internal
* \brief test if segment follows a gap. If so, handle the gap
*
* If in inline mode, segment may be un-ack'd. In this case we
* consider it a gap, but it's not 'final' yet.
*
* \retval bool 1 gap 0 no gap
*/
int DoHandleGap(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, TcpSegment *seg, ReassembleData *rd,
Packet *p, uint32_t next_seq)
{
if (unlikely(SEQ_GT(seg->seq, next_seq))) {
/* we've run into a sequence gap */
if (StreamTcpInlineMode()) {
/* don't conclude it's a gap until we see that the data
* that is missing was acked. */
if (SEQ_GT(seg->seq,stream->last_ack) && ssn->state != TCP_CLOSED)
return 1;
}
/* first, pass on data before the gap */
if (rd->data_len > 0) {
SCLogDebug("pre GAP data");
/* process what we have so far */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
rd->data, rd->data_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += rd->data_len;
rd->data_len = 0;
}
#ifdef DEBUG
uint32_t gap_len = seg->seq - next_seq;
SCLogDebug("expected next_seq %" PRIu32 ", got %" PRIu32 " , "
"stream->last_ack %" PRIu32 ". Seq gap %" PRIu32"",
next_seq, seg->seq, stream->last_ack, gap_len);
#endif
/* We have missed the packet and end host has ack'd it, so
* IDS should advance it's ra_base_seq and should not consider this
* packet any longer, even if it is retransmitted, as end host will
* drop it anyway */
rd->ra_base_seq = seg->seq - 1;
/* send gap "signal" */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
NULL, 0, StreamGetAppLayerFlags(ssn, stream, p)|STREAM_GAP);
AppLayerProfilingStore(ra_ctx->app_tctx, p);
/* set a GAP flag and make sure not bothering this stream anymore */
SCLogDebug("STREAMTCP_STREAM_FLAG_GAP set");
stream->flags |= STREAMTCP_STREAM_FLAG_GAP;
StreamTcpSetEvent(p, STREAM_REASSEMBLY_SEQ_GAP);
SCPerfCounterIncr(ra_ctx->counter_tcp_reass_gap, tv->sc_perf_pca);
#ifdef DEBUG
dbg_app_layer_gap++;
#endif
return 1;
}
return 0;
}
static inline int DoReassemble(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, TcpSegment *seg, ReassembleData *rd,
Packet *p)
{
/* fast path 1: segment is exactly what we need */
if (likely(rd->data_len == 0 &&
SEQ_EQ(seg->seq, rd->ra_base_seq+1) &&
SEQ_EQ(stream->last_ack, (seg->seq + seg->payload_len))))
{
/* process single segment directly */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
seg->payload, seg->payload_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += seg->payload_len;
rd->ra_base_seq += seg->payload_len;
#ifdef DEBUG
ra_ctx->fp1++;
#endif
/* if after the first data chunk we have no alproto yet,
* there is no point in continueing here. */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("no alproto after first data chunk");
return 0;
}
return 1;
/* fast path 2: segment acked completely, meets minimal size req for 0copy processing */
} else if (rd->data_len == 0 &&
SEQ_EQ(seg->seq, rd->ra_base_seq+1) &&
SEQ_GT(stream->last_ack, (seg->seq + seg->payload_len)) &&
seg->payload_len >= stream_config.zero_copy_size)
{
/* process single segment directly */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
seg->payload, seg->payload_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += seg->payload_len;
rd->ra_base_seq += seg->payload_len;
#ifdef DEBUG
ra_ctx->fp2++;
#endif
/* if after the first data chunk we have no alproto yet,
* there is no point in continueing here. */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("no alproto after first data chunk");
return 0;
}
return 1;
}
#ifdef DEBUG
ra_ctx->sp++;
#endif
uint16_t payload_offset = 0;
uint16_t payload_len = 0;
/* start clean */
rd->partial = FALSE;
/* if the segment ends beyond ra_base_seq we need to consider it */
if (SEQ_GT((seg->seq + seg->payload_len), rd->ra_base_seq+1)) {
SCLogDebug("seg->seq %" PRIu32 ", seg->payload_len %" PRIu32 ", "
"ra_base_seq %" PRIu32 ", last_ack %"PRIu32, seg->seq,
seg->payload_len, rd->ra_base_seq, stream->last_ack);
if (StreamTcpInlineMode() == 0) {
/* handle segments partly before ra_base_seq */
if (SEQ_GT(rd->ra_base_seq, seg->seq)) {
payload_offset = (rd->ra_base_seq + 1) - seg->seq;
SCLogDebug("payload_offset %u", payload_offset);
if (SEQ_LT(stream->last_ack, (seg->seq + seg->payload_len))) {
if (SEQ_LT(stream->last_ack, (rd->ra_base_seq + 1))) {
payload_len = (stream->last_ack - seg->seq);
SCLogDebug("payload_len %u", payload_len);
} else {
payload_len = (stream->last_ack - seg->seq) - payload_offset;
SCLogDebug("payload_len %u", payload_len);
}
rd->partial = TRUE;
} else {
payload_len = seg->payload_len - payload_offset;
SCLogDebug("payload_len %u", payload_len);
}
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
BUG_ON((payload_len + payload_offset) > seg->payload_len);
}
} else {
payload_offset = 0;
if (SEQ_LT(stream->last_ack, (seg->seq + seg->payload_len))) {
payload_len = stream->last_ack - seg->seq;
SCLogDebug("payload_len %u", payload_len);
rd->partial = TRUE;
} else {
payload_len = seg->payload_len;
SCLogDebug("payload_len %u", payload_len);
}
}
/* inline mode, don't consider last_ack as we process un-ACK'd segments */
} else {
/* handle segments partly before ra_base_seq */
if (SEQ_GT(rd->ra_base_seq, seg->seq)) {
payload_offset = rd->ra_base_seq - seg->seq - 1;
payload_len = seg->payload_len - payload_offset;
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
BUG_ON((payload_len + payload_offset) > seg->payload_len);
}
} else {
payload_offset = 0;
payload_len = seg->payload_len;
}
}
SCLogDebug("payload_offset is %"PRIu16", payload_len is %"PRIu16""
" and stream->last_ack is %"PRIu32"", payload_offset,
payload_len, stream->last_ack);
if (payload_len == 0) {
SCLogDebug("no payload_len, so bail out");
return 0;
}
/* copy the data into the smsg */
uint16_t copy_size = sizeof(rd->data) - rd->data_len;
if (copy_size > payload_len) {
copy_size = payload_len;
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(rd->data));
}
SCLogDebug("copy_size is %"PRIu16"", copy_size);
memcpy(rd->data + rd->data_len, seg->payload + payload_offset, copy_size);
rd->data_len += copy_size;
rd->ra_base_seq += copy_size;
SCLogDebug("ra_base_seq %"PRIu32", data_len %"PRIu32, rd->ra_base_seq, rd->data_len);
/* queue the smsg if it's full */
if (rd->data_len == sizeof(rd->data)) {
/* process what we have so far */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
rd->data, rd->data_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += rd->data_len;
rd->data_len = 0;
/* if after the first data chunk we have no alproto yet,
* there is no point in continueing here. */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("no alproto after first data chunk");
return 0;
}
}
/* if the payload len is bigger than what we copied, we handle the
* rest of the payload next... */
if (copy_size < payload_len) {
SCLogDebug("copy_size %" PRIu32 " < %" PRIu32 "", copy_size,
payload_len);
payload_offset += copy_size;
payload_len -= copy_size;
SCLogDebug("payload_offset is %"PRIu16", seg->payload_len is "
"%"PRIu16" and stream->last_ack is %"PRIu32"",
payload_offset, seg->payload_len, stream->last_ack);
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
/* we need a while loop here as the packets theoretically can be
* 64k */
char segment_done = FALSE;
while (segment_done == FALSE) {
SCLogDebug("new msg at offset %" PRIu32 ", payload_len "
"%" PRIu32 "", payload_offset, payload_len);
rd->data_len = 0;
copy_size = sizeof(rd->data) - rd->data_len;
if (copy_size > (seg->payload_len - payload_offset)) {
copy_size = (seg->payload_len - payload_offset);
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(rd->data));
}
SCLogDebug("copy payload_offset %" PRIu32 ", data_len "
"%" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, rd->data_len, copy_size);
memcpy(rd->data + rd->data_len, seg->payload +
payload_offset, copy_size);
rd->data_len += copy_size;
rd->ra_base_seq += copy_size;
SCLogDebug("ra_base_seq %"PRIu32, rd->ra_base_seq);
SCLogDebug("copied payload_offset %" PRIu32 ", "
"data_len %" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, rd->data_len, copy_size);
if (rd->data_len == sizeof(rd->data)) {
/* process what we have so far */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
rd->data, rd->data_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
rd->data_sent += rd->data_len;
rd->data_len = 0;
/* if after the first data chunk we have no alproto yet,
* there is no point in continueing here. */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("no alproto after first data chunk");
return 0;
}
}
/* see if we have segment payload left to process */
if ((copy_size + payload_offset) < seg->payload_len) {
payload_offset += copy_size;
payload_len -= copy_size;
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
} else {
payload_offset = 0;
segment_done = TRUE;
}
}
}
}
return 1;
}
/**
* \brief Update the stream reassembly upon receiving an ACK packet.
*
* Stream is in the opposite direction of the packet, as the ACK-packet
* is ACK'ing the stream.
*
* One of the utilities call by this function AppLayerHandleTCPData(),
* has a feature where it will call this very same function for the
* stream opposing the stream it is called with. This shouldn't cause
* any issues, since processing of each stream is independent of the
* other stream.
*
* \todo this function is too long, we need to break it up. It needs it BAD
*/
int StreamTcpReassembleAppLayer (ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream,
Packet *p)
{
SCEnter();
/* this function can be directly called by app layer protocol
* detection. */
if (stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) {
SCLogDebug("stream no reassembly flag set. Mostly called via "
"app proto detection.");
SCReturnInt(0);
}
SCLogDebug("stream->seg_list %p", stream->seg_list);
#ifdef DEBUG
PrintList(stream->seg_list);
GetSessionSize(ssn, p);
#endif
/* if no segments are in the list or all are already processed,
* and state is beyond established, we send an empty msg */
TcpSegment *seg_tail = stream->seg_list_tail;
if (seg_tail == NULL ||
(seg_tail->flags & SEGMENTTCP_FLAG_APPLAYER_PROCESSED))
{
/* send an empty EOF msg if we have no segments but TCP state
* is beyond ESTABLISHED */
if (ssn->state >= TCP_CLOSING || (p->flags & PKT_PSEUDO_STREAM_END)) {
SCLogDebug("sending empty eof message");
/* send EOF to app layer */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
NULL, 0,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
SCReturnInt(0);
}
}
/* no segments, nothing to do */
if (stream->seg_list == NULL) {
SCLogDebug("no segments in the list to reassemble");
SCReturnInt(0);
}
if (stream->flags & STREAMTCP_STREAM_FLAG_GAP) {
SCReturnInt(0);
}
/* stream->ra_app_base_seq remains at stream->isn until protocol is
* detected. */
ReassembleData rd;
rd.ra_base_seq = stream->ra_app_base_seq;
rd.data_len = 0;
rd.data_sent = 0;
rd.partial = FALSE;
uint32_t next_seq = rd.ra_base_seq + 1;
SCLogDebug("ra_base_seq %"PRIu32", last_ack %"PRIu32", next_seq %"PRIu32,
rd.ra_base_seq, stream->last_ack, next_seq);
/* loop through the segments and fill one or more msgs */
TcpSegment *seg = stream->seg_list;
SCLogDebug("pre-loop seg %p", seg);
/* Check if we have a gap at the start of the list. If last_ack is
* bigger than the list start and the list start is bigger than
* next_seq, we know we are missing data that has been ack'd. That
* won't get retransmitted, so it's a data gap.
*/
if (!(p->flow->flags & FLOW_NO_APPLAYER_INSPECTION)) {
if (SEQ_GT(seg->seq, next_seq) && SEQ_LT(seg->seq, stream->last_ack)) {
/* send gap signal */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
NULL, 0,
StreamGetAppLayerFlags(ssn, stream, p)|STREAM_GAP);
AppLayerProfilingStore(ra_ctx->app_tctx, p);
/* set a GAP flag and make sure not bothering this stream anymore */
SCLogDebug("STREAMTCP_STREAM_FLAG_GAP set");
stream->flags |= STREAMTCP_STREAM_FLAG_GAP;
StreamTcpSetEvent(p, STREAM_REASSEMBLY_SEQ_GAP);
SCPerfCounterIncr(ra_ctx->counter_tcp_reass_gap, tv->sc_perf_pca);
#ifdef DEBUG
dbg_app_layer_gap++;
#endif
SCReturnInt(0);
}
}
for (; seg != NULL; )
{
/* if in inline mode, we process all segments regardless of whether
* they are ack'd or not. In non-inline, we process only those that
* are at least partly ack'd. */
if (StreamTcpInlineMode() == 0 && SEQ_GEQ(seg->seq, stream->last_ack))
break;
SCLogDebug("seg %p, SEQ %"PRIu32", LEN %"PRIu16", SUM %"PRIu32,
seg, seg->seq, seg->payload_len,
(uint32_t)(seg->seq + seg->payload_len));
if (p->flow->flags & FLOW_NO_APPLAYER_INSPECTION) {
SCLogDebug("FLOW_NO_APPLAYER_INSPECTION set, breaking out");
break;
}
if (StreamTcpReturnSegmentCheck(p->flow, ssn, stream, seg) == 1) {
SCLogDebug("removing segment");
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
continue;
} else if (StreamTcpAppLayerSegmentProcessed(stream, seg)) {
TcpSegment *next_seg = seg->next;
seg = next_seg;
continue;
}
/* check if we have a sequence gap and if so, handle it */
if (DoHandleGap(tv, ra_ctx, ssn, stream, seg, &rd, p, next_seq) == 1)
break;
/* process this segment */
if (DoReassemble(tv, ra_ctx, ssn, stream, seg, &rd, p) == 0)
break;
/* done with this segment, return it to the pool */
TcpSegment *next_seg = seg->next;
next_seq = seg->seq + seg->payload_len;
if (rd.partial == FALSE) {
SCLogDebug("fully done with segment in app layer reassembly (seg %p seq %"PRIu32")",
seg, seg->seq);
seg->flags |= SEGMENTTCP_FLAG_APPLAYER_PROCESSED;
SCLogDebug("flags now %02x", seg->flags);
} else {
SCLogDebug("not yet fully done with segment in app layer reassembly");
}
seg = next_seg;
}
/* put the partly filled smsg in the queue to the l7 handler */
if (rd.data_len > 0) {
SCLogDebug("data_len > 0, %u", rd.data_len);
/* process what we have so far */
BUG_ON(rd.data_len > sizeof(rd.data));
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
rd.data, rd.data_len,
StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
}
/* if no data was sent to the applayer, we send it a empty 'nudge'
* when in inline mode */
if (StreamTcpInlineMode() && rd.data_sent == 0 && ssn->state > TCP_ESTABLISHED) {
SCLogDebug("sending empty eof message");
/* send EOF to app layer */
AppLayerHandleTCPData(tv, ra_ctx, p, p->flow, ssn, stream,
NULL, 0, StreamGetAppLayerFlags(ssn, stream, p));
AppLayerProfilingStore(ra_ctx->app_tctx, p);
}
/* store ra_base_seq in the stream */
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
stream->ra_app_base_seq = rd.ra_base_seq;
} else {
TcpSegment *tmp_seg = stream->seg_list;
while (tmp_seg != NULL) {
tmp_seg->flags &= ~SEGMENTTCP_FLAG_APPLAYER_PROCESSED;
tmp_seg = tmp_seg->next;
}
}
SCLogDebug("stream->ra_app_base_seq %u", stream->ra_app_base_seq);
SCReturnInt(0);
}
typedef struct ReassembleRawData_ {
uint32_t ra_base_seq;
int partial; /* last segment was processed only partially */
StreamMsg *smsg;
uint16_t smsg_offset; // TODO diff with smsg->data_len?
} ReassembleRawData;
static void DoHandleRawGap(TcpSession *ssn, TcpStream *stream, TcpSegment *seg, Packet *p,
ReassembleRawData *rd, uint32_t next_seq)
{
/* we've run into a sequence gap */
if (SEQ_GT(seg->seq, next_seq)) {
/* pass on pre existing smsg (if any) */
if (rd->smsg != NULL && rd->smsg->data_len > 0) {
/* if app layer protocol has not been detected till yet,
then check did we have sent message to app layer already
or not. If not then sent the message and set flag that first
message has been sent. No more data till proto has not
been detected */
StreamTcpStoreStreamChunk(ssn, rd->smsg, p, 0);
stream->ra_raw_base_seq = rd->ra_base_seq;
rd->smsg = NULL;
}
/* see what the length of the gap is, gap length is seg->seq -
* (ra_base_seq +1) */
#ifdef DEBUG
uint32_t gap_len = seg->seq - next_seq;
SCLogDebug("expected next_seq %" PRIu32 ", got %" PRIu32 " , "
"stream->last_ack %" PRIu32 ". Seq gap %" PRIu32"",
next_seq, seg->seq, stream->last_ack, gap_len);
#endif
stream->ra_raw_base_seq = rd->ra_base_seq;
/* We have missed the packet and end host has ack'd it, so
* IDS should advance it's ra_base_seq and should not consider this
* packet any longer, even if it is retransmitted, as end host will
* drop it anyway */
rd->ra_base_seq = seg->seq - 1;
}
}
static int DoRawReassemble(TcpSession *ssn, TcpStream *stream, TcpSegment *seg, Packet *p,
ReassembleRawData *rd)
{
uint16_t payload_offset = 0;
uint16_t payload_len = 0;
/* start clean */
rd->partial = FALSE;
/* if the segment ends beyond ra_base_seq we need to consider it */
if (SEQ_GT((seg->seq + seg->payload_len), rd->ra_base_seq+1)) {
SCLogDebug("seg->seq %" PRIu32 ", seg->payload_len %" PRIu32 ", "
"ra_base_seq %" PRIu32 "", seg->seq,
seg->payload_len, rd->ra_base_seq);
/* handle segments partly before ra_base_seq */
if (SEQ_GT(rd->ra_base_seq, seg->seq)) {
payload_offset = rd->ra_base_seq - seg->seq;
if (SEQ_LT(stream->last_ack, (seg->seq + seg->payload_len))) {
if (SEQ_LT(stream->last_ack, rd->ra_base_seq)) {
payload_len = (stream->last_ack - seg->seq);
} else {
payload_len = (stream->last_ack - seg->seq) - payload_offset;
}
rd->partial = TRUE;
} else {
payload_len = seg->payload_len - payload_offset;
}
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
BUG_ON((payload_len + payload_offset) > seg->payload_len);
}
} else {
payload_offset = 0;
if (SEQ_LT(stream->last_ack, (seg->seq + seg->payload_len))) {
payload_len = stream->last_ack - seg->seq;
rd->partial = TRUE;
} else {
payload_len = seg->payload_len;
}
}
SCLogDebug("payload_offset is %"PRIu16", payload_len is %"PRIu16""
" and stream->last_ack is %"PRIu32"", payload_offset,
payload_len, stream->last_ack);
if (payload_len == 0) {
SCLogDebug("no payload_len, so bail out");
return 1; // TODO
}
if (rd->smsg == NULL) {
rd->smsg = StreamMsgGetFromPool();
if (rd->smsg == NULL) {
SCLogDebug("stream_msg_pool is empty");
return -1;
}
rd->smsg_offset = 0;
StreamTcpSetupMsg(ssn, stream, p, rd->smsg);
rd->smsg->seq = rd->ra_base_seq + 1;
SCLogDebug("smsg->seq %u", rd->smsg->seq);
}
/* copy the data into the smsg */
uint16_t copy_size = sizeof (rd->smsg->data) - rd->smsg_offset;
if (copy_size > payload_len) {
copy_size = payload_len;
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(rd->smsg->data));
}
SCLogDebug("copy_size is %"PRIu16"", copy_size);
memcpy(rd->smsg->data + rd->smsg_offset, seg->payload + payload_offset,
copy_size);
rd->smsg_offset += copy_size;
rd->ra_base_seq += copy_size;
SCLogDebug("ra_base_seq %"PRIu32, rd->ra_base_seq);
rd->smsg->data_len += copy_size;
/* queue the smsg if it's full */
if (rd->smsg->data_len == sizeof (rd->smsg->data)) {
StreamTcpStoreStreamChunk(ssn, rd->smsg, p, 0);
stream->ra_raw_base_seq = rd->ra_base_seq;
rd->smsg = NULL;
}
/* if the payload len is bigger than what we copied, we handle the
* rest of the payload next... */
if (copy_size < payload_len) {
SCLogDebug("copy_size %" PRIu32 " < %" PRIu32 "", copy_size,
payload_len);
payload_offset += copy_size;
payload_len -= copy_size;
SCLogDebug("payload_offset is %"PRIu16", seg->payload_len is "
"%"PRIu16" and stream->last_ack is %"PRIu32"",
payload_offset, seg->payload_len, stream->last_ack);
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
/* we need a while loop here as the packets theoretically can be
* 64k */
char segment_done = FALSE;
while (segment_done == FALSE) {
SCLogDebug("new msg at offset %" PRIu32 ", payload_len "
"%" PRIu32 "", payload_offset, payload_len);
/* get a new message
XXX we need a setup function */
rd->smsg = StreamMsgGetFromPool();
if (rd->smsg == NULL) {
SCLogDebug("stream_msg_pool is empty");
SCReturnInt(-1);
}
rd->smsg_offset = 0;
StreamTcpSetupMsg(ssn, stream, p, rd->smsg);
rd->smsg->seq = rd->ra_base_seq + 1;
copy_size = sizeof(rd->smsg->data) - rd->smsg_offset;
if (copy_size > payload_len) {
copy_size = payload_len;
}
if (SCLogDebugEnabled()) {
BUG_ON(copy_size > sizeof(rd->smsg->data));
}
SCLogDebug("copy payload_offset %" PRIu32 ", smsg_offset "
"%" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, rd->smsg_offset, copy_size);
memcpy(rd->smsg->data + rd->smsg_offset, seg->payload +
payload_offset, copy_size);
rd->smsg_offset += copy_size;
rd->ra_base_seq += copy_size;
SCLogDebug("ra_base_seq %"PRIu32, rd->ra_base_seq);
rd->smsg->data_len += copy_size;
SCLogDebug("copied payload_offset %" PRIu32 ", "
"smsg_offset %" PRIu32 ", copy_size %" PRIu32 "",
payload_offset, rd->smsg_offset, copy_size);
if (rd->smsg->data_len == sizeof(rd->smsg->data)) {
StreamTcpStoreStreamChunk(ssn, rd->smsg, p, 0);
stream->ra_raw_base_seq = rd->ra_base_seq;
rd->smsg = NULL;
}
/* see if we have segment payload left to process */
if (copy_size < payload_len) {
payload_offset += copy_size;
payload_len -= copy_size;
if (SCLogDebugEnabled()) {
BUG_ON(payload_offset > seg->payload_len);
}
} else {
payload_offset = 0;
segment_done = TRUE;
}
}
}
}
return 1;
}
/**
* \brief Update the stream reassembly upon receiving an ACK packet.
* \todo this function is too long, we need to break it up. It needs it BAD
*/
static int StreamTcpReassembleRaw (TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
SCLogDebug("start p %p", p);
if (ssn->flags & STREAMTCP_FLAG_DISABLE_RAW)
SCReturnInt(0);
if (stream->seg_list == NULL) {
SCLogDebug("no segments in the list to reassemble");
SCReturnInt(0);
}
#if 0
if (ssn->state <= TCP_ESTABLISHED &&
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream)) {
SCLogDebug("only starting raw reassembly after app layer protocol "
"detection has completed.");
SCReturnInt(0);
}
#endif
/* check if we have enough data */
if (StreamTcpReassembleRawCheckLimit(ssn,stream,p) == 0) {
SCLogDebug("not yet reassembling");
SCReturnInt(0);
}
TcpSegment *seg = stream->seg_list;
ReassembleRawData rd;
rd.smsg = NULL;
rd.ra_base_seq = stream->ra_raw_base_seq;
rd.smsg_offset = 0;
uint32_t next_seq = rd.ra_base_seq + 1;
SCLogDebug("ra_base_seq %"PRIu32", last_ack %"PRIu32", next_seq %"PRIu32,
rd.ra_base_seq, stream->last_ack, next_seq);
/* loop through the segments and fill one or more msgs */
for (; seg != NULL && SEQ_LT(seg->seq, stream->last_ack);)
{
SCLogDebug("seg %p, SEQ %"PRIu32", LEN %"PRIu16", SUM %"PRIu32", flags %02x",
seg, seg->seq, seg->payload_len,
(uint32_t)(seg->seq + seg->payload_len), seg->flags);
if (StreamTcpReturnSegmentCheck(p->flow, ssn, stream, seg) == 1) {
SCLogDebug("removing segment");
TcpSegment *next_seg = seg->next;
StreamTcpRemoveSegmentFromStream(stream, seg);
StreamTcpSegmentReturntoPool(seg);
seg = next_seg;
continue;
} else if(seg->flags & SEGMENTTCP_FLAG_RAW_PROCESSED) {
TcpSegment *next_seg = seg->next;
seg = next_seg;
continue;
}
DoHandleRawGap(ssn, stream, seg, p, &rd, next_seq);
if (DoRawReassemble(ssn, stream, seg, p, &rd) == 0)
break;
/* done with this segment, return it to the pool */
TcpSegment *next_seg = seg->next;
next_seq = seg->seq + seg->payload_len;
if (rd.partial == FALSE) {
SCLogDebug("fully done with segment in raw reassembly (seg %p seq %"PRIu32")",
seg, seg->seq);
seg->flags |= SEGMENTTCP_FLAG_RAW_PROCESSED;
SCLogDebug("flags now %02x", seg->flags);
} else {
SCLogDebug("not yet fully done with segment in raw reassembly");
}
seg = next_seg;
}
/* put the partly filled smsg in the queue to the l7 handler */
if (rd.smsg != NULL) {
StreamTcpStoreStreamChunk(ssn, rd.smsg, p, 0);
rd.smsg = NULL;
stream->ra_raw_base_seq = rd.ra_base_seq;
}
SCReturnInt(0);
}
/** \brief update app layer and raw reassembly
*
* \retval r 0 on success, -1 on error
*/
int StreamTcpReassembleHandleSegmentUpdateACK (ThreadVars *tv,
TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
SCLogDebug("stream->seg_list %p", stream->seg_list);
int r = 0;
if (!(StreamTcpInlineMode())) {
if (StreamTcpReassembleAppLayer(tv, ra_ctx, ssn, stream, p) < 0)
r = -1;
if (StreamTcpReassembleRaw(ra_ctx, ssn, stream, p) < 0)
r = -1;
}
SCLogDebug("stream->seg_list %p", stream->seg_list);
SCReturnInt(r);
}
int StreamTcpReassembleHandleSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, TcpStream *stream,
Packet *p, PacketQueue *pq)
{
SCEnter();
SCLogDebug("ssn %p, stream %p, p %p, p->payload_len %"PRIu16"",
ssn, stream, p, p->payload_len);
/* we need to update the opposing stream in
* StreamTcpReassembleHandleSegmentUpdateACK */
TcpStream *opposing_stream = NULL;
if (stream == &ssn->client) {
opposing_stream = &ssn->server;
} else {
opposing_stream = &ssn->client;
}
/* handle ack received */
if (StreamTcpReassembleHandleSegmentUpdateACK(tv, ra_ctx, ssn, opposing_stream, p) != 0)
{
SCLogDebug("StreamTcpReassembleHandleSegmentUpdateACK error");
SCReturnInt(-1);
}
/* If no stream reassembly/application layer protocol inspection, then
simple return */
if (p->payload_len > 0 && !(stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
SCLogDebug("calling StreamTcpReassembleHandleSegmentHandleData");
if (StreamTcpReassembleHandleSegmentHandleData(tv, ra_ctx, ssn, stream, p) != 0) {
SCLogDebug("StreamTcpReassembleHandleSegmentHandleData error");
SCReturnInt(-1);
}
p->flags |= PKT_STREAM_ADD;
}
/* in stream inline mode even if we have no data we call the reassembly
* functions to handle EOF */
if (StreamTcpInlineMode()) {
int r = 0;
if (StreamTcpReassembleAppLayer(tv, ra_ctx, ssn, stream, p) < 0)
r = -1;
if (StreamTcpReassembleInlineRaw(ra_ctx, ssn, stream, p) < 0)
r = -1;
if (r < 0) {
SCReturnInt(-1);
}
}
StreamTcpReassembleMemuseCounter(tv, ra_ctx);
SCReturnInt(0);
}
/**
* \brief Function to replace the data from a specific point up to given length.
*
* \param dst_seg Destination segment to replace the data
* \param src_seg Source segment of which data is to be written to destination
* \param start_point Starting point to replace the data onwards
* \param len Length up to which data is need to be replaced
*
* \todo VJ We can remove the abort()s later.
* \todo VJ Why not memcpy?
*/
void StreamTcpSegmentDataReplace(TcpSegment *dst_seg, TcpSegment *src_seg,
uint32_t start_point, uint16_t len)
{
uint32_t seq;
uint16_t src_pos = 0;
uint16_t dst_pos = 0;
SCLogDebug("start_point %u", start_point);
if (SEQ_GT(start_point, dst_seg->seq)) {
dst_pos = start_point - dst_seg->seq;
} else if (SEQ_LT(start_point, dst_seg->seq)) {
dst_pos = dst_seg->seq - start_point;
}
if (SCLogDebugEnabled()) {
BUG_ON(((len + dst_pos) - 1) > dst_seg->payload_len);
} else {
if (((len + dst_pos) - 1) > dst_seg->payload_len)
return;
}
src_pos = (uint16_t)(start_point - src_seg->seq);
SCLogDebug("Replacing data from dst_pos %"PRIu16"", dst_pos);
for (seq = start_point; SEQ_LT(seq, (start_point + len)) &&
src_pos < src_seg->payload_len && dst_pos < dst_seg->payload_len;
seq++, dst_pos++, src_pos++)
{
dst_seg->payload[dst_pos] = src_seg->payload[src_pos];
}
SCLogDebug("Replaced data of size %"PRIu16" up to src_pos %"PRIu16
" dst_pos %"PRIu16, len, src_pos, dst_pos);
}
/**
* \brief Function to compare the data from a specific point up to given length.
*
* \param dst_seg Destination segment to compare the data
* \param src_seg Source segment of which data is to be compared to destination
* \param start_point Starting point to compare the data onwards
* \param len Length up to which data is need to be compared
*
* \retval 1 same
* \retval 0 different
*/
static int StreamTcpSegmentDataCompare(TcpSegment *dst_seg, TcpSegment *src_seg,
uint32_t start_point, uint16_t len)
{
uint32_t seq;
uint16_t src_pos = 0;
uint16_t dst_pos = 0;
SCLogDebug("start_point %u dst_seg %u src_seg %u", start_point, dst_seg->seq, src_seg->seq);
if (SEQ_GT(start_point, dst_seg->seq)) {
SCLogDebug("start_point %u > dst %u", start_point, dst_seg->seq);
dst_pos = start_point - dst_seg->seq;
} else if (SEQ_LT(start_point, dst_seg->seq)) {
SCLogDebug("start_point %u < dst %u", start_point, dst_seg->seq);
dst_pos = dst_seg->seq - start_point;
}
if (SCLogDebugEnabled()) {
BUG_ON(((len + dst_pos) - 1) > dst_seg->payload_len);
} else {
if (((len + dst_pos) - 1) > dst_seg->payload_len)
return 1;
}
src_pos = (uint16_t)(start_point - src_seg->seq);
SCLogDebug("Comparing data from dst_pos %"PRIu16", src_pos %u", dst_pos, src_pos);
for (seq = start_point; SEQ_LT(seq, (start_point + len)) &&
src_pos < src_seg->payload_len && dst_pos < dst_seg->payload_len;
seq++, dst_pos++, src_pos++)
{
if (dst_seg->payload[dst_pos] != src_seg->payload[src_pos]) {
SCLogDebug("data is different %02x != %02x, dst_pos %u, src_pos %u", dst_seg->payload[dst_pos], src_seg->payload[src_pos], dst_pos, src_pos);
return 0;
}
}
SCLogDebug("Compared data of size %"PRIu16" up to src_pos %"PRIu16
" dst_pos %"PRIu16, len, src_pos, dst_pos);
return 1;
}
/**
* \brief Function to copy the data from src_seg to dst_seg.
*
* \param dst_seg Destination segment for copying the contents
* \param src_seg Source segment to copy its contents
*
* \todo VJ wouldn't a memcpy be more appropriate here?
*
* \warning Both segments need to be properly initialized.
*/
void StreamTcpSegmentDataCopy(TcpSegment *dst_seg, TcpSegment *src_seg)
{
uint32_t u;
uint16_t dst_pos = 0;
uint16_t src_pos = 0;
uint32_t seq;
if (SEQ_GT(dst_seg->seq, src_seg->seq)) {
src_pos = dst_seg->seq - src_seg->seq;
seq = dst_seg->seq;
} else {
dst_pos = src_seg->seq - dst_seg->seq;
seq = src_seg->seq;
}
SCLogDebug("Copying data from seq %"PRIu32"", seq);
for (u = seq;
(SEQ_LT(u, (src_seg->seq + src_seg->payload_len)) &&
SEQ_LT(u, (dst_seg->seq + dst_seg->payload_len))); u++)
{
//SCLogDebug("u %"PRIu32, u);
dst_seg->payload[dst_pos] = src_seg->payload[src_pos];
dst_pos++;
src_pos++;
}
SCLogDebug("Copyied data of size %"PRIu16" up to dst_pos %"PRIu16"",
src_pos, dst_pos);
}
/**
* \brief Function to get the segment of required length from the pool.
*
* \param len Length which tells the required size of needed segment.
*
* \retval seg Segment from the pool or NULL
*/
TcpSegment* StreamTcpGetSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, uint16_t len)
{
uint16_t idx = segment_pool_idx[len];
SCLogDebug("segment_pool_idx %" PRIu32 " for payload_len %" PRIu32 "",
idx, len);
SCMutexLock(&segment_pool_mutex[idx]);
TcpSegment *seg = (TcpSegment *) PoolGet(segment_pool[idx]);
SCLogDebug("segment_pool[%u]->empty_stack_size %u, segment_pool[%u]->alloc_"
"list_size %u, alloc %u", idx, segment_pool[idx]->empty_stack_size,
idx, segment_pool[idx]->alloc_stack_size,
segment_pool[idx]->allocated);
SCMutexUnlock(&segment_pool_mutex[idx]);
SCLogDebug("seg we return is %p", seg);
if (seg == NULL) {
SCLogDebug("segment_pool[%u]->empty_stack_size %u, "
"alloc %u", idx, segment_pool[idx]->empty_stack_size,
segment_pool[idx]->allocated);
/* Increment the counter to show that we are not able to serve the
segment request due to memcap limit */
SCPerfCounterIncr(ra_ctx->counter_tcp_segment_memcap, tv->sc_perf_pca);
} else {
seg->flags = stream_config.segment_init_flags;
seg->next = NULL;
seg->prev = NULL;
}
#ifdef DEBUG
SCMutexLock(&segment_pool_cnt_mutex);
segment_pool_cnt++;
SCMutexUnlock(&segment_pool_cnt_mutex);
#endif
return seg;
}
/**
* \brief Trigger RAW stream reassembly
*
* Used by AppLayerTriggerRawStreamReassembly to trigger RAW stream
* reassembly from the applayer, for example upon completion of a
* HTTP request.
*
* Works by setting a flag in the TcpSession that is unset as soon
* as it's checked. Since everything happens when operating under
* a single lock period, no side effects are expected.
*
* \param ssn TcpSession
*/
void StreamTcpReassembleTriggerRawReassembly(TcpSession *ssn)
{
#ifdef DEBUG
BUG_ON(ssn == NULL);
#endif
if (ssn != NULL) {
SCLogDebug("flagged ssn %p for immediate raw reassembly", ssn);
ssn->flags |= STREAMTCP_FLAG_TRIGGER_RAW_REASSEMBLY;
}
}
#ifdef UNITTESTS
/** unit tests and it's support functions below */
static uint32_t UtSsnSmsgCnt(TcpSession *ssn, uint8_t direction)
{
uint32_t cnt = 0;
StreamMsg *smsg = (direction == STREAM_TOSERVER) ?
ssn->toserver_smsg_head :
ssn->toclient_smsg_head;
while (smsg) {
cnt++;
smsg = smsg->next;
}
return cnt;
}
/** \brief The Function tests the reassembly engine working for different
* OSes supported. It includes all the OS cases and send
* crafted packets to test the reassembly.
*
* \param stream The stream which will contain the reassembled segments
*/
static int StreamTcpReassembleStreamTest(TcpStream *stream)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x42, 2, 4); /*BB*/
p->tcph->th_seq = htonl(16);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x44, 1, 4); /*D*/
p->tcph->th_seq = htonl(22);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x45, 2, 4); /*EE*/
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x46, 3, 4); /*FFF*/
p->tcph->th_seq = htonl(27);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x47, 2, 4); /*GG*/
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x48, 2, 4); /*HH*/
p->tcph->th_seq = htonl(32);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x49, 1, 4); /*I*/
p->tcph->th_seq = htonl(34);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4a, 4, 4); /*JJJJ*/
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 4;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4b, 3, 4); /*KKK*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4c, 3, 4); /*LLL*/
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4d, 3, 4); /*MMM*/
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4e, 1, 4); /*N*/
p->tcph->th_seq = htonl(28);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4f, 1, 4); /*O*/
p->tcph->th_seq = htonl(31);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x50, 1, 4); /*P*/
p->tcph->th_seq = htonl(32);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x51, 2, 4); /*QQ*/
p->tcph->th_seq = htonl(34);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x30, 1, 4); /*0*/
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpReassembleFreeThreadCtx(ra_ctx);
SCFree(p);
return 1;
}
/** \brief The Function to create the packet with given payload, which is used
* to test the reassembly of the engine.
*
* \param payload The variable used to store the payload contents of the
* current packet.
* \param value The value which current payload will have for this packet
* \param payload_len The length of the filed payload for current packet.
* \param len Length of the payload array
*/
void StreamTcpCreateTestPacket(uint8_t *payload, uint8_t value,
uint8_t payload_len, uint8_t len)
{
uint8_t i;
for (i = 0; i < payload_len; i++)
payload[i] = value;
for (; i < len; i++)
payload = NULL;
}
/** \brief The Function Checks the reassembled stream contents against predefined
* stream contents according to OS policy used.
*
* \param stream_policy Predefined value of stream for different OS policies
* \param stream Reassembled stream returned from the reassembly functions
*/
int StreamTcpCheckStreamContents(uint8_t *stream_policy, uint16_t sp_size, TcpStream *stream)
{
TcpSegment *temp;
uint16_t i = 0;
uint8_t j;
#ifdef DEBUG
if (SCLogDebugEnabled()) {
TcpSegment *temp1;
for (temp1 = stream->seg_list; temp1 != NULL; temp1 = temp1->next)
PrintRawDataFp(stdout, temp1->payload, temp1->payload_len);
PrintRawDataFp(stdout, stream_policy, sp_size);
}
#endif
for (temp = stream->seg_list; temp != NULL; temp = temp->next) {
j = 0;
for (; j < temp->payload_len; j++) {
SCLogDebug("i %"PRIu16", len %"PRIu32", stream %"PRIx32" and temp is %"PRIx8"",
i, temp->payload_len, stream_policy[i], temp->payload[j]);
if (stream_policy[i] == temp->payload[j]) {
i++;
continue;
} else
return 0;
}
}
return 1;
}
/** \brief The Function Checks the Stream Queue contents against predefined
* stream contents.
*
* \param stream_contents Predefined value of stream contents
* \param stream Queue which has the stream contents
*
* \retval On success the function returns 1, on failure 0.
*/
static int StreamTcpCheckChunks (TcpSession *ssn, uint8_t *stream_contents)
{
SCEnter();
StreamMsg *msg;
uint16_t i = 0;
uint8_t j;
uint8_t cnt = 0;
if (ssn == NULL) {
printf("ssn == NULL, ");
SCReturnInt(0);
}
if (ssn->toserver_smsg_head == NULL) {
printf("ssn->toserver_smsg_head == NULL, ");
SCReturnInt(0);
}
msg = ssn->toserver_smsg_head;
while(msg != NULL) {
cnt++;
j = 0;
for (; j < msg->data_len; j++) {
SCLogDebug("i is %" PRIu32 " and len is %" PRIu32 " and temp is %" PRIx32 "", i, msg->data_len, msg->data[j]);
if (stream_contents[i] == msg->data[j]) {
i++;
continue;
} else {
SCReturnInt(0);
}
}
msg = msg->next;
}
SCReturnInt(1);
}
/* \brief The function craft packets to test the overlapping, where
* new segment stats before the list segment.
*
* \param stream The stream which will contain the reassembled segments and
* also tells the OS policy used for reassembling the segments.
*/
static int StreamTcpTestStartsBeforeListSegment(TcpStream *stream) {
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 1, 4); /*B*/
p->tcph->th_seq = htonl(16);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x44, 1, 4); /*D*/
p->tcph->th_seq = htonl(22);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x45, 2, 4); /*EE*/
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4a, 4, 4); /*JJJJ*/
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 4;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
SCLogDebug("sending segment with SEQ 21, len 3");
StreamTcpCreateTestPacket(payload, 0x4c, 3, 4); /*LLL*/
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4d, 3, 4); /*MMM*/
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
SCFree(p);
return 1;
}
/* \brief The function craft packets to test the overlapping, where
* new segment stats at the same seq no. as the list segment.
*
* \param stream The stream which will contain the reassembled segments and
* also tells the OS policy used for reassembling the segments.
*/
static int StreamTcpTestStartsAtSameListSegment(TcpStream *stream)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x48, 2, 4); /*HH*/
p->tcph->th_seq = htonl(32);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x49, 1, 4); /*I*/
p->tcph->th_seq = htonl(34);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4b, 3, 4); /*KKK*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4c, 4, 4); /*LLLL*/
p->tcph->th_seq = htonl(18);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 4;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x50, 1, 4); /*P*/
p->tcph->th_seq = htonl(32);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x51, 2, 4); /*QQ*/
p->tcph->th_seq = htonl(34);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
SCFree(p);
return 1;
}
/* \brief The function craft packets to test the overlapping, where
* new segment stats after the list segment.
*
* \param stream The stream which will contain the reassembled segments and
* also tells the OS policy used for reassembling the segments.
*/
static int StreamTcpTestStartsAfterListSegment(TcpStream *stream)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x46, 3, 4); /*FFF*/
p->tcph->th_seq = htonl(27);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 3;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x47, 2, 4); /*GG*/
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4a, 2, 4); /*JJ*/
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 2;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4f, 1, 4); /*O*/
p->tcph->th_seq = htonl(31);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpCreateTestPacket(payload, 0x4e, 1, 4); /*N*/
p->tcph->th_seq = htonl(28);
p->tcph->th_ack = htonl(31);
p->payload = payload;
p->payload_len = 1;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
SCFree(p);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and BSD policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest01(void)
{
TcpStream stream;
uint8_t stream_before_bsd[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_bsd,sizeof(stream_before_bsd), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and BSD policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest02(void)
{
TcpStream stream;
uint8_t stream_same_bsd[8] = {0x43, 0x43, 0x43, 0x4c, 0x48, 0x48,
0x49, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_bsd, sizeof(stream_same_bsd), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and BSD policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest03(void)
{
TcpStream stream;
uint8_t stream_after_bsd[8] = {0x41, 0x41, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_bsd, sizeof(stream_after_bsd), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and BSD policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest04(void)
{
TcpStream stream;
uint8_t stream_bsd[25] = {0x30, 0x41, 0x41, 0x41, 0x4a, 0x4a, 0x42, 0x43,
0x43, 0x43, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x49, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly: ");
return 0;
}
if (StreamTcpCheckStreamContents(stream_bsd, sizeof(stream_bsd), &stream) == 0) {
printf("failed in stream matching: ");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and VISTA policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest05(void)
{
TcpStream stream;
uint8_t stream_before_vista[10] = {0x4a, 0x41, 0x42, 0x4a, 0x4c, 0x44,
0x4c, 0x4d, 0x45, 0x45};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_VISTA;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_vista, sizeof(stream_before_vista), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and VISTA policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest06(void)
{
TcpStream stream;
uint8_t stream_same_vista[8] = {0x43, 0x43, 0x43, 0x4c, 0x48, 0x48,
0x49, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_VISTA;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_vista, sizeof(stream_same_vista), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and BSD policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest07(void)
{
TcpStream stream;
uint8_t stream_after_vista[8] = {0x41, 0x41, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_VISTA;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_vista, sizeof(stream_after_vista), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and VISTA policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest08(void)
{
TcpStream stream;
uint8_t stream_vista[25] = {0x30, 0x41, 0x41, 0x41, 0x4a, 0x42, 0x42, 0x43,
0x43, 0x43, 0x4c, 0x44, 0x4c, 0x4d, 0x45, 0x45,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x49, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_VISTA;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_vista, sizeof(stream_vista), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and LINUX policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest09(void)
{
TcpStream stream;
uint8_t stream_before_linux[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_linux, sizeof(stream_before_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and LINUX policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest10(void)
{
TcpStream stream;
uint8_t stream_same_linux[8] = {0x4c, 0x4c, 0x4c, 0x4c, 0x48, 0x48,
0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_linux, sizeof(stream_same_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and LINUX policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest11(void)
{
TcpStream stream;
uint8_t stream_after_linux[8] = {0x41, 0x41, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_linux, sizeof(stream_after_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and LINUX policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest12(void)
{
TcpStream stream;
uint8_t stream_linux[25] = {0x30, 0x41, 0x41, 0x41, 0x4a, 0x4a, 0x42, 0x43,
0x43, 0x43, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_linux, sizeof(stream_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and OLD_LINUX policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest13(void)
{
TcpStream stream;
uint8_t stream_before_old_linux[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_OLD_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_old_linux, sizeof(stream_before_old_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and OLD_LINUX policy is
* used to reassemble segments.
*/
static int StreamTcpReassembleTest14(void)
{
TcpStream stream;
uint8_t stream_same_old_linux[8] = {0x4c, 0x4c, 0x4c, 0x4c, 0x48, 0x48,
0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_OLD_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_old_linux, sizeof(stream_same_old_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and OLD_LINUX policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest15(void)
{
TcpStream stream;
uint8_t stream_after_old_linux[8] = {0x41, 0x41, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_OLD_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_old_linux, sizeof(stream_after_old_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and OLD_LINUX policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest16(void)
{
TcpStream stream;
uint8_t stream_old_linux[25] = {0x30, 0x41, 0x41, 0x41, 0x4a, 0x4a, 0x42, 0x4b,
0x4b, 0x4b, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_OLD_LINUX;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_old_linux, sizeof(stream_old_linux), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and SOLARIS policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest17(void)
{
TcpStream stream;
uint8_t stream_before_solaris[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_SOLARIS;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_solaris, sizeof(stream_before_solaris), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and SOLARIS policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest18(void)
{
TcpStream stream;
uint8_t stream_same_solaris[8] = {0x4c, 0x4c, 0x4c, 0x4c, 0x48, 0x48,
0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_SOLARIS;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_solaris, sizeof(stream_same_solaris), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and SOLARIS policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest19(void)
{
TcpStream stream;
uint8_t stream_after_solaris[8] = {0x41, 0x4a, 0x4a, 0x46, 0x46, 0x46,
0x47, 0x47};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_SOLARIS;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
StreamTcpFreeConfig(TRUE);
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_solaris, sizeof(stream_after_solaris), &stream) == 0) {
printf("failed in stream matching!!\n");
StreamTcpFreeConfig(TRUE);
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and SOLARIS policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest20(void)
{
TcpStream stream;
uint8_t stream_solaris[25] = {0x30, 0x41, 0x4a, 0x4a, 0x4a, 0x42, 0x42, 0x4b,
0x4b, 0x4b, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x46, 0x46, 0x47, 0x47, 0x48, 0x48, 0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_SOLARIS;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly!!\n");
StreamTcpFreeConfig(TRUE);
return 0;
}
if (StreamTcpCheckStreamContents(stream_solaris, sizeof(stream_solaris), &stream) == 0) {
printf("failed in stream matching!!\n");
StreamTcpFreeConfig(TRUE);
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* before the list segment and LAST policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest21(void)
{
TcpStream stream;
uint8_t stream_before_last[10] = {0x4a, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c,
0x4c, 0x4d, 0x4d, 0x4d};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LAST;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsBeforeListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_before_last, sizeof(stream_before_last), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* at the same seq no. as the list segment and LAST policy is used
* to reassemble segments.
*/
static int StreamTcpReassembleTest22(void)
{
TcpStream stream;
uint8_t stream_same_last[8] = {0x4c, 0x4c, 0x4c, 0x4c, 0x50, 0x48,
0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LAST;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAtSameListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_same_last, sizeof(stream_same_last), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly when new segment starts
* after the list segment and LAST policy is used to reassemble
* segments.
*/
static int StreamTcpReassembleTest23(void)
{
TcpStream stream;
uint8_t stream_after_last[8] = {0x41, 0x4a, 0x4a, 0x46, 0x4e, 0x46, 0x47, 0x4f};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LAST;
StreamTcpInitConfig(TRUE);
if (StreamTcpTestStartsAfterListSegment(&stream) == 0) {
printf("failed in segments reassembly!!\n");
return 0;
}
if (StreamTcpCheckStreamContents(stream_after_last, sizeof(stream_after_last), &stream) == 0) {
printf("failed in stream matching!!\n");
return 0;
}
StreamTcpFreeConfig(TRUE);
return 1;
}
/** \brief The Function to test the reassembly engine for all the case
* before, same and after overlapping and LAST policy is used to
* reassemble segments.
*/
static int StreamTcpReassembleTest24(void)
{
int ret = 0;
TcpStream stream;
uint8_t stream_last[25] = {0x30, 0x41, 0x4a, 0x4a, 0x4a, 0x4a, 0x42, 0x4b,
0x4b, 0x4b, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d,
0x46, 0x4e, 0x46, 0x47, 0x4f, 0x50, 0x48, 0x51, 0x51};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_LAST;
StreamTcpInitConfig(TRUE);
if (StreamTcpReassembleStreamTest(&stream) == 0) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(stream_last, sizeof(stream_last), &stream) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/** \brief The Function to test the missed packets handling with given payload,
* which is used to test the reassembly of the engine.
*
* \param stream Stream which contain the packets
* \param seq Sequence number of the packet
* \param ack Acknowledgment number of the packet
* \param payload The variable used to store the payload contents of the
* current packet.
* \param len The length of the payload for current packet.
* \param th_flag The TCP flags
* \param flowflags The packet flow direction
* \param state The TCP session state
*
* \retval On success it returns 0 and on failure it return -1.
*/
static int StreamTcpTestMissedPacket (TcpReassemblyThreadCtx *ra_ctx,
TcpSession *ssn, uint32_t seq, uint32_t ack, uint8_t *payload,
uint16_t len, uint8_t th_flags, uint8_t flowflags, uint8_t state)
{
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return -1;
Flow f;
TCPHdr tcph;
Port sp;
Port dp;
struct in_addr in;
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
sp = 200;
dp = 220;
FLOW_INITIALIZE(&f);
if (inet_pton(AF_INET, "1.2.3.4", &in) != 1) {
SCFree(p);
return -1;
}
f.src.addr_data32[0] = in.s_addr;
if (inet_pton(AF_INET, "1.2.3.5", &in) != 1) {
SCFree(p);
return -1;
}
f.dst.addr_data32[0] = in.s_addr;
f.flags |= FLOW_IPV4;
f.sp = sp;
f.dp = dp;
f.protoctx = ssn;
f.proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(seq);
tcph.th_ack = htonl(ack);
tcph.th_flags = th_flags;
p->tcph = &tcph;
p->flowflags = flowflags;
p->payload = payload;
p->payload_len = len;
ssn->state = state;
TcpStream *s = NULL;
if (flowflags & FLOW_PKT_TOSERVER) {
s = &ssn->server;
} else {
s = &ssn->client;
}
SCMutexLock(&f.m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, ssn, s, p, &pq) == -1) {
SCMutexUnlock(&f.m);
SCFree(p);
return -1;
}
SCMutexUnlock(&f.m);
SCFree(p);
return 0;
}
/**
* \test Test the handling of packets missed by both IDS and the end host.
* The packet is missed in the starting of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest25 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
TcpSession ssn;
uint8_t th_flag;
uint8_t flowflags;
uint8_t check_contents[7] = {0x41, 0x41, 0x41, 0x42, 0x42, 0x43, 0x43};
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
ack = 20;
StreamTcpInitConfig(TRUE);
StreamTcpCreateTestPacket(payload, 0x42, 2, 4); /*BB*/
seq = 10;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x43, 2, 4); /*CC*/
seq = 12;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
ssn.server.next_seq = 14;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
seq = 7;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(check_contents, sizeof(check_contents), &ssn.server) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by both IDS and the end host.
* The packet is missed in the middle of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest26 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
TcpSession ssn;
uint8_t th_flag;
uint8_t flowflags;
uint8_t check_contents[7] = {0x41, 0x41, 0x41, 0x42, 0x42, 0x43, 0x43};
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
ack = 20;
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
seq = 10;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x43, 2, 4); /*CC*/
seq = 15;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x42, 2, 4); /*BB*/
seq = 13;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(check_contents, sizeof(check_contents), &ssn.server) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by both IDS and the end host.
* The packet is missed in the end of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest27 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
TcpSession ssn;
uint8_t th_flag;
uint8_t flowflags;
uint8_t check_contents[7] = {0x41, 0x41, 0x41, 0x42, 0x42, 0x43, 0x43};
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
ack = 20;
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
seq = 10;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x42, 2, 4); /*BB*/
seq = 13;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
StreamTcpCreateTestPacket(payload, 0x43, 2, 4); /*CC*/
seq = 15;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(check_contents, sizeof(check_contents), &ssn.server) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by IDS, but the end host has
* received it and send the acknowledgment of it. The packet is missed
* in the starting of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest28 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
uint8_t th_flag;
uint8_t th_flags;
uint8_t flowflags;
uint8_t check_contents[5] = {0x41, 0x41, 0x42, 0x42, 0x42};
TcpSession ssn;
memset(&ssn, 0, sizeof (TcpSession));
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
StreamTcpInitConfig(TRUE);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
th_flags = TH_ACK;
ssn.server.last_ack = 22;
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 6;
ssn.server.isn = 6;
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
seq = 10;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly (1): ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 12;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly (2): ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
seq = 12;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly (4): ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 15;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_TIME_WAIT) == -1) {
printf("failed in segments reassembly (5): ");
goto end;
}
if (StreamTcpCheckChunks(&ssn, check_contents) == 0) {
printf("failed in stream matching (6): ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by IDS, but the end host has
* received it and send the acknowledgment of it. The packet is missed
* in the middle of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest29 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
uint8_t th_flag;
uint8_t th_flags;
uint8_t flowflags;
uint8_t check_contents[5] = {0x41, 0x41, 0x42, 0x42, 0x42};
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpSession ssn;
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
th_flags = TH_ACK;
ssn.server.last_ack = 22;
ssn.server.ra_raw_base_seq = 9;
ssn.server.isn = 9;
StreamTcpInitConfig(TRUE);
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
seq = 10;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 15;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
seq = 15;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 18;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_TIME_WAIT) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckChunks(&ssn, check_contents) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the handling of packets missed by IDS, but the end host has
* received it and send the acknowledgment of it. The packet is missed
* at the end of the stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest30 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
uint8_t th_flag;
uint8_t th_flags;
uint8_t flowflags;
uint8_t check_contents[6] = {0x41, 0x41, 0x42, 0x42, 0x42, 0x00};
TcpSession ssn;
memset(&ssn, 0, sizeof (TcpSession));
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
th_flags = TH_ACK;
ssn.server.last_ack = 22;
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 9;
ssn.server.isn = 9;
StreamTcpInitConfig(TRUE);
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
seq = 10;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 12;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
seq = 12;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 3, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 18;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flags, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
th_flag = TH_FIN|TH_ACK;
seq = 18;
ack = 20;
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x00, 1, 4);
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 1, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x00, 0, 4);
seq = 20;
ack = 18;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 0, th_flag, flowflags, TCP_TIME_WAIT) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckChunks(&ssn, check_contents) == 0) {
printf("failed in stream matching: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test to reassemble the packets using the fast track method, as most
* packets arrives in order.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest31 (void)
{
int ret = 0;
uint8_t payload[4];
uint32_t seq;
uint32_t ack;
uint8_t th_flag;
uint8_t flowflags;
uint8_t check_contents[5] = {0x41, 0x41, 0x42, 0x42, 0x42};
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpSession ssn;
memset(&ssn, 0, sizeof (TcpSession));
flowflags = FLOW_PKT_TOSERVER;
th_flag = TH_ACK|TH_PUSH;
ssn.server.ra_raw_base_seq = 9;
ssn.server.isn = 9;
StreamTcpInitConfig(TRUE);
StreamTcpCreateTestPacket(payload, 0x41, 2, 4); /*AA*/
seq = 10;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 2, th_flag, flowflags, TCP_ESTABLISHED) == -1){
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 1, 4); /*B*/
seq = 15;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 1, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 1, 4); /*B*/
seq = 12;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 1, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 1, 4); /*B*/
seq = 16;
ack = 20;
if (StreamTcpTestMissedPacket (ra_ctx, &ssn, seq, ack, payload, 1, th_flag, flowflags, TCP_ESTABLISHED) == -1) {
printf("failed in segments reassembly: ");
goto end;
}
if (StreamTcpCheckStreamContents(check_contents, 5, &ssn.server) == 0) {
printf("failed in stream matching: ");
goto end;
}
if (ssn.server.seg_list_tail->seq != 16) {
printf("failed in fast track handling: ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
static int StreamTcpReassembleTest32(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
uint8_t ret = 0;
uint8_t check_contents[35] = {0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x42, 0x42, 0x42, 0x42,
0x42, 0x43, 0x43, 0x43, 0x43, 0x43, 0x43, 0x43,
0x43, 0x43, 0x43};
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t payload[20] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
StreamTcpCreateTestPacket(payload, 0x41, 10, 20); /*AA*/
p->payload = payload;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
StreamTcpCreateTestPacket(payload, 0x42, 10, 20); /*BB*/
p->payload = payload;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(40);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
StreamTcpCreateTestPacket(payload, 0x43, 10, 20); /*CC*/
p->payload = payload;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(5);
p->tcph->th_ack = htonl(31);
p->payload_len = 20;
StreamTcpCreateTestPacket(payload, 0x41, 20, 20); /*AA*/
p->payload = payload;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1)
goto end;
if (StreamTcpCheckStreamContents(check_contents, 35, &stream) != 0) {
ret = 1;
} else {
printf("failed in stream matching: ");
}
end:
StreamTcpFreeConfig(TRUE);
SCFree(p);
return ret;
}
static int StreamTcpReassembleTest33(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t packet[1460] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(40);
p->tcph->th_ack = htonl(31);
p->payload_len = 10;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(5);
p->tcph->th_ack = htonl(31);
p->payload_len = 30;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
static int StreamTcpReassembleTest34(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t packet[1460] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 4096);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 4096);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
p->tcph->th_seq = htonl(857961230);
p->tcph->th_ack = htonl(31);
p->payload_len = 304;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(857961534);
p->tcph->th_ack = htonl(31);
p->payload_len = 1460;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(857963582);
p->tcph->th_ack = htonl(31);
p->payload_len = 1460;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(857960946);
p->tcph->th_ack = htonl(31);
p->payload_len = 1460;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
/** \test Test the bug 56 condition */
static int StreamTcpReassembleTest35(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t packet[1460] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 10);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 10);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
p->tcph->th_seq = htonl(2257022155UL);
p->tcph->th_ack = htonl(1374943142);
p->payload_len = 142;
stream.last_ack = 2257022285UL;
stream.ra_raw_base_seq = 2257022172UL;
stream.ra_app_base_seq = 2257022172UL;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(2257022285UL);
p->tcph->th_ack = htonl(1374943142);
p->payload_len = 34;
stream.last_ack = 2257022285UL;
stream.ra_raw_base_seq = 2257022172UL;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
/** \test Test the bug 57 condition */
static int StreamTcpReassembleTest36(void)
{
TcpSession ssn;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
memset(&stream, 0, sizeof (TcpStream));
stream.os_policy = OS_POLICY_BSD;
uint8_t packet[1460] = "";
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 10);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 10);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
p->tcph->th_seq = htonl(1549588966);
p->tcph->th_ack = htonl(4162241372UL);
p->payload_len = 204;
stream.last_ack = 1549589007;
stream.ra_raw_base_seq = 1549589101;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(1549589007);
p->tcph->th_ack = htonl(4162241372UL);
p->payload_len = 23;
stream.last_ack = 1549589007;
stream.ra_raw_base_seq = 1549589101;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
/** \test Test the bug 76 condition */
static int StreamTcpReassembleTest37(void)
{
TcpSession ssn;
Flow f;
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
TcpStream stream;
uint8_t packet[1460] = "";
PacketQueue pq;
ThreadVars tv;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 10);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 10);
memset(&stream, 0, sizeof (TcpStream));
memset(&pq,0,sizeof(PacketQueue));
memset(&ssn, 0, sizeof (TcpSession));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
FLOW_INITIALIZE(&f);
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
stream.os_policy = OS_POLICY_BSD;
p->tcph->th_seq = htonl(3061088537UL);
p->tcph->th_ack = htonl(1729548549UL);
p->payload_len = 1391;
stream.last_ack = 3061091137UL;
stream.ra_raw_base_seq = 3061091309UL;
stream.ra_app_base_seq = 3061091309UL;
/* pre base_seq, so should be rejected */
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) != -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(3061089928UL);
p->tcph->th_ack = htonl(1729548549UL);
p->payload_len = 1391;
stream.last_ack = 3061091137UL;
stream.ra_raw_base_seq = 3061091309UL;
stream.ra_app_base_seq = 3061091309UL;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
p->tcph->th_seq = htonl(3061091319UL);
p->tcph->th_ack = htonl(1729548549UL);
p->payload_len = 1391;
stream.last_ack = 3061091137UL;
stream.ra_raw_base_seq = 3061091309UL;
stream.ra_app_base_seq = 3061091309UL;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx,&ssn, &stream, p, &pq) == -1) {
SCFree(p);
return 0;
}
StreamTcpFreeConfig(TRUE);
SCFree(p);
return 1;
}
/**
* \test Test to make sure we don't send the smsg from toclient to app layer
* until the app layer protocol has been detected and one smsg from
* toserver side has been sent to app layer.
*
* Unittest modified by commit -
*
* commit bab1636377bb4f1b7b889f4e3fd594795085eaa4
* Author: Anoop Saldanha <anoopsaldanha@gmail.com>
* Date: Fri Feb 15 18:58:33 2013 +0530
*
* Improved app protocol detection.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest38 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
TCPHdr tcph;
Port sp;
Port dp;
struct in_addr in;
TcpSession ssn;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
uint8_t httpbuf2[] = "POST / HTTP/1.0\r\nUser-Agent: Victor/1.0\r\n\r\n";
uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */
uint8_t httpbuf1[] = "HTTP/1.0 200 OK\r\nServer: VictorServer/1.0\r\n\r\n";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
FLOW_INITIALIZE(&f);
if (inet_pton(AF_INET, "1.2.3.4", &in) != 1)
goto end;
f.src.addr_data32[0] = in.s_addr;
if (inet_pton(AF_INET, "1.2.3.5", &in) != 1)
goto end;
f.dst.addr_data32[0] = in.s_addr;
sp = 200;
dp = 220;
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 9;
ssn.server.isn = 9;
ssn.server.last_ack = 60;
ssn.client.ra_raw_base_seq = ssn.client.ra_app_base_seq = 9;
ssn.client.isn = 9;
ssn.client.last_ack = 60;
f.alproto = ALPROTO_UNKNOWN;
f.flags |= FLOW_IPV4;
f.sp = sp;
f.dp = dp;
f.protoctx = &ssn;
f.proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf2;
p->payload_len = httplen2;
ssn.state = TCP_ESTABLISHED;
TcpStream *s = NULL;
s = &ssn.server;
SCMutexLock(&f.m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (1): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) > 0) {
printf("there shouldn't be any stream smsgs in the queue (2): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf1;
p->payload_len = httplen1;
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(55);
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (3): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("there should one stream smsg in the queue (6): ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCMutexUnlock(&f.m);
SCFree(p);
return ret;
}
/**
* \test Test to make sure that we don't return the segments until the app
* layer proto has been detected and after that remove the processed
* segments.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest39 (void)
{
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread *stt = NULL;
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpThreadInit(&tv, NULL, (void **)&stt);
memset(&tcph, 0, sizeof (TCPHdr));
f.flags = FLOW_IPV4;
f.proto = IPPROTO_TCP;
p->flow = &f;
p->tcph = &tcph;
SCMutexLock(&f.m);
int ret = 0;
StreamTcpInitConfig(TRUE);
/* handshake */
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
TcpSession *ssn = (TcpSession *)f.protoctx;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != 0) {
printf("failure 1\n");
goto end;
}
/* handshake */
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != 0) {
printf("failure 2\n");
goto end;
}
/* handshake */
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != 0) {
printf("failure 3\n");
goto end;
}
/* partial request */
uint8_t request1[] = { 0x47, 0x45, };
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = sizeof(request1);
p->payload = request1;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != STREAM_TOSERVER) {
printf("failure 4\n");
goto end;
}
/* response ack against partial request */
p->tcph->th_ack = htonl(3);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != STREAM_TOSERVER) {
printf("failure 5\n");
goto end;
}
/* complete partial request */
uint8_t request2[] = {
0x54, 0x20, 0x2f, 0x69, 0x6e, 0x64,
0x65, 0x78, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x20,
0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x30,
0x0d, 0x0a, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x20,
0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73,
0x74, 0x0d, 0x0a, 0x55, 0x73, 0x65, 0x72, 0x2d,
0x41, 0x67, 0x65, 0x6e, 0x74, 0x3a, 0x20, 0x41,
0x70, 0x61, 0x63, 0x68, 0x65, 0x42, 0x65, 0x6e,
0x63, 0x68, 0x2f, 0x32, 0x2e, 0x33, 0x0d, 0x0a,
0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x3a, 0x20,
0x2a, 0x2f, 0x2a, 0x0d, 0x0a, 0x0d, 0x0a };
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(3);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = sizeof(request2);
p->payload = request2;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_UNKNOWN ||
f.alproto_ts != ALPROTO_UNKNOWN ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next != NULL ||
ssn->server.seg_list != NULL ||
ssn->toserver_smsg_head != NULL ||
ssn->toclient_smsg_head != NULL ||
ssn->data_first_seen_dir != STREAM_TOSERVER) {
printf("failure 6\n");
goto end;
}
/* response - request ack */
uint8_t response[] = {
0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31,
0x20, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x0d,
0x0a, 0x44, 0x61, 0x74, 0x65, 0x3a, 0x20, 0x46,
0x72, 0x69, 0x2c, 0x20, 0x32, 0x33, 0x20, 0x53,
0x65, 0x70, 0x20, 0x32, 0x30, 0x31, 0x31, 0x20,
0x30, 0x36, 0x3a, 0x32, 0x39, 0x3a, 0x33, 0x39,
0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x53, 0x65,
0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x41, 0x70,
0x61, 0x63, 0x68, 0x65, 0x2f, 0x32, 0x2e, 0x32,
0x2e, 0x31, 0x35, 0x20, 0x28, 0x55, 0x6e, 0x69,
0x78, 0x29, 0x20, 0x44, 0x41, 0x56, 0x2f, 0x32,
0x0d, 0x0a, 0x4c, 0x61, 0x73, 0x74, 0x2d, 0x4d,
0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, 0x3a,
0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x30, 0x34,
0x20, 0x4e, 0x6f, 0x76, 0x20, 0x32, 0x30, 0x31,
0x30, 0x20, 0x31, 0x35, 0x3a, 0x30, 0x34, 0x3a,
0x34, 0x36, 0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a,
0x45, 0x54, 0x61, 0x67, 0x3a, 0x20, 0x22, 0x61,
0x62, 0x38, 0x39, 0x36, 0x35, 0x2d, 0x32, 0x63,
0x2d, 0x34, 0x39, 0x34, 0x33, 0x62, 0x37, 0x61,
0x37, 0x66, 0x37, 0x66, 0x38, 0x30, 0x22, 0x0d,
0x0a, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x2d,
0x52, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x3a, 0x20,
0x62, 0x79, 0x74, 0x65, 0x73, 0x0d, 0x0a, 0x43,
0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x4c,
0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20, 0x34,
0x34, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x6e, 0x65,
0x63, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x63,
0x6c, 0x6f, 0x73, 0x65, 0x0d, 0x0a, 0x43, 0x6f,
0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79,
0x70, 0x65, 0x3a, 0x20, 0x74, 0x65, 0x78, 0x74,
0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x0d, 0x0a, 0x58,
0x2d, 0x50, 0x61, 0x64, 0x3a, 0x20, 0x61, 0x76,
0x6f, 0x69, 0x64, 0x20, 0x62, 0x72, 0x6f, 0x77,
0x73, 0x65, 0x72, 0x20, 0x62, 0x75, 0x67, 0x0d,
0x0a, 0x0d, 0x0a, 0x3c, 0x68, 0x74, 0x6d, 0x6c,
0x3e, 0x3c, 0x62, 0x6f, 0x64, 0x79, 0x3e, 0x3c,
0x68, 0x31, 0x3e, 0x49, 0x74, 0x20, 0x77, 0x6f,
0x72, 0x6b, 0x73, 0x21, 0x3c, 0x2f, 0x68, 0x31,
0x3e, 0x3c, 0x2f, 0x62, 0x6f, 0x64, 0x79, 0x3e,
0x3c, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3e };
p->tcph->th_ack = htonl(88);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = sizeof(response);
p->payload = response;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_UNKNOWN ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next != NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 7\n");
goto end;
}
/* response ack from request */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(88);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next != NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 8\n");
goto end;
}
/* response - acking */
p->tcph->th_ack = htonl(88);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 9\n");
goto end;
}
/* response ack from request */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(88);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 10\n");
goto end;
}
/* response - acking the request again*/
p->tcph->th_ack = htonl(88);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 11\n");
goto end;
}
/*** New Request ***/
/* partial request */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(88);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = sizeof(request1);
p->payload = request1;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 12\n");
goto end;
}
/* response ack against partial request */
p->tcph->th_ack = htonl(90);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 13\n");
goto end;
}
/* complete request */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(90);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = sizeof(request2);
p->payload = request2;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list == NULL ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next == NULL ||
ssn->client.seg_list->next->next->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 14\n");
goto end;
}
/* response ack against second partial request */
p->tcph->th_ack = htonl(175);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list->next == NULL ||
ssn->client.seg_list->next->next == NULL ||
ssn->client.seg_list->next->next->next == NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 15\n");
goto end;
}
if (ssn->toserver_smsg_head == NULL ||
ssn->toserver_smsg_head->next == NULL ||
ssn->toserver_smsg_head->next->next != NULL ||
ssn->toclient_smsg_head == NULL ||
ssn->toclient_smsg_head->next != NULL) {
printf("failure 16\n");
goto end;
}
StreamMsgReturnListToPool(ssn->toserver_smsg_head);
ssn->toserver_smsg_head = ssn->toserver_smsg_tail = NULL;
StreamMsgReturnListToPool(ssn->toclient_smsg_head);
ssn->toclient_smsg_head = ssn->toclient_smsg_tail = NULL;
/* response acking a request */
p->tcph->th_ack = htonl(175);
p->tcph->th_seq = htonl(328);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list == NULL ||
ssn->server.seg_list->next != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 15\n");
goto end;
}
/* request acking a response */
p->tcph->th_ack = htonl(328);
p->tcph->th_seq = htonl(175);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = 0;
p->payload = NULL;
if (StreamTcpPacket(&tv, p, stt, &pq) == -1)
goto end;
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server) ||
!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client) ||
f.alproto != ALPROTO_HTTP ||
f.alproto_ts != ALPROTO_HTTP ||
f.alproto_tc != ALPROTO_HTTP ||
f.data_al_so_far[0] != 0 ||
f.data_al_so_far[1] != 0 ||
f.flags & FLOW_NO_APPLAYER_INSPECTION ||
!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER) || !FLOW_IS_PP_DONE(&f, STREAM_TOSERVER) ||
!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT) || FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT) ||
ssn->client.seg_list != NULL ||
ssn->server.seg_list != NULL ||
ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) {
printf("failure 15\n");
goto end;
}
ret = 1;
end:
StreamTcpThreadDeinit(&tv, (void *)stt);
StreamTcpSessionClear(p->flow->protoctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f.m);
return ret;
}
/**
* \test Test to make sure that we sent all the segments from the initial
* segments to app layer until we have detected the app layer proto.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest40 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpInitConfig(TRUE);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 130);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
uint8_t httpbuf1[] = "P";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
uint8_t httpbuf3[] = "O";
uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */
uint8_t httpbuf4[] = "S";
uint32_t httplen4 = sizeof(httpbuf4) - 1; /* minus the \0 */
uint8_t httpbuf5[] = "T \r\n";
uint32_t httplen5 = sizeof(httpbuf5) - 1; /* minus the \0 */
uint8_t httpbuf2[] = "HTTP/1.0 200 OK\r\nServer: VictorServer/1.0\r\n\r\n";
uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 9;
ssn.server.isn = 9;
ssn.server.last_ack = 10;
ssn.client.ra_raw_base_seq = ssn.client.ra_app_base_seq = 9;
ssn.client.isn = 9;
ssn.client.last_ack = 10;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(10);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf1;
p->payload_len = httplen1;
ssn.state = TCP_ESTABLISHED;
TcpStream *s = NULL;
s = &ssn.client;
SCMutexLock(&f->m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (1): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOCLIENT) > 0) {
printf("there shouldn't be any stream smsgs in the queue, as we didn't"
" processed any smsg from toserver side till yet (2): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
s = &ssn.server;
ssn.server.last_ack = 11;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (3): ");
goto end;
}
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf3;
p->payload_len = httplen3;
tcph.th_seq = htonl(11);
tcph.th_ack = htonl(55);
s = &ssn.client;
ssn.client.last_ack = 55;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (5): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(55);
tcph.th_ack = htonl(12);
s = &ssn.server;
ssn.server.last_ack = 12;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (6): ");
goto end;
}
/* check is have the segment in the list and flagged or not */
if (ssn.client.seg_list == NULL ||
(ssn.client.seg_list->flags & SEGMENTTCP_FLAG_APPLAYER_PROCESSED))
{
printf("the list is NULL or the processed segment has not been flaged (7): ");
goto end;
}
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf4;
p->payload_len = httplen4;
tcph.th_seq = htonl(12);
tcph.th_ack = htonl(100);
s = &ssn.client;
ssn.client.last_ack = 100;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (10): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(100);
tcph.th_ack = htonl(13);
s = &ssn.server;
ssn.server.last_ack = 13;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (11): ");
goto end;
}
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf5;
p->payload_len = httplen5;
tcph.th_seq = htonl(13);
tcph.th_ack = htonl(145);
s = &ssn.client;
ssn.client.last_ack = 145;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (14): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(145);
tcph.th_ack = htonl(16);
s = &ssn.server;
ssn.server.last_ack = 16;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (15): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) == 0) {
printf("there should be a stream smsgs in the queue, as we have detected"
" the app layer protocol and one smsg from toserver side has "
"been sent (16): ");
goto end;
}
if (f->alproto != ALPROTO_HTTP) {
printf("app layer proto has not been detected (18): ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/**
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest43 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
uint8_t httpbuf1[] = "/ HTTP/1.0\r\nUser-Agent: Victor/1.0";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
uint8_t httpbuf2[] = "HTTP/1.0 200 OK\r\nServer: VictorServer/1.0\r\n\r\n";
uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */
uint8_t httpbuf3[] = "W2dyb3VwMV0NCnBob25lMT1wMDB3ODgyMTMxMzAyMTINCmxvZ2lu"
"MT0NCnBhc3N3b3JkMT0NCnBob25lMj1wMDB3ODgyMTMxMzAyMTIN"
"CmxvZ2luMj0NCnBhc3N3b3JkMj0NCnBob25lMz0NCmxvZ2luMz0N"
"CnBhc3N3b3JkMz0NCnBob25lND0NCmxvZ2luND0NCnBhc3N3b3Jk"
"ND0NCnBob25lNT0NCmxvZ2luNT0NCnBhc3N3b3JkNT0NCnBob25l"
"Nj0NCmxvZ2luNj0NCnBhc3N3b3JkNj0NCmNhbGxfdGltZTE9MzIN"
"CmNhbGxfdGltZTI9MjMyDQpkYXlfbGltaXQ9NQ0KbW9udGhfbGlt"
"aXQ9MTUNCltncm91cDJdDQpwaG9uZTE9DQpsb2dpbjE9DQpwYXNz"
"d29yZDE9DQpwaG9uZTI9DQpsb2dpbjI9DQpwYXNzd29yZDI9DQpw"
"aG9uZT\r\n\r\n";
uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 9;
ssn.server.isn = 9;
ssn.server.last_ack = 600;
ssn.client.ra_raw_base_seq = ssn.client.ra_app_base_seq = 9;
ssn.client.isn = 9;
ssn.client.last_ack = 600;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(10);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
ssn.state = TCP_ESTABLISHED;
TcpStream *s = NULL;
s = &ssn.server;
SCMutexLock(&f->m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (1): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) > 0) {
printf("there shouldn't be any stream smsgs in the queue (2): ");
goto end;
}
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf1;
p->payload_len = httplen1;
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(55);
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (3): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOCLIENT) > 0) {
printf("there shouldn't be any stream smsgs in the queue, as we didn't"
" processed any smsg from toserver side till yet (4): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(55);
tcph.th_ack = htonl(44);
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (5): ");
goto end;
}
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn.client)) {
printf("app layer detected flag isn't set, it should be (8): ");
goto end;
}
/* This packets induces a packet gap and also shows why we need to
process the current segment completely, even if it results in sending more
than one smsg to the app layer. If we don't send more than one smsg in
this case, then the first segment of lentgh 34 bytes will be sent to
app layer and protocol can not be detected in that message and moreover
the segment lentgh is less than the max. signature size for protocol
detection, so this will keep looping !! */
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = httpbuf3;
p->payload_len = httplen3;
tcph.th_seq = htonl(54);
tcph.th_ack = htonl(100);
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (9): ");
goto end;
}
/* Check if we have stream smsgs in queue */
if (UtSsnSmsgCnt(&ssn, STREAM_TOCLIENT) > 0) {
printf("there shouldn't be any stream smsgs in the queue, as we didn't"
" detected the app layer protocol till yet (10): ");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf2;
p->payload_len = httplen2;
tcph.th_seq = htonl(100);
tcph.th_ack = htonl(53);
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet (11): ");
goto end;
}
/* the flag should be set, as the smsg scanned size has crossed the max.
signature size for app proto detection */
if (!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn.client)) {
printf("app layer detected flag is not set, it should be (14): ");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpReassembleTest44(void)
{
uint8_t ret = 0;
StreamTcpInitConfig(TRUE);
uint32_t memuse = SC_ATOMIC_GET(ra_memuse);
StreamTcpReassembleIncrMemuse(500);
if (SC_ATOMIC_GET(ra_memuse) != (memuse+500)) {
printf("failed in incrementing the memory");
goto end;
}
StreamTcpReassembleDecrMemuse(500);
if (SC_ATOMIC_GET(ra_memuse) != memuse) {
printf("failed in decrementing the memory");
goto end;
}
if (StreamTcpReassembleCheckMemcap(500) != 1) {
printf("failed in validating the memcap");
goto end;
}
if (StreamTcpReassembleCheckMemcap((memuse + stream_config.reassembly_memcap)) != 0) {
printf("failed in validating the memcap");
goto end;
}
StreamTcpFreeConfig(TRUE);
if (SC_ATOMIC_GET(ra_memuse) != 0) {
printf("failed in clearing the memory");
goto end;
}
ret = 1;
return ret;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test to make sure that reassembly_depth is enforced.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest45 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
uint8_t httpbuf1[] = "/ HTTP/1.0\r\nUser-Agent: Victor/1.0";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
STREAMTCP_SET_RA_BASE_SEQ(&ssn.server, 9);
ssn.server.isn = 9;
ssn.server.last_ack = 60;
STREAMTCP_SET_RA_BASE_SEQ(&ssn.client, 9);
ssn.client.isn = 9;
ssn.client.last_ack = 60;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf1;
p->payload_len = httplen1;
ssn.state = TCP_ESTABLISHED;
/* set the default value of reassembly depth, as there is no config file */
stream_config.reassembly_depth = httplen1 + 1;
TcpStream *s = NULL;
s = &ssn.server;
SCMutexLock(&f->m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toclient packet: ");
goto end;
}
/* Check if we have flags set or not */
if (s->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) {
printf("there shouldn't be a noreassembly flag be set: ");
goto end;
}
STREAMTCP_SET_RA_BASE_SEQ(&ssn.server, ssn.server.isn + httplen1);
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = httplen1;
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet: ");
goto end;
}
/* Check if we have flags set or not */
if (s->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) {
printf("there shouldn't be a noreassembly flag be set: ");
goto end;
}
STREAMTCP_SET_RA_BASE_SEQ(&ssn.client, ssn.client.isn + httplen1);
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = httplen1;
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet: ");
goto end;
}
/* Check if we have flags set or not */
if (!(s->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
printf("the noreassembly flags should be set, "
"p.payload_len %"PRIu16" stream_config.reassembly_"
"depth %"PRIu32": ", p->payload_len,
stream_config.reassembly_depth);
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/**
* \test Test the undefined config value of reassembly depth.
* the default value of 0 will be loaded and stream will be reassembled
* until the session ended
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest46 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
uint8_t httpbuf1[] = "/ HTTP/1.0\r\nUser-Agent: Victor/1.0";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
STREAMTCP_SET_RA_BASE_SEQ(&ssn.server, 9);
ssn.server.isn = 9;
ssn.server.last_ack = 60;
ssn.server.next_seq = ssn.server.isn;
STREAMTCP_SET_RA_BASE_SEQ(&ssn.client, 9);
ssn.client.isn = 9;
ssn.client.last_ack = 60;
ssn.client.next_seq = ssn.client.isn;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = httpbuf1;
p->payload_len = httplen1;
ssn.state = TCP_ESTABLISHED;
stream_config.reassembly_depth = 0;
TcpStream *s = NULL;
s = &ssn.server;
SCMutexLock(&f->m);
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toclient packet\n");
goto end;
}
/* Check if we have flags set or not */
if ((ssn.client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) ||
(ssn.server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
printf("there shouldn't be any no reassembly flag be set \n");
goto end;
}
STREAMTCP_SET_RA_BASE_SEQ(&ssn.server, ssn.server.isn + httplen1);
p->flowflags = FLOW_PKT_TOSERVER;
p->payload_len = httplen1;
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet\n");
goto end;
}
/* Check if we have flags set or not */
if ((ssn.client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) ||
(ssn.server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
printf("there shouldn't be any no reassembly flag be set \n");
goto end;
}
STREAMTCP_SET_RA_BASE_SEQ(&ssn.client, ssn.client.isn + httplen1);
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload_len = httplen1;
tcph.th_seq = htonl(10 + httplen1);
tcph.th_ack = htonl(20 + httplen1);
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver packet\n");
goto end;
}
/* Check if we have flags set or not */
if ((ssn.client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) ||
(ssn.server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) {
printf("the no_reassembly flags should not be set, "
"p->payload_len %"PRIu16" stream_config.reassembly_"
"depth %"PRIu32": ", p->payload_len,
stream_config.reassembly_depth);
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/**
* \test Test to make sure we detect the sequence wrap around and continue
* stream reassembly properly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpReassembleTest47 (void)
{
int ret = 0;
Packet *p = PacketGetFromAlloc();
if (unlikely(p == NULL))
return 0;
Flow *f = NULL;
TCPHdr tcph;
TcpSession ssn;
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&ssn, 0, sizeof(TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
/* prevent L7 from kicking in */
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOSERVER, 0);
StreamMsgQueueSetMinChunkLen(FLOW_PKT_TOCLIENT, 0);
StreamTcpInitConfig(TRUE);
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
uint8_t httpbuf1[] = "GET /EVILSUFF HTTP/1.1\r\n\r\n";
uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */
ssn.server.ra_raw_base_seq = ssn.server.ra_app_base_seq = 572799781UL;
ssn.server.isn = 572799781UL;
ssn.server.last_ack = 572799782UL;
ssn.client.ra_raw_base_seq = ssn.client.ra_app_base_seq = 4294967289UL;
ssn.client.isn = 4294967289UL;
ssn.client.last_ack = 21;
f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 200, 220);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
p->flow = f;
tcph.th_win = htons(5480);
ssn.state = TCP_ESTABLISHED;
TcpStream *s = NULL;
uint8_t cnt = 0;
SCMutexLock(&f->m);
for (cnt=0; cnt < httplen1; cnt++) {
tcph.th_seq = htonl(ssn.client.isn + 1 + cnt);
tcph.th_ack = htonl(572799782UL);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = &httpbuf1[cnt];
p->payload_len = 1;
s = &ssn.client;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver "
"packet\n");
goto end;
}
p->flowflags = FLOW_PKT_TOCLIENT;
p->payload = NULL;
p->payload_len = 0;
tcph.th_seq = htonl(572799782UL);
tcph.th_ack = htonl(ssn.client.isn + 1 + cnt);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
s = &ssn.server;
if (StreamTcpReassembleHandleSegment(&tv, ra_ctx, &ssn, s, p, &pq) == -1) {
printf("failed in segments reassembly, while processing toserver "
"packet\n");
goto end;
}
}
if (f->alproto != ALPROTO_HTTP) {
printf("App layer protocol (HTTP) should have been detected\n");
goto end;
}
ret = 1;
end:
StreamTcpReassembleFreeThreadCtx(ra_ctx);
StreamTcpFreeConfig(TRUE);
SCFree(p);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/** \test 3 in order segments in inline reassembly */
static int StreamTcpReassembleInlineTest01(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload[] = "AAAAABBBBBCCCCC";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly.
*/
static int StreamTcpReassembleInlineTest02(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "AAAAABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message: ");
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 20) {
printf("expected data length to be 20, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 20) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 20);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly with a small window size so that we
* cutting off at the start (left edge)
*/
static int StreamTcpReassembleInlineTest03(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 15;
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "BBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message 1: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(17);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected two stream messages: ");
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly with a small window size so that we
* cutting off at the start (left edge) with small packet overlap.
*/
static int StreamTcpReassembleInlineTest04(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 16;
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "ABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(17);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message: ");
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 16) {
printf("expected data length to be 16, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 16) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 16);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test with a GAP we should have 2 smsgs */
static int StreamTcpReassembleInlineTest05(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload1[] = "AAAAABBBBB";
uint8_t stream_payload2[] = "DDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
ssn.client.next_seq = 12;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
p->tcph->th_seq = htonl(17);
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 10) {
printf("expected data length to be 10, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 10) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 10);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 5) {
printf("expected data length to be 5, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 5) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 5);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test with a GAP we should have 2 smsgs, with filling the GAP later */
static int StreamTcpReassembleInlineTest06(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload1[] = "AAAAABBBBB";
uint8_t stream_payload2[] = "DDDDD";
uint8_t stream_payload3[] = "AAAAABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
ssn.client.next_seq = 12;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
p->tcph->th_seq = htonl(17);
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected two stream messages: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 10) {
printf("expected data length to be 10, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 10) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 10);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 5) {
printf("expected data length to be 5, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 5) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 5);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(12);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 3) {
printf("expected a single stream message, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
smsg = ssn.toserver_smsg_head->next->next;
if (smsg->data_len != 20) {
printf("expected data length to be 20, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload3, smsg->data, 20) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload3, 20);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test with a GAP we should have 2 smsgs, with filling the GAP later, small
* window */
static int StreamTcpReassembleInlineTest07(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 16;
uint8_t stream_payload1[] = "ABBBBB";
uint8_t stream_payload2[] = "DDDDD";
uint8_t stream_payload3[] = "AAAAABBBBBCCCCCD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
ssn.client.next_seq = 12;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
p->tcph->th_seq = htonl(17);
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 6) {
printf("expected data length to be 6, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 6) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 6);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 5) {
printf("expected data length to be 5, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 5) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 5);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(12);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 3) {
printf("expected a single stream message, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
smsg = ssn.toserver_smsg_head->next->next;
if (smsg->data_len != 16) {
printf("expected data length to be 16, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload3, smsg->data, 16) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload3, 16);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly with a small window size so that we
* cutting off at the start (left edge). Test if the first segment is
* removed from the list.
*/
static int StreamTcpReassembleInlineTest08(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 15;
ssn.client.flags |= STREAMTCP_STREAM_FLAG_GAP;
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "BBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 17;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 16) {
printf("ra_raw_base_seq %"PRIu32", expected 16: ", ssn.client.ra_raw_base_seq);
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(17);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected a single stream message, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 15) {
printf("expected data length to be 15, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 15) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 15);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 21) {
printf("ra_raw_base_seq %"PRIu32", expected 21: ", ssn.client.ra_raw_base_seq);
goto end;
}
if (ssn.client.seg_list->seq != 7) {
printf("expected segment 2 (seq 7) to be first in the list, got seq %"PRIu32": ", ssn.client.seg_list->seq);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test 3 in order segments, then reassemble, add one more and reassemble again.
* test the sliding window reassembly with a small window size so that we
* cutting off at the start (left edge). Test if the first segment is
* removed from the list.
*/
static int StreamTcpReassembleInlineTest09(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
stream_config.reassembly_toserver_chunk_size = 20;
ssn.client.flags |= STREAMTCP_STREAM_FLAG_GAP;
uint8_t stream_payload1[] = "AAAAABBBBBCCCCC";
uint8_t stream_payload2[] = "DDDDD";
uint8_t stream_payload3[] = "AAAAABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(17);
p->flow = &f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.client.next_seq = 12;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 2) {
printf("expected 2 stream message2, got %u: ", UtSsnSmsgCnt(&ssn, STREAM_TOSERVER));
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 10) {
printf("expected data length to be 10, got %u (bot): ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 10) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 10);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
smsg = ssn.toserver_smsg_head->next;
if (smsg->data_len != 5) {
printf("expected data length to be 5, got %u (top): ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload2, smsg->data, 5) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload2, 5);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 11) {
printf("ra_raw_base_seq %"PRIu32", expected 11: ", ssn.client.ra_raw_base_seq);
goto end;
}
/* close the GAP and see if we properly reassemble and update ra_base_seq */
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 4: ");
goto end;
}
ssn.client.next_seq = 22;
p->tcph->th_seq = htonl(12);
r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed 2: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 3) {
printf("expected 3 stream messages: ");
goto end;
}
smsg = ssn.toserver_smsg_head->next->next;
if (smsg->data_len != 20) {
printf("expected data length to be 20, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload3, smsg->data, 20) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload3, 20);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 21) {
printf("ra_raw_base_seq %"PRIu32", expected 21: ", ssn.client.ra_raw_base_seq);
goto end;
}
if (ssn.client.seg_list->seq != 2) {
printf("expected segment 1 (seq 2) to be first in the list, got seq %"PRIu32": ", ssn.client.seg_list->seq);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test App Layer reassembly.
*/
static int StreamTcpReassembleInlineTest10(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow *f = NULL;
Packet *p = NULL;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTInitInline();
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.server, 1);
f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1024, 80);
if (f == NULL)
goto end;
f->protoctx = &ssn;
f->proto = IPPROTO_TCP;
uint8_t stream_payload1[] = "GE";
uint8_t stream_payload2[] = "T /";
uint8_t stream_payload3[] = "HTTP/1.0\r\n\r\n";
p = UTHBuildPacketReal(stream_payload3, 12, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(7);
p->flow = f;
p->flowflags |= FLOW_PKT_TOSERVER;
SCMutexLock(&f->m);
if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, 2, stream_payload1, 2) == -1) {
printf("failed to add segment 1: ");
goto end;
}
ssn.server.next_seq = 4;
int r = StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p);
if (r < 0) {
printf("StreamTcpReassembleAppLayer failed: ");
goto end;
}
/* ssn.server.ra_app_base_seq should be isn here. */
if (ssn.server.ra_app_base_seq != 1 || ssn.server.ra_app_base_seq != ssn.server.isn) {
printf("expected ra_app_base_seq 1, got %u: ", ssn.server.ra_app_base_seq);
goto end;
}
if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, 4, stream_payload2, 3) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, 7, stream_payload3, 12) == -1) {
printf("failed to add segment 3: ");
goto end;
}
ssn.server.next_seq = 19;
r = StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p);
if (r < 0) {
printf("StreamTcpReassembleAppLayer failed: ");
goto end;
}
if (ssn.server.ra_app_base_seq != 18) {
printf("expected ra_app_base_seq 18, got %u: ", ssn.server.ra_app_base_seq);
goto end;
}
ret = 1;
end:
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
SCMutexUnlock(&f->m);
UTHFreeFlow(f);
return ret;
}
/** \test test insert with overlap
*/
static int StreamTcpReassembleInsertTest01(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
Flow f;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
FLOW_INITIALIZE(&f);
uint8_t stream_payload1[] = "AAAAABBBBBCCCCCDDDDD";
uint8_t payload[] = { 'C', 'C', 'C', 'C', 'C' };
Packet *p = UTHBuildPacketReal(payload, 5, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80);
if (p == NULL) {
printf("couldn't get a packet: ");
goto end;
}
p->tcph->th_seq = htonl(12);
p->flow = &f;
SCMutexLock(&f.m);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) {
printf("failed to add segment 1: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) {
printf("failed to add segment 2: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 14, 'D', 2) == -1) {
printf("failed to add segment 3: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 16, 'D', 6) == -1) {
printf("failed to add segment 4: ");
goto end;
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1) {
printf("failed to add segment 5: ");
goto end;
}
ssn.client.next_seq = 21;
int r = StreamTcpReassembleInlineRaw(ra_ctx, &ssn, &ssn.client, p);
if (r < 0) {
printf("StreamTcpReassembleInlineRaw failed: ");
goto end;
}
if (UtSsnSmsgCnt(&ssn, STREAM_TOSERVER) != 1) {
printf("expected a single stream message: ");
goto end;
}
StreamMsg *smsg = ssn.toserver_smsg_head;
if (smsg->data_len != 20) {
printf("expected data length to be 20, got %u: ", smsg->data_len);
goto end;
}
if (!(memcmp(stream_payload1, smsg->data, 20) == 0)) {
printf("data is not what we expected:\nExpected:\n");
PrintRawDataFp(stdout, stream_payload1, 20);
printf("Got:\n");
PrintRawDataFp(stdout, smsg->data, smsg->data_len);
goto end;
}
if (ssn.client.ra_raw_base_seq != 21) {
printf("ra_raw_base_seq %"PRIu32", expected 21: ", ssn.client.ra_raw_base_seq);
goto end;
}
ret = 1;
end:
SCMutexUnlock(&f.m);
FLOW_DESTROY(&f);
UTHFreePacket(p);
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test test insert with overlaps
*/
static int StreamTcpReassembleInsertTest02(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
int i;
for (i = 2; i < 10; i++) {
int len;
len = i % 2;
if (len == 0)
len = 1;
int seq;
seq = i * 10;
if (seq < 2)
seq = 2;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, seq, 'A', len) == -1) {
printf("failed to add segment 1: ");
goto end;
}
}
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'B', 1024) == -1) {
printf("failed to add segment 2: ");
goto end;
}
ret = 1;
end:
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
/** \test test insert with overlaps
*/
static int StreamTcpReassembleInsertTest03(void)
{
int ret = 0;
TcpReassemblyThreadCtx *ra_ctx = NULL;
ThreadVars tv;
TcpSession ssn;
memset(&tv, 0x00, sizeof(tv));
StreamTcpUTInit(&ra_ctx);
StreamTcpUTSetupSession(&ssn);
StreamTcpUTSetupStream(&ssn.client, 1);
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 1024) == -1) {
printf("failed to add segment 2: ");
goto end;
}
int i;
for (i = 2; i < 10; i++) {
int len;
len = i % 2;
if (len == 0)
len = 1;
int seq;
seq = i * 10;
if (seq < 2)
seq = 2;
if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, seq, 'B', len) == -1) {
printf("failed to add segment 2: ");
goto end;
}
}
ret = 1;
end:
StreamTcpUTClearSession(&ssn);
StreamTcpUTDeinit(ra_ctx);
return ret;
}
#endif /* UNITTESTS */
/** \brief The Function Register the Unit tests to test the reassembly engine
* for various OS policies.
*/
void StreamTcpReassembleRegisterTests(void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpReassembleTest01 -- BSD OS Before Reassembly Test", StreamTcpReassembleTest01, 1);
UtRegisterTest("StreamTcpReassembleTest02 -- BSD OS At Same Reassembly Test", StreamTcpReassembleTest02, 1);
UtRegisterTest("StreamTcpReassembleTest03 -- BSD OS After Reassembly Test", StreamTcpReassembleTest03, 1);
UtRegisterTest("StreamTcpReassembleTest04 -- BSD OS Complete Reassembly Test", StreamTcpReassembleTest04, 1);
UtRegisterTest("StreamTcpReassembleTest05 -- VISTA OS Before Reassembly Test", StreamTcpReassembleTest05, 1);
UtRegisterTest("StreamTcpReassembleTest06 -- VISTA OS At Same Reassembly Test", StreamTcpReassembleTest06, 1);
UtRegisterTest("StreamTcpReassembleTest07 -- VISTA OS After Reassembly Test", StreamTcpReassembleTest07, 1);
UtRegisterTest("StreamTcpReassembleTest08 -- VISTA OS Complete Reassembly Test", StreamTcpReassembleTest08, 1);
UtRegisterTest("StreamTcpReassembleTest09 -- LINUX OS Before Reassembly Test", StreamTcpReassembleTest09, 1);
UtRegisterTest("StreamTcpReassembleTest10 -- LINUX OS At Same Reassembly Test", StreamTcpReassembleTest10, 1);
UtRegisterTest("StreamTcpReassembleTest11 -- LINUX OS After Reassembly Test", StreamTcpReassembleTest11, 1);
UtRegisterTest("StreamTcpReassembleTest12 -- LINUX OS Complete Reassembly Test", StreamTcpReassembleTest12, 1);
UtRegisterTest("StreamTcpReassembleTest13 -- LINUX_OLD OS Before Reassembly Test", StreamTcpReassembleTest13, 1);
UtRegisterTest("StreamTcpReassembleTest14 -- LINUX_OLD At Same Reassembly Test", StreamTcpReassembleTest14, 1);
UtRegisterTest("StreamTcpReassembleTest15 -- LINUX_OLD OS After Reassembly Test", StreamTcpReassembleTest15, 1);
UtRegisterTest("StreamTcpReassembleTest16 -- LINUX_OLD OS Complete Reassembly Test", StreamTcpReassembleTest16, 1);
UtRegisterTest("StreamTcpReassembleTest17 -- SOLARIS OS Before Reassembly Test", StreamTcpReassembleTest17, 1);
UtRegisterTest("StreamTcpReassembleTest18 -- SOLARIS At Same Reassembly Test", StreamTcpReassembleTest18, 1);
UtRegisterTest("StreamTcpReassembleTest19 -- SOLARIS OS After Reassembly Test", StreamTcpReassembleTest19, 1);
UtRegisterTest("StreamTcpReassembleTest20 -- SOLARIS OS Complete Reassembly Test", StreamTcpReassembleTest20, 1);
UtRegisterTest("StreamTcpReassembleTest21 -- LAST OS Before Reassembly Test", StreamTcpReassembleTest21, 1);
UtRegisterTest("StreamTcpReassembleTest22 -- LAST OS At Same Reassembly Test", StreamTcpReassembleTest22, 1);
UtRegisterTest("StreamTcpReassembleTest23 -- LAST OS After Reassembly Test", StreamTcpReassembleTest23, 1);
UtRegisterTest("StreamTcpReassembleTest24 -- LAST OS Complete Reassembly Test", StreamTcpReassembleTest24, 1);
UtRegisterTest("StreamTcpReassembleTest25 -- Gap at Start Reassembly Test", StreamTcpReassembleTest25, 1);
UtRegisterTest("StreamTcpReassembleTest26 -- Gap at middle Reassembly Test", StreamTcpReassembleTest26, 1);
UtRegisterTest("StreamTcpReassembleTest27 -- Gap at after Reassembly Test", StreamTcpReassembleTest27, 1);
UtRegisterTest("StreamTcpReassembleTest28 -- Gap at Start IDS missed packet Reassembly Test", StreamTcpReassembleTest28, 1);
UtRegisterTest("StreamTcpReassembleTest29 -- Gap at Middle IDS missed packet Reassembly Test", StreamTcpReassembleTest29, 1);
UtRegisterTest("StreamTcpReassembleTest30 -- Gap at End IDS missed packet Reassembly Test", StreamTcpReassembleTest30, 1);
UtRegisterTest("StreamTcpReassembleTest31 -- Fast Track Reassembly Test", StreamTcpReassembleTest31, 1);
UtRegisterTest("StreamTcpReassembleTest32 -- Bug test", StreamTcpReassembleTest32, 1);
UtRegisterTest("StreamTcpReassembleTest33 -- Bug test", StreamTcpReassembleTest33, 1);
UtRegisterTest("StreamTcpReassembleTest34 -- Bug test", StreamTcpReassembleTest34, 1);
UtRegisterTest("StreamTcpReassembleTest35 -- Bug56 test", StreamTcpReassembleTest35, 1);
UtRegisterTest("StreamTcpReassembleTest36 -- Bug57 test", StreamTcpReassembleTest36, 1);
UtRegisterTest("StreamTcpReassembleTest37 -- Bug76 test", StreamTcpReassembleTest37, 1);
UtRegisterTest("StreamTcpReassembleTest38 -- app proto test", StreamTcpReassembleTest38, 1);
UtRegisterTest("StreamTcpReassembleTest39 -- app proto test", StreamTcpReassembleTest39, 1);
UtRegisterTest("StreamTcpReassembleTest40 -- app proto test", StreamTcpReassembleTest40, 1);
UtRegisterTest("StreamTcpReassembleTest43 -- min smsg size test", StreamTcpReassembleTest43, 1);
UtRegisterTest("StreamTcpReassembleTest44 -- Memcap Test", StreamTcpReassembleTest44, 1);
UtRegisterTest("StreamTcpReassembleTest45 -- Depth Test", StreamTcpReassembleTest45, 1);
UtRegisterTest("StreamTcpReassembleTest46 -- Depth Test", StreamTcpReassembleTest46, 1);
UtRegisterTest("StreamTcpReassembleTest47 -- TCP Sequence Wraparound Test", StreamTcpReassembleTest47, 1);
UtRegisterTest("StreamTcpReassembleInlineTest01 -- inline RAW ra", StreamTcpReassembleInlineTest01, 1);
UtRegisterTest("StreamTcpReassembleInlineTest02 -- inline RAW ra 2", StreamTcpReassembleInlineTest02, 1);
UtRegisterTest("StreamTcpReassembleInlineTest03 -- inline RAW ra 3", StreamTcpReassembleInlineTest03, 1);
UtRegisterTest("StreamTcpReassembleInlineTest04 -- inline RAW ra 4", StreamTcpReassembleInlineTest04, 1);
UtRegisterTest("StreamTcpReassembleInlineTest05 -- inline RAW ra 5 GAP", StreamTcpReassembleInlineTest05, 1);
UtRegisterTest("StreamTcpReassembleInlineTest06 -- inline RAW ra 6 GAP", StreamTcpReassembleInlineTest06, 1);
UtRegisterTest("StreamTcpReassembleInlineTest07 -- inline RAW ra 7 GAP", StreamTcpReassembleInlineTest07, 1);
UtRegisterTest("StreamTcpReassembleInlineTest08 -- inline RAW ra 8 cleanup", StreamTcpReassembleInlineTest08, 1);
UtRegisterTest("StreamTcpReassembleInlineTest09 -- inline RAW ra 9 GAP cleanup", StreamTcpReassembleInlineTest09, 1);
UtRegisterTest("StreamTcpReassembleInlineTest10 -- inline APP ra 10", StreamTcpReassembleInlineTest10, 1);
UtRegisterTest("StreamTcpReassembleInsertTest01 -- insert with overlap", StreamTcpReassembleInsertTest01, 1);
UtRegisterTest("StreamTcpReassembleInsertTest02 -- insert with overlap", StreamTcpReassembleInsertTest02, 1);
UtRegisterTest("StreamTcpReassembleInsertTest03 -- insert with overlap", StreamTcpReassembleInsertTest03, 1);
StreamTcpInlineRegisterTests();
StreamTcpUtilRegisterTests();
#endif /* UNITTESTS */
}
| Java |
<?php
/**
* Plugin Name: Category Image Video
* Plugin URI: https://github.com/cheh/
* Description: This is a WordPress plugin that adds two additional fields to the taxonomy "Category".
* Version: 1.0.0
* Author: Dmitriy Chekhovkiy <chehovskiy.dima@gmail.com>
* Author URI: https://github.com/cheh/
* Text Domain: category-image-video
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Domain Path: /languages
*
* @package Category_Image_Video
* @author Dmitriy Chekhovkiy <chehovskiy.dima@gmail.com>
* @license GPL-2.0+
* @link https://github.com/cheh/
* @copyright 2017 Dmitriy Chekhovkiy
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
if ( ! version_compare( PHP_VERSION, '5.4', '>=' ) ) {
add_action( 'admin_notices', 'civ_fail_wp_version' );
} else {
// Public-Facing Functionality.
require_once( plugin_dir_path( __FILE__ ) . 'includes/class-category-image-video-tools.php' );
require_once( plugin_dir_path( __FILE__ ) . 'public/class-category-image-video.php' );
add_action( 'plugins_loaded', array( 'CIV_Plugin', 'get_instance' ) );
// Dashboard and Administrative Functionality.
if ( is_admin() ) {
require_once( plugin_dir_path( __FILE__ ) . 'admin/class-category-image-video-admin.php' );
add_action( 'plugins_loaded', array( 'CIV_Plugin_Admin', 'get_instance' ) );
}
}
add_action( 'plugins_loaded', 'civ_load_plugin_textdomain' );
/**
* Load the plugin text domain for translation.
*
* @since 1.0.0
*/
function civ_load_plugin_textdomain() {
load_plugin_textdomain( 'category-image-video', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
/**
* Show in WP Dashboard notice about the plugin is not activated.
*
* @since 1.0.0
*/
function civ_fail_wp_version() {
$message = esc_html__( 'This plugin requires WordPress version 4.4, plugin is currently NOT ACTIVE.', 'category-image-video' );
$html_message = sprintf( '<div class="error">%s</div>', wpautop( $message ) );
echo wp_kses_post( $html_message );
}
| Java |
<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/php_header.php';
$problem = $u->getProblemById($_GET['p']);
if($_POST){
$data = $_POST;
$data['figure'] = file_get_contents($_FILES['figure']['tmp_name']);
$data['figure_file'] = $_FILES['figure']['tmp_name'];
$data['mml'] = file_get_contents($_FILES['mml']['tmp_name']);
if(!$u->submitSolution($data)){
$error = $u->error;
}
else{
$msg = 'Solution submitted successfully. It will appear on the website after approval of an editor. Thank you for contributing to this growing collection of science-problems!';
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>New problem</title>
<?php include 'includes/html_head_include.php'; ?>
</head>
<body class="no-sidebar">
<?php include $_SERVER['DOCUMENT_ROOT'].'/includes/header.php'; ?>
<!-- Main Wrapper -->
<div id="main-wrapper">
<div class="container">
<div class="row">
<div class="12u">
<!-- Portfolio -->
<section>
<div>
<div class="row">
<div class="12u skel-cell-mainContent">
<!-- Content -->
<article class="box is-post">
<header>
<h2>New Solution</h2>
</header>
<p>
<h3>Problem</h3>
<?php
echo $problem['mml'];
?>
<h3>Upload solution file</h3>
<span class="error"><?php echo $error; ?></span>
<span class="message"><?php echo $msg; ?></span>
<form class="fullwidth" enctype="multipart/form-data" method="post" action="">
<input type="hidden" name="problem_id" value="<?php echo $_GET['p']; ?>"/>
<label>Figure (optional)</label>
<input type="file" class="file" name="figure" />
<label>MathML file</label>
<input type="file" class="file" name="mml" required/>
<br/>
<input type="submit"/>
</form>
</p>
</article>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
<?php include $_SERVER['DOCUMENT_ROOT'].'/includes/footer.php'; ?>
</body>
</html>
| Java |
/*global chrome */
// Check if the feature is enable
let promise = new Promise(function (resolve) {
chrome.storage.sync.get({
isEdEnable: true
}, function (items) {
if (items.isEdEnable === true) {
resolve();
}
});
});
promise.then(function () {
/*global removeIfExist */
/*eslint no-undef: "error"*/
removeIfExist(".blockheader");
removeIfExist(".blockcontent .upload-infos");
removeIfExist(".blockfooter");
}); | Java |
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 2005-2006, Kevin P. Fleming
*
* Kevin P. Fleming <kpfleming@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*! \file
*
* \brief Background DNS update manager
*
* \author Kevin P. Fleming <kpfleming@digium.com>
*
* \bug There is a minor race condition. In the event that an IP address
* of a dnsmgr managed host changes, there is the potential for the consumer
* of that address to access the in_addr data at the same time that the dnsmgr
* thread is in the middle of updating it to the new address.
*/
#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision: 130752 $")
#include "asterisk/_private.h"
#include <regex.h>
#include <signal.h>
#include "asterisk/dnsmgr.h"
#include "asterisk/linkedlists.h"
#include "asterisk/utils.h"
#include "asterisk/config.h"
#include "asterisk/sched.h"
#include "asterisk/cli.h"
#include "asterisk/manager.h"
static struct sched_context *sched;
static int refresh_sched = -1;
static pthread_t refresh_thread = AST_PTHREADT_NULL;
struct ast_dnsmgr_entry {
/*! where we will store the resulting address */
struct in_addr *result;
/*! the last result, used to check if address has changed */
struct in_addr last;
/*! Set to 1 if the entry changes */
int changed:1;
ast_mutex_t lock;
AST_RWLIST_ENTRY(ast_dnsmgr_entry) list;
/*! just 1 here, but we use calloc to allocate the correct size */
char name[1];
};
static AST_RWLIST_HEAD_STATIC(entry_list, ast_dnsmgr_entry);
AST_MUTEX_DEFINE_STATIC(refresh_lock);
#define REFRESH_DEFAULT 300
static int enabled;
static int refresh_interval;
struct refresh_info {
struct entry_list *entries;
int verbose;
unsigned int regex_present:1;
regex_t filter;
};
static struct refresh_info master_refresh_info = {
.entries = &entry_list,
.verbose = 0,
};
struct ast_dnsmgr_entry *ast_dnsmgr_get(const char *name, struct in_addr *result)
{
struct ast_dnsmgr_entry *entry;
if (!result || ast_strlen_zero(name) || !(entry = ast_calloc(1, sizeof(*entry) + strlen(name))))
return NULL;
entry->result = result;
ast_mutex_init(&entry->lock);
strcpy(entry->name, name);
memcpy(&entry->last, result, sizeof(entry->last));
AST_RWLIST_WRLOCK(&entry_list);
AST_RWLIST_INSERT_HEAD(&entry_list, entry, list);
AST_RWLIST_UNLOCK(&entry_list);
return entry;
}
void ast_dnsmgr_release(struct ast_dnsmgr_entry *entry)
{
if (!entry)
return;
AST_RWLIST_WRLOCK(&entry_list);
AST_RWLIST_REMOVE(&entry_list, entry, list);
AST_RWLIST_UNLOCK(&entry_list);
ast_verb(4, "removing dns manager for '%s'\n", entry->name);
ast_mutex_destroy(&entry->lock);
ast_free(entry);
}
int ast_dnsmgr_lookup(const char *name, struct in_addr *result, struct ast_dnsmgr_entry **dnsmgr)
{
struct ast_hostent ahp;
struct hostent *hp;
if (ast_strlen_zero(name) || !result || !dnsmgr)
return -1;
if (*dnsmgr && !strcasecmp((*dnsmgr)->name, name))
return 0;
ast_verb(4, "doing dnsmgr_lookup for '%s'\n", name);
/* if it's actually an IP address and not a name,
there's no need for a managed lookup */
if (inet_aton(name, result))
return 0;
/* do a lookup now but add a manager so it will automagically get updated in the background */
if ((hp = ast_gethostbyname(name, &ahp)))
memcpy(result, hp->h_addr, sizeof(result));
/* if dnsmgr is not enable don't bother adding an entry */
if (!enabled)
return 0;
ast_verb(3, "adding dns manager for '%s'\n", name);
*dnsmgr = ast_dnsmgr_get(name, result);
return !*dnsmgr;
}
/*
* Refresh a dnsmgr entry
*/
static int dnsmgr_refresh(struct ast_dnsmgr_entry *entry, int verbose)
{
struct ast_hostent ahp;
struct hostent *hp;
char iabuf[INET_ADDRSTRLEN];
char iabuf2[INET_ADDRSTRLEN];
struct in_addr tmp;
int changed = 0;
ast_mutex_lock(&entry->lock);
if (verbose)
ast_verb(3, "refreshing '%s'\n", entry->name);
if ((hp = ast_gethostbyname(entry->name, &ahp))) {
/* check to see if it has changed, do callback if requested (where de callback is defined ????) */
memcpy(&tmp, hp->h_addr, sizeof(tmp));
if (tmp.s_addr != entry->last.s_addr) {
ast_copy_string(iabuf, ast_inet_ntoa(entry->last), sizeof(iabuf));
ast_copy_string(iabuf2, ast_inet_ntoa(tmp), sizeof(iabuf2));
ast_log(LOG_NOTICE, "host '%s' changed from %s to %s\n",
entry->name, iabuf, iabuf2);
memcpy(entry->result, hp->h_addr, sizeof(entry->result));
memcpy(&entry->last, hp->h_addr, sizeof(entry->last));
changed = entry->changed = 1;
}
}
ast_mutex_unlock(&entry->lock);
return changed;
}
int ast_dnsmgr_refresh(struct ast_dnsmgr_entry *entry)
{
return dnsmgr_refresh(entry, 0);
}
/*
* Check if dnsmgr entry has changed from since last call to this function
*/
int ast_dnsmgr_changed(struct ast_dnsmgr_entry *entry)
{
int changed;
ast_mutex_lock(&entry->lock);
changed = entry->changed;
entry->changed = 0;
ast_mutex_unlock(&entry->lock);
return changed;
}
static void *do_refresh(void *data)
{
for (;;) {
pthread_testcancel();
usleep((ast_sched_wait(sched)*1000));
pthread_testcancel();
ast_sched_runq(sched);
}
return NULL;
}
static int refresh_list(const void *data)
{
struct refresh_info *info = (struct refresh_info *)data;
struct ast_dnsmgr_entry *entry;
/* if a refresh or reload is already in progress, exit now */
if (ast_mutex_trylock(&refresh_lock)) {
if (info->verbose)
ast_log(LOG_WARNING, "DNS Manager refresh already in progress.\n");
return -1;
}
ast_verb(3, "Refreshing DNS lookups.\n");
AST_RWLIST_RDLOCK(info->entries);
AST_RWLIST_TRAVERSE(info->entries, entry, list) {
if (info->regex_present && regexec(&info->filter, entry->name, 0, NULL, 0))
continue;
dnsmgr_refresh(entry, info->verbose);
}
AST_RWLIST_UNLOCK(info->entries);
ast_mutex_unlock(&refresh_lock);
/* automatically reschedule based on the interval */
return refresh_interval * 1000;
}
void dnsmgr_start_refresh(void)
{
if (refresh_sched > -1) {
AST_SCHED_DEL(sched, refresh_sched);
refresh_sched = ast_sched_add_variable(sched, 100, refresh_list, &master_refresh_info, 1);
}
}
static int do_reload(int loading);
static char *handle_cli_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
switch (cmd) {
case CLI_INIT:
e->command = "dnsmgr reload";
e->usage =
"Usage: dnsmgr reload\n"
" Reloads the DNS manager configuration.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc > 2)
return CLI_SHOWUSAGE;
do_reload(0);
return CLI_SUCCESS;
}
static char *handle_cli_refresh(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
struct refresh_info info = {
.entries = &entry_list,
.verbose = 1,
};
switch (cmd) {
case CLI_INIT:
e->command = "dnsmgr refresh";
e->usage =
"Usage: dnsmgr refresh [pattern]\n"
" Peforms an immediate refresh of the managed DNS entries.\n"
" Optional regular expression pattern is used to filter the entries to refresh.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (!enabled) {
ast_cli(a->fd, "DNS Manager is disabled.\n");
return 0;
}
if (a->argc > 3) {
return CLI_SHOWUSAGE;
}
if (a->argc == 3) {
if (regcomp(&info.filter, a->argv[2], REG_EXTENDED | REG_NOSUB)) {
return CLI_SHOWUSAGE;
} else {
info.regex_present = 1;
}
}
refresh_list(&info);
if (info.regex_present) {
regfree(&info.filter);
}
return CLI_SUCCESS;
}
static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
{
int count = 0;
struct ast_dnsmgr_entry *entry;
switch (cmd) {
case CLI_INIT:
e->command = "dnsmgr status";
e->usage =
"Usage: dnsmgr status\n"
" Displays the DNS manager status.\n";
return NULL;
case CLI_GENERATE:
return NULL;
}
if (a->argc > 2)
return CLI_SHOWUSAGE;
ast_cli(a->fd, "DNS Manager: %s\n", enabled ? "enabled" : "disabled");
ast_cli(a->fd, "Refresh Interval: %d seconds\n", refresh_interval);
AST_RWLIST_RDLOCK(&entry_list);
AST_RWLIST_TRAVERSE(&entry_list, entry, list)
count++;
AST_RWLIST_UNLOCK(&entry_list);
ast_cli(a->fd, "Number of entries: %d\n", count);
return CLI_SUCCESS;
}
static struct ast_cli_entry cli_reload = AST_CLI_DEFINE(handle_cli_reload, "Reloads the DNS manager configuration");
static struct ast_cli_entry cli_refresh = AST_CLI_DEFINE(handle_cli_refresh, "Performs an immediate refresh");
static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the DNS manager status");
int dnsmgr_init(void)
{
if (!(sched = sched_context_create())) {
ast_log(LOG_ERROR, "Unable to create schedule context.\n");
return -1;
}
ast_cli_register(&cli_reload);
ast_cli_register(&cli_status);
ast_cli_register(&cli_refresh);
return do_reload(1);
}
int dnsmgr_reload(void)
{
return do_reload(0);
}
static int do_reload(int loading)
{
struct ast_config *config;
struct ast_flags config_flags = { loading ? 0 : CONFIG_FLAG_FILEUNCHANGED };
const char *interval_value;
const char *enabled_value;
int interval;
int was_enabled;
int res = -1;
if ((config = ast_config_load("dnsmgr.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
return 0;
/* ensure that no refresh cycles run while the reload is in progress */
ast_mutex_lock(&refresh_lock);
/* reset defaults in preparation for reading config file */
refresh_interval = REFRESH_DEFAULT;
was_enabled = enabled;
enabled = 0;
AST_SCHED_DEL(sched, refresh_sched);
if (config) {
if ((enabled_value = ast_variable_retrieve(config, "general", "enable"))) {
enabled = ast_true(enabled_value);
}
if ((interval_value = ast_variable_retrieve(config, "general", "refreshinterval"))) {
if (sscanf(interval_value, "%d", &interval) < 1)
ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", interval_value);
else if (interval < 0)
ast_log(LOG_WARNING, "Invalid refresh interval '%d' specified, using default\n", interval);
else
refresh_interval = interval;
}
ast_config_destroy(config);
}
if (enabled && refresh_interval)
ast_log(LOG_NOTICE, "Managed DNS entries will be refreshed every %d seconds.\n", refresh_interval);
/* if this reload enabled the manager, create the background thread
if it does not exist */
if (enabled) {
if (!was_enabled && (refresh_thread == AST_PTHREADT_NULL)) {
if (ast_pthread_create_background(&refresh_thread, NULL, do_refresh, NULL) < 0) {
ast_log(LOG_ERROR, "Unable to start refresh thread.\n");
}
}
/* make a background refresh happen right away */
refresh_sched = ast_sched_add_variable(sched, 100, refresh_list, &master_refresh_info, 1);
res = 0;
}
/* if this reload disabled the manager and there is a background thread,
kill it */
else if (!enabled && was_enabled && (refresh_thread != AST_PTHREADT_NULL)) {
/* wake up the thread so it will exit */
pthread_cancel(refresh_thread);
pthread_kill(refresh_thread, SIGURG);
pthread_join(refresh_thread, NULL);
refresh_thread = AST_PTHREADT_NULL;
res = 0;
}
else
res = 0;
ast_mutex_unlock(&refresh_lock);
manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: DNSmgr\r\nStatus: %s\r/nMessage: DNSmgr reload Requested\r\n", enabled ? "Enabled" : "Disabled");
return res;
}
| Java |
<?php
/*------------------------------------------------------------------------
# view.html.php - TrackClub Component
# ------------------------------------------------------------------------
# author Michael
# copyright Copyright (C) 2014. All Rights Reserved
# license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
# website tuscaloosatrackclub.com
-------------------------------------------------------------------------*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla view library
jimport('joomla.application.component.view');
/**
* athletes View
*/
class TrackclubsViewathletes extends JViewLegacy
{
/**
* Athletes view display method
* @return void
*/
function display($tpl = null)
{
// Include helper submenu
TrackclubsHelper::addSubmenu('athletes');
// Get data from the model
$items = $this->get('Items');
$pagination = $this->get('Pagination');
// Check for errors.
if (count($errors = $this->get('Errors'))){
JError::raiseError(500, implode('<br />', $errors));
return false;
};
// Assign data to the view
$this->items = $items;
$this->pagination = $pagination;
// Set the toolbar
$this->addToolBar();
// Show sidebar
$this->sidebar = JHtmlSidebar::render();
// Display the template
parent::display($tpl);
// Set the document
$this->setDocument();
}
/**
* Setting the toolbar
*/
protected function addToolBar()
{
$canDo = TrackclubsHelper::getActions();
JToolBarHelper::title(JText::_('Trackclubs Manager'), 'trackclubs');
if($canDo->get('core.create')){
JToolBarHelper::addNew('athlete.add', 'JTOOLBAR_NEW');
};
if($canDo->get('core.edit')){
JToolBarHelper::editList('athlete.edit', 'JTOOLBAR_EDIT');
};
if($canDo->get('core.delete')){
JToolBarHelper::deleteList('', 'athletes.delete', 'JTOOLBAR_DELETE');
};
if($canDo->get('core.admin')){
JToolBarHelper::divider();
JToolBarHelper::preferences('com_trackclubs');
};
}
/**
* Method to set up the document properties
*
*
* @return void
*/
protected function setDocument()
{
$document = JFactory::getDocument();
$document->setTitle(JText::_('Trackclubs Manager - Administrator'));
}
}
?> | Java |
package com.nilsonmassarenti.app.currencyfair.model;
/**
* This class is to manager URL of Rest.
* @author nilsonmassarenti - nilsonmassarenti@gmail.com
* @version 0.1
* Last update: 03-Mar-2015 12:20 am
*/
public class CurrencyFairURI {
public static final String DUMMY_BP = "/rest/currencyfair/dummy";
public static final String GET_CURRENCY_FAIR = "/rest/currencyfair/get/{id}";
public static final String GET_ALL_CURRENCY_FAIR = "/rest/currencyfairs";
public static final String CREATE_CURRENCY_FAIR = "/rest/currencyfair/create";
public static final String DELETE_CURRENCY_FAIR = "/rest/currencyfair/delete/{id}";
}
| Java |
/* pictool: ANSI C converter for Tibia's PIC files
* (c) 2007-2009 Ivan Vucica
* Part of OpenTibia project
*
* Although written in ANSI C, this makes use of #pragma pack(),
* make sure your compiler supports packed structures, or else.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/* Headers */
#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <errno.h>
#if !_MSC_VER
#include <unistd.h>
#endif
#if !BAZEL_BUILD
#include "../../sprdata.h"
#else
#include "sprdata.h"
#endif
#include "picfuncs.h"
#pragma pack(1)
typedef struct {
uint32_t signature;
uint16_t imgcount;
} fileheader_t;
typedef struct {
uint8_t width, height;
uint8_t unk1, unk2, unk3; /* FIXME (ivucica#4#) zerocoolz says this should be colorkey, according to http://otfans.net/showpost.php?p=840634&postcount=134 */
} picheader_t;
#pragma pack()
static int filesize (FILE* f) {
int loc = ftell(f);
int size = 0;
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, loc, SEEK_SET);
return size;
}
int writesprite (FILE *f, SDL_Surface *s, int offx, int offy, uint16_t *datasize) {
return writeSprData(f, s, offx, offy, datasize);
}
int readsprite (FILE *f, uint32_t sprloc, SDL_Surface *s, int offx, int offy) {
int oldloc = ftell(f);
int r;
fseek(f, sprloc, SEEK_SET);
r = readSprData(f, s, offx, offy);
fseek(f, oldloc, SEEK_SET);
return r;
}
int picdetails (const char* filename) {
FILE *f;
int i,j,k;
fileheader_t fh;
picheader_t ph;
uint32_t sprloc;
f = fopen(filename, "rb");
printf("information for %s\n", filename);
if (!f)
return -1;
fread(&fh, sizeof(fh), 1, f);
printf("signature %d\n", fh.signature);
printf("imagecount %d\n", fh.imgcount);
for(i = 0; i < fh.imgcount ; i++){
fread(&ph, sizeof(ph), 1, f);
printf("img%d width %d height %d bg rgb #%02x%02x%02x\n", i, ph.width, ph.height, ph.unk1, ph.unk2, ph.unk3);
for(j = 0; j<ph.height; j++){
for(k = 0; k < ph.width; k++){
fread(&sprloc, sizeof(sprloc), 1, f);
printf("sprite img %d x %d y %d location %d\n", i,k,j,sprloc);
}
}
}
return 0;
}
int dumperror_stderr(char* txt, ...)
{
va_list vl;
va_start(vl, txt);
int r = vfprintf(stderr, txt, vl);
va_end(vl);
return r;
}
int (*pictool_dumperror)(char*,...) = dumperror_stderr;
int writepic(const char* filename, int index, SDL_Surface *s){
FILE *fi, *fo;
fileheader_t fh;
picheader_t ph;
uint32_t sprloc, sproffset;
size_t continuationposi, continuationposo;
uint16_t datasize;
void *data;
int i,j,k;
fi = fopen(filename, "rb");
fo = fopen("__tmp__.pic","wb+");
if (!fi || !fo)
return -1;
fread(&fh, sizeof(fh), 1, fi);
fwrite(&fh, sizeof(fh), 1, fo);
sproffset = fh.imgcount * (sizeof(ph)+1)-2;
for(i = 0; i < fh.imgcount; i++){
fread(&ph, sizeof(ph), 1, fi);
if(i == index){
ph.width = s->w / 32;
ph.height = s->h / 32;
}
sproffset += ph.width * ph.height * 4;
fseek(fi, ph.width*ph.height*4, SEEK_CUR);
}
fseek(fi, sizeof(fh), SEEK_SET);
for(i = 0; i < fh.imgcount; i++){
fread(&ph, sizeof(ph), 1, fi);
if(i != index){
if(!ph.width || !ph.height){
fprintf(stderr, "pictool: width or height are 0\n");
return (10);
}
fwrite(&ph, sizeof(ph), 1, fo);
for(j=0; j < ph.width * ph.height; j++){
fread(&sprloc, sizeof(sprloc), 1, fi);
if(sproffset > 4000000){
dumperror_stderr("pictool: infinite loop\n");
exit(8);
}
if(sprloc > filesize(fi)){
dumperror_stderr("pictool: bad spr pointer\n");
exit(9);
}
fwrite(&sproffset, sizeof(sproffset), 1, fo);
continuationposi = ftell(fi);
continuationposo = ftell(fo);
fseek(fi, sprloc, SEEK_SET);
fseek(fo, sproffset, SEEK_SET);
fread(&datasize, sizeof(datasize), 1, fi);
fwrite(&datasize, sizeof(datasize), 1, fo);
data = malloc(datasize+2);
if(!data){
dumperror_stderr("pictool: allocation problem\n");
return (7);
}
fread(data, datasize+2, 1, fi);
fwrite(data, datasize+2, 1, fo);
free(data);
fseek(fo, continuationposo, SEEK_SET);
fseek(fi, continuationposi, SEEK_SET);
sproffset += datasize+2; // 2 == space for datasize
}
fflush(fo);
}
else{
fseek(fi, ph.width*ph.height*4, SEEK_CUR);
ph.width = s->w / 32; ph.height = s->h / 32;
fwrite(&ph, sizeof(ph), 1, fo);
for(j = 0; j < ph.height; j++){
for(k = 0; k < ph.width; k++){
/*printf("Placing %d %d on %d\n", j, k, sproffset);*/
fwrite(&sproffset, sizeof(sproffset), 1, fo);
continuationposo = ftell(fo);
fseek(fo, sproffset, SEEK_SET);
writesprite(fo, s, k * 32, j*32, &datasize);
/*printf("Its size is: %d\n", datasize);*/
fseek(fo, continuationposo, SEEK_SET);
sproffset += datasize+2;
}
}
fflush(fo);
}
}
fclose(fo);
fclose(fi);
if(rename("__tmp__.pic", filename)){
if (errno == 17) {// file exists
if(unlink(filename)) {
if (errno != 2)
return 93;
}
if(rename("__tmp__.pic", filename)){
return 92;
}
} else {
return 92;
}
}
return 0;
}
int readpic (const char* filename, int index, SDL_Surface **sr) {
/* index >= -1; -1 means that we should print out details */
SDL_Surface *s=NULL;
FILE *f;
int i,j,k;
fileheader_t fh;
picheader_t ph;
uint32_t sprloc;
uint32_t magenta;
f = fopen(filename, "rb");
if (!f)
return -1;
fread(&fh,sizeof(fh),1,f);
for(i = 0; i < fh.imgcount && i <= index; i++){
fread(&ph, sizeof(ph), 1, f);
if(i == index){
s = SDL_CreateRGBSurface(SDL_SWSURFACE, ph.width*32, ph.height*32, 32, 0xFF, 0xFF00, 0xFF0000, 0xFF000000);
if(!s){
printf("CreateRGBSurface failed: %s\n", SDL_GetError());
return -1;
}
magenta = SDL_MapRGB(s->format, 255, 0, 255);
SDL_FillRect(s, NULL, magenta);
/* FIXME (ivucica#4#) Above statement is potentially unportable to architectures with
* different endianess. Lilliputtans would be happier if we took a look at SDL
* docs and corrected this. */
for(j = 0; j < ph.height; j++){
for(k = 0; k < ph.width; k++){
fread(&sprloc, sizeof(sprloc), 1, f);
dbgprintf(":: reading sprite at pos %d %d\n", j, k);
if(readsprite(f, sprloc, s, k*32, j*32)){ /* TODO (ivucica#1#) cleanup sdl surface upon error */
return -1;
}
}
}
}
else{
fseek(f, sizeof(sprloc)*ph.height*ph.width, SEEK_CUR);
}
}
fclose(f);
*sr = s;
return 0;
}
| Java |
<?php
/*
Plugin Name: Vertical marquee post title
Description: This plug-in will create the vertical marquee effect in your website, if you want your post title to move vertically (scroll upward or downwards) in the screen use this plug-in.
Author: Gopi Ramasamy
Version: 2.5
Plugin URI: http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/
Author URI: http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/
Donate link: http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
function vmptshow()
{
$vmpt_setting = get_option('vmpt_setting');
$array = array("setting" => $vmpt_setting);
echo vmpt_shortcode($array);
}
function vmpt_shortcode( $atts )
{
global $wpdb;
$vmpt_marquee = "";
$vmpt = "";
$link = "";
//[vmpt setting="1"]
if ( ! is_array( $atts ) ) { return ''; }
$setting = $atts['setting'];
switch ($setting)
{
case 1:
$vmpt_setting = get_option('vmpt_setting1');
break;
case 2:
$vmpt_setting = get_option('vmpt_setting2');
break;
case 3:
$vmpt_setting = get_option('vmpt_setting3');
break;
case 4:
$vmpt_setting = get_option('vmpt_setting4');
break;
default:
$vmpt_setting = get_option('vmpt_setting1');
}
@list($vmpt_scrollamount, $vmpt_scrolldelay, $vmpt_direction, $vmpt_style, $vmpt_noofpost, $vmpt_categories, $vmpt_orderbys, $vmpt_order, $vmpt_spliter) = explode("~~", @$vmpt_setting);
if(!is_numeric($vmpt_scrollamount)){ $vmpt_scrollamount = 2; }
if(!is_numeric($vmpt_scrolldelay)){ $vmpt_scrolldelay = 5; }
if(!is_numeric($vmpt_noofpost)){ $vmpt_noofpost = 10; }
$sSql = query_posts('cat='.$vmpt_categories.'&orderby='.$vmpt_orderbys.'&order='.$vmpt_order.'&showposts='.$vmpt_noofpost);
if ( ! empty($sSql) )
{
$count = 0;
foreach ( $sSql as $sSql )
{
$title = stripslashes($sSql->post_title);
$link = get_permalink($sSql->ID);
if($count==0)
{
if($link != "") { $vmpt = $vmpt . "<a target='' href='".$link."'>"; }
$vmpt = $vmpt . $title;
if($link != "") { $vmpt = $vmpt . "</a>"; }
}
else
{
$vmpt = $vmpt . " <br /><br /> ";
if($link != "") { $vmpt = $vmpt . "<a target='' href='".$link."'>"; }
$vmpt = $vmpt . $title;
if($link != "") { $vmpt = $vmpt . "</a>"; }
}
$count = $count + 1;
}
}
else
{
$vmpt = __('No records found.', 'vertical-marquee-post-title');
}
wp_reset_query();
$vmpt_marquee = $vmpt_marquee . "<div style='padding:3px;' class='vmpt_marquee'>";
$vmpt_marquee = $vmpt_marquee . "<marquee style='$vmpt_style' scrollamount='$vmpt_scrollamount' scrolldelay='$vmpt_scrolldelay' direction='$vmpt_direction' onmouseover='this.stop()' onmouseout='this.start()'>";
$vmpt_marquee = $vmpt_marquee . $vmpt;
$vmpt_marquee = $vmpt_marquee . "</marquee>";
$vmpt_marquee = $vmpt_marquee . "</div>";
return $vmpt_marquee;
}
function vmpt_install()
{
add_option('vmpt_title', "Marquee post title");
add_option('vmpt_setting', "1");
add_option('vmpt_setting1', "2~~5~~up~~height:100px;~~10~~~~ID~~DESC");
add_option('vmpt_setting2', "2~~5~~up~~color:#FF0000;font:Arial;height:100px;~~10~~~~ID~~DESC");
add_option('vmpt_setting3', "2~~5~~down~~color:#FF0000;font:Arial;height:120px;~~10~~~~title~~DESC");
add_option('vmpt_setting4', "2~~5~~down~~color:#FF0000;font:Arial;height:140px;~~10~~~~rand~~DESC");
}
function vmpt_deactivation()
{
// No action required.
}
function vmpt_option()
{
?>
<div class="wrap">
<div class="form-wrap">
<div id="icon-edit" class="icon32 icon32-posts-post"><br>
</div>
<h2><?php _e('Vertical marquee post title', 'vertical-marquee-post-title'); ?></h2>
<?php
global $wpdb;
$vmpt_setting1 = get_option('vmpt_setting1');
$vmpt_setting2 = get_option('vmpt_setting2');
$vmpt_setting3 = get_option('vmpt_setting3');
$vmpt_setting4 = get_option('vmpt_setting4');
list($a1, $b1, $c1, $d1, $e1, $f1, $g1, $h1) = explode("~~", $vmpt_setting1);
list($a2, $b2, $c2, $d2, $e2, $f2, $g2, $h2) = explode("~~", $vmpt_setting2);
list($a3, $b3, $c3, $d3, $e3, $f3, $g3, $h3) = explode("~~", $vmpt_setting3);
list($a4, $b4, $c4, $d4, $e4, $f4, $g4, $h4) = explode("~~", $vmpt_setting4);
if (isset($_POST['vmpt_submit']))
{
// Just security thingy that wordpress offers us
check_admin_referer('vmpt_form_setting');
$a1 = stripslashes($_POST['vmpt_scrollamount1']);
$b1 = stripslashes($_POST['vmpt_scrolldelay1']);
$c1 = stripslashes($_POST['vmpt_direction1']);
$d1 = stripslashes($_POST['vmpt_style1']);
$e1 = stripslashes($_POST['vmpt_noofpost1']);
$f1 = stripslashes($_POST['vmpt_categories1']);
$g1 = stripslashes($_POST['vmpt_orderbys1']);
$h1 = stripslashes($_POST['vmpt_order1']);
$a2 = stripslashes($_POST['vmpt_scrollamount2']);
$b2 = stripslashes($_POST['vmpt_scrolldelay2']);
$c2 = stripslashes($_POST['vmpt_direction2']);
$d2 = stripslashes($_POST['vmpt_style2']);
$e2 = stripslashes($_POST['vmpt_noofpost2']);
$f2 = stripslashes($_POST['vmpt_categories2']);
$g2 = stripslashes($_POST['vmpt_orderbys2']);
$h2 = stripslashes($_POST['vmpt_order2']);
$a3 = stripslashes($_POST['vmpt_scrollamount3']);
$b3 = stripslashes($_POST['vmpt_scrolldelay3']);
$c3 = stripslashes($_POST['vmpt_direction3']);
$d3 = stripslashes($_POST['vmpt_style3']);
$e3 = stripslashes($_POST['vmpt_noofpost3']);
$f3 = stripslashes($_POST['vmpt_categories3']);
$g3 = stripslashes($_POST['vmpt_orderbys3']);
$h3 = stripslashes($_POST['vmpt_order3']);
$a4 = stripslashes($_POST['vmpt_scrollamount4']);
$b4 = stripslashes($_POST['vmpt_scrolldelay4']);
$c4 = stripslashes($_POST['vmpt_direction4']);
$d4 = stripslashes($_POST['vmpt_style4']);
$e4 = stripslashes($_POST['vmpt_noofpost4']);
$f4 = stripslashes($_POST['vmpt_categories4']);
$g4 = stripslashes($_POST['vmpt_orderbys4']);
$h4 = stripslashes($_POST['vmpt_order4']);
update_option('vmpt_setting1', @$a1 . "~~" . @$b1 . "~~" . @$c1 . "~~" . @$d1 . "~~" . @$e1 . "~~" . @$f1 . "~~" . @$g1 . "~~" . @$h1 . "~~" . @$i1 );
update_option('vmpt_setting2', @$a2 . "~~" . @$b2 . "~~" . @$c2 . "~~" . @$d2 . "~~" . @$e2 . "~~" . @$f2 . "~~" . @$g2 . "~~" . @$h2 . "~~" . @$i2 );
update_option('vmpt_setting3', @$a3 . "~~" . @$b3 . "~~" . @$c3 . "~~" . @$d3 . "~~" . @$e3 . "~~" . @$f3 . "~~" . @$g3 . "~~" . @$h3 . "~~" . @$i3 );
update_option('vmpt_setting4', @$a4 . "~~" . @$b4 . "~~" . @$c4 . "~~" . @$d4 . "~~" . @$e4 . "~~" . @$f4 . "~~" . @$g4 . "~~" . @$h4 . "~~" . @$i4 );
?>
<div class="updated fade">
<p><strong><?php _e('Details successfully updated.', 'vertical-marquee-post-title'); ?></strong></p>
</div>
<?php
}
echo '<form name="vmpt_form" method="post" action="">';
?>
<table width="800" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><?php
echo '<h3>'.__('Setting 1', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a1 . '" name="vmpt_scrollamount1" id="vmpt_scrollamount1" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b1 . '" name="vmpt_scrolldelay1" id="vmpt_scrolldelay1" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c1 . '" name="vmpt_direction1" id="vmpt_direction1" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d1 . '" name="vmpt_style1" id="vmpt_style1" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e1 . '" name="vmpt_noofpost1" id="vmpt_noofpost1" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f1 . '" name="vmpt_categories1" id="vmpt_categories1" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g1 . '" name="vmpt_orderbys1" id="vmpt_orderbys1" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h1 . '" name="vmpt_order1" id="vmpt_order1" /> ASC/DESC </p>';
?>
</td>
<td><?php
echo '<h3>'.__('Setting 2', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a2 . '" name="vmpt_scrollamount2" id="vmpt_scrollamount2" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b2 . '" name="vmpt_scrolldelay2" id="vmpt_scrolldelay2" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c2 . '" name="vmpt_direction2" id="vmpt_direction2" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d2 . '" name="vmpt_style2" id="vmpt_style2" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e2 . '" name="vmpt_noofpost2" id="vmpt_noofpost2" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f2 . '" name="vmpt_categories2" id="vmpt_categories2" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g2 . '" name="vmpt_orderbys2" id="vmpt_orderbys2" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h2 . '" name="vmpt_order2" id="vmpt_order2" /> ASC/DESC </p>';
?>
</td>
</tr>
<tr>
<td><?php
echo '<h3>'.__('Setting 3', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a3 . '" name="vmpt_scrollamount3" id="vmpt_scrollamount3" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b3 . '" name="vmpt_scrolldelay3" id="vmpt_scrolldelay3" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c3 . '" name="vmpt_direction3" id="vmpt_direction3" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d3 . '" name="vmpt_style3" id="vmpt_style3" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e3 . '" name="vmpt_noofpost3" id="vmpt_noofpost3" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f3 . '" name="vmpt_categories3" id="vmpt_categories3" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g3 . '" name="vmpt_orderbys3" id="vmpt_orderbys3" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h3 . '" name="vmpt_order3" id="vmpt_order3" /> ASC/DESC </p>';
?>
</td>
<td><?php
echo '<h3>'.__('Setting 4', 'vertical-marquee-post-title').'</h3>';
echo '<p>'.__('Scroll amount :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $a4 . '" name="vmpt_scrollamount4" id="vmpt_scrollamount4" /></p>';
echo '<p>'.__('Scroll delay :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $b4 . '" name="vmpt_scrolldelay4" id="vmpt_scrolldelay4" /></p>';
echo '<p>'.__('Scroll direction :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $c4 . '" name="vmpt_direction4" id="vmpt_direction4" /> '.__('(Up / Down)', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Scroll style :', 'vertical-marquee-post-title').'<br><input style="width: 250px;" type="text" value="';
echo $d4 . '" name="vmpt_style4" id="vmpt_style4" /></p>';
echo '<p>'.__('Number of post :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $e4 . '" name="vmpt_noofpost4" id="vmpt_noofpost4" /></p>';
echo '<p>'.__('Post categories :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $f4 . '" name="vmpt_categories4" id="vmpt_categories4" /> (Example: 1, 3, 4) <br> '.__('Category IDs, separated by commas.', 'vertical-marquee-post-title').'</p>';
echo '<p>'.__('Post orderbys :', 'vertical-marquee-post-title').'<br><input style="width: 200px;" type="text" value="';
echo $g4 . '" name="vmpt_orderbys4" id="vmpt_orderbys4" /> '.__('(Any 1 from below list)', 'vertical-marquee-post-title').' <br> ID / author / title / rand / date / category / modified</p>';
echo '<p>'.__('Post order :', 'vertical-marquee-post-title').'<br><input style="width: 100px;" type="text" value="';
echo $h4 . '" name="vmpt_order4" id="vmpt_order4" /> ASC/DESC </p>';
?>
</td>
</tr>
</table>
<br />
<input name="vmpt_submit" id="vmpt_submit" lang="publish" class="button-primary" value="<?php _e('Update all 4 settings', 'vertical-marquee-post-title'); ?>" type="Submit" />
<?php wp_nonce_field('vmpt_form_setting'); ?>
</form>
<h3><?php _e('Plugin configuration option', 'vertical-marquee-post-title'); ?></h3>
<ol>
<li><?php _e('Drag and drop the widget.', 'vertical-marquee-post-title'); ?></li>
<li><?php _e('Add the plugin in the posts or pages using short code.', 'vertical-marquee-post-title'); ?></li>
<li><?php _e('Add directly in to the theme using PHP code.', 'vertical-marquee-post-title'); ?></li>
</ol>
<p class="description"><?php _e('Check official website for more information ', 'vertical-marquee-post-title'); ?>
<a href="http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/" target="_blank"><?php _e('Click here', 'vertical-marquee-post-title'); ?></a></p>
</div>
</div>
<?php
}
function vmpt_add_to_menu()
{
add_options_page( __('Vertical marquee post title', 'vertical-marquee-post-title'),
__('Vertical marquee post title', 'vertical-marquee-post-title'), 'manage_options', __FILE__, 'vmpt_option' );
}
if (is_admin())
{
add_action('admin_menu', 'vmpt_add_to_menu');
}
class vmpt_widget_register extends WP_Widget
{
function __construct()
{
$widget_ops = array('classname' => 'widget_text newsticker-widget', 'description' => __('Vertical marquee post title', 'vertical-marquee-post-title'), 'vertical-marquee-post-title');
parent::__construct('vertical-marquee-post-title', __('Vertical marquee post title', 'vertical-marquee-post-title'), $widget_ops);
}
function widget( $args, $instance )
{
extract( $args, EXTR_SKIP );
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );
$vmpt_setting = $instance['vmpt_setting'];
echo $args['before_widget'];
if ( ! empty( $title ) )
{
echo $args['before_title'] . $title . $args['after_title'];
}
// Call widget method
$arr = array();
$arr["setting"] = $vmpt_setting;
echo vmpt_shortcode($arr);
// Call widget method
echo $args['after_widget'];
}
function update( $new_instance, $old_instance )
{
$instance = $old_instance;
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['vmpt_setting'] = ( ! empty( $new_instance['vmpt_setting'] ) ) ? strip_tags( $new_instance['vmpt_setting'] ) : '';
return $instance;
}
function form( $instance )
{
$defaults = array(
'title' => '',
'vmpt_setting' => ''
);
$instance = wp_parse_args( (array) $instance, $defaults);
$title = $instance['title'];
$vmpt_setting = $instance['vmpt_setting'];
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Widget title', 'vertical-marquee-post-title'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('vmpt_setting'); ?>"><?php _e('Setting', 'vertical-marquee-post-title'); ?></label>
<select class="widefat" id="<?php echo $this->get_field_id('vmpt_setting'); ?>" name="<?php echo $this->get_field_name('vmpt_setting'); ?>">
<option value="1" <?php $this->vmpt_render_selected($vmpt_setting=='1'); ?>>Setting 1</option>
<option value="2" <?php $this->vmpt_render_selected($vmpt_setting=='2'); ?>>Setting 2</option>
<option value="3" <?php $this->vmpt_render_selected($vmpt_setting=='3'); ?>>Setting 3</option>
<option value="4" <?php $this->vmpt_render_selected($vmpt_setting=='4'); ?>>Setting 4</option>
</select>
</p>
<p>
<?php _e('Check official website for more information', 'vertical-marquee-post-title'); ?>
<a target="_blank" href="http://www.gopiplus.com/work/2012/09/02/vertical-marquee-post-title-wordpress-plugin/"><?php _e('click here', 'vertical-marquee-post-title'); ?></a>
</p>
<?php
}
function vmpt_render_selected($var)
{
if ($var==1 || $var==true)
{
echo 'selected="selected"';
}
}
}
function vmpt_widget_loading()
{
register_widget( 'vmpt_widget_register' );
}
function vmpt_textdomain()
{
load_plugin_textdomain( 'vertical-marquee-post-title', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action('plugins_loaded', 'vmpt_textdomain');
register_activation_hook(__FILE__, 'vmpt_install');
register_deactivation_hook(__FILE__, 'vmpt_deactivation');
add_action( 'widgets_init', 'vmpt_widget_loading');
add_shortcode( 'vmpt', 'vmpt_shortcode' );
?> | Java |
<?php
namespace Icinga\Module\Businessprocess\Web\Form;
use Icinga\Application\Icinga;
use Icinga\Exception\ProgrammingError;
use Icinga\Web\Notification;
use Icinga\Web\Request;
use Icinga\Web\Response;
use Icinga\Web\Url;
use Exception;
/**
* QuickForm wants to be a base class for simple forms
*/
abstract class QuickForm extends QuickBaseForm
{
const ID = '__FORM_NAME';
const CSRF = '__FORM_CSRF';
/**
* The name of this form
*/
protected $formName;
/**
* Whether the form has been sent
*/
protected $hasBeenSent;
/**
* Whether the form has been sent
*/
protected $hasBeenSubmitted;
/**
* The submit caption, element - still tbd
*/
// protected $submit;
/**
* Our request
*/
protected $request;
/**
* @var Url
*/
protected $successUrl;
protected $successMessage;
protected $submitLabel;
protected $submitButtonName;
protected $deleteButtonName;
protected $fakeSubmitButtonName;
/**
* Whether form elements have already been created
*/
protected $didSetup = false;
protected $isApiRequest = false;
public function __construct($options = null)
{
parent::__construct($options);
$this->setMethod('post');
$this->getActionFromRequest()
->createIdElement()
->regenerateCsrfToken()
->setPreferredDecorators();
}
protected function getActionFromRequest()
{
$this->setAction(Url::fromRequest());
return $this;
}
protected function setPreferredDecorators()
{
$this->setAttrib('class', 'autofocus icinga-controls');
$this->setDecorators(
array(
'Description',
array('FormErrors', array('onlyCustomFormErrors' => true)),
'FormElements',
'Form'
)
);
return $this;
}
protected function addSubmitButtonIfSet()
{
if (false === ($label = $this->getSubmitLabel())) {
return;
}
if ($this->submitButtonName && $el = $this->getElement($this->submitButtonName)) {
return;
}
$el = $this->createElement('submit', $label)
->setLabel($label)
->setDecorators(array('ViewHelper'));
$this->submitButtonName = $el->getName();
$this->addElement($el);
$fakeEl = $this->createElement('submit', '_FAKE_SUBMIT')
->setLabel($label)
->setDecorators(array('ViewHelper'));
$this->fakeSubmitButtonName = $fakeEl->getName();
$this->addElement($fakeEl);
$this->addDisplayGroup(
array($this->fakeSubmitButtonName),
'fake_button',
array(
'decorators' => array('FormElements'),
'order' => 1,
)
);
$grp = array(
$this->submitButtonName,
$this->deleteButtonName
);
$this->addDisplayGroup($grp, 'buttons', array(
'decorators' => array(
'FormElements',
array('HtmlTag', array('tag' => 'dl')),
'DtDdWrapper',
),
'order' => 1000,
));
}
protected function addSimpleDisplayGroup($elements, $name, $options)
{
if (! array_key_exists('decorators', $options)) {
$options['decorators'] = array(
'FormElements',
array('HtmlTag', array('tag' => 'dl')),
'Fieldset',
);
}
return $this->addDisplayGroup($elements, $name, $options);
}
protected function createIdElement()
{
$this->detectName();
$this->addHidden(self::ID, $this->getName());
$this->getElement(self::ID)->setIgnore(true);
return $this;
}
public function getSentValue($name, $default = null)
{
$request = $this->getRequest();
if ($request->isPost() && $this->hasBeenSent()) {
return $request->getPost($name);
} else {
return $default;
}
}
public function getSubmitLabel()
{
if ($this->submitLabel === null) {
return $this->translate('Submit');
}
return $this->submitLabel;
}
public function setSubmitLabel($label)
{
$this->submitLabel = $label;
return $this;
}
public function setApiRequest($isApiRequest = true)
{
$this->isApiRequest = $isApiRequest;
return $this;
}
public function isApiRequest()
{
return $this->isApiRequest;
}
public function regenerateCsrfToken()
{
if (! $element = $this->getElement(self::CSRF)) {
$this->addHidden(self::CSRF, CsrfToken::generate());
$element = $this->getElement(self::CSRF);
}
$element->setIgnore(true);
return $this;
}
public function removeCsrfToken()
{
$this->removeElement(self::CSRF);
return $this;
}
public function setSuccessUrl($url, $params = null)
{
if (! $url instanceof Url) {
$url = Url::fromPath($url);
}
if ($params !== null) {
$url->setParams($params);
}
$this->successUrl = $url;
return $this;
}
public function getSuccessUrl()
{
$url = $this->successUrl ?: $this->getAction();
if (! $url instanceof Url) {
$url = Url::fromPath($url);
}
return $url;
}
protected function beforeSetup()
{
}
public function setup()
{
}
protected function onSetup()
{
}
public function setAction($action)
{
if ($action instanceof Url) {
$action = $action->getAbsoluteUrl('&');
}
return parent::setAction($action);
}
public function hasBeenSubmitted()
{
if ($this->hasBeenSubmitted === null) {
$req = $this->getRequest();
if ($req->isPost()) {
if (! $this->hasSubmitButton()) {
return $this->hasBeenSubmitted = $this->hasBeenSent();
}
$this->hasBeenSubmitted = $this->pressedButton(
$this->fakeSubmitButtonName,
$this->getSubmitLabel()
) || $this->pressedButton(
$this->submitButtonName,
$this->getSubmitLabel()
);
} else {
$this->hasBeenSubmitted = false;
}
}
return $this->hasBeenSubmitted;
}
protected function hasSubmitButton()
{
return $this->submitButtonName !== null;
}
protected function pressedButton($name, $label)
{
$req = $this->getRequest();
if (! $req->isPost()) {
return false;
}
$req = $this->getRequest();
$post = $req->getPost();
return array_key_exists($name, $post)
&& $post[$name] === $label;
}
protected function beforeValidation($data = array())
{
}
public function prepareElements()
{
if (! $this->didSetup) {
$this->beforeSetup();
$this->setup();
$this->addSubmitButtonIfSet();
$this->onSetup();
$this->didSetup = true;
}
return $this;
}
public function handleRequest(Request $request = null)
{
if ($request === null) {
$request = $this->getRequest();
} else {
$this->setRequest($request);
}
$this->prepareElements();
if ($this->hasBeenSent()) {
$post = $request->getPost();
if ($this->hasBeenSubmitted()) {
$this->beforeValidation($post);
if ($this->isValid($post)) {
try {
$this->onSuccess();
} catch (Exception $e) {
$this->addException($e);
$this->onFailure();
}
} else {
$this->onFailure();
}
} else {
$this->setDefaults($post);
}
} else {
// Well...
}
return $this;
}
public function addException(Exception $e, $elementName = null)
{
$file = preg_split('/[\/\\\]/', $e->getFile(), -1, PREG_SPLIT_NO_EMPTY);
$file = array_pop($file);
$msg = sprintf(
'%s (%s:%d)',
$e->getMessage(),
$file,
$e->getLine()
);
if ($el = $this->getElement($elementName)) {
$el->addError($msg);
} else {
$this->addError($msg);
}
}
public function onSuccess()
{
$this->redirectOnSuccess();
}
public function setSuccessMessage($message)
{
$this->successMessage = $message;
return $this;
}
public function getSuccessMessage($message = null)
{
if ($message !== null) {
return $message;
}
if ($this->successMessage === null) {
return t('Form has successfully been sent');
}
return $this->successMessage;
}
public function redirectOnSuccess($message = null)
{
if ($this->isApiRequest()) {
// TODO: Set the status line message?
$this->successMessage = $this->getSuccessMessage($message);
return;
}
$url = $this->getSuccessUrl();
$this->notifySuccess($this->getSuccessMessage($message));
$this->redirectAndExit($url);
}
public function onFailure()
{
}
public function notifySuccess($message = null)
{
if ($message === null) {
$message = t('Form has successfully been sent');
}
Notification::success($message);
return $this;
}
public function notifyError($message)
{
Notification::error($message);
return $this;
}
protected function redirectAndExit($url)
{
/** @var Response $response */
$response = Icinga::app()->getFrontController()->getResponse();
$response->redirectAndExit($url);
}
protected function setHttpResponseCode($code)
{
Icinga::app()->getFrontController()->getResponse()->setHttpResponseCode($code);
return $this;
}
protected function onRequest()
{
}
public function setRequest(Request $request)
{
if ($this->request !== null) {
throw new ProgrammingError('Unable to set request twice');
}
$this->request = $request;
$this->prepareElements();
$this->onRequest();
return $this;
}
/**
* @return Request
*/
public function getRequest()
{
if ($this->request === null) {
/** @var Request $request */
$request = Icinga::app()->getFrontController()->getRequest();
$this->setRequest($request);
}
return $this->request;
}
public function hasBeenSent()
{
if ($this->hasBeenSent === null) {
/** @var Request $req */
if ($this->request === null) {
$req = Icinga::app()->getFrontController()->getRequest();
} else {
$req = $this->request;
}
if ($req->isPost()) {
$post = $req->getPost();
$this->hasBeenSent = array_key_exists(self::ID, $post) &&
$post[self::ID] === $this->getName();
} else {
$this->hasBeenSent = false;
}
}
return $this->hasBeenSent;
}
protected function detectName()
{
if ($this->formName !== null) {
$this->setName($this->formName);
} else {
$this->setName(get_class($this));
}
}
}
| Java |
package pf::constants::admin_roles;
=head1 NAME
pf::constants::admin_roles - constants for admin_roles object
=cut
=head1 DESCRIPTION
pf::constants::admin_roles
=cut
use strict;
use warnings;
use base qw(Exporter);
our @EXPORT_OK = qw(@ADMIN_ACTIONS);
our @ADMIN_ACTIONS = qw(
ADMIN_ROLES_CREATE
ADMIN_ROLES_DELETE
ADMIN_ROLES_READ
ADMIN_ROLES_UPDATE
AUDITING_READ
CONFIGURATION_MAIN_READ
CONFIGURATION_MAIN_UPDATE
FINGERBANK_READ
FINGERBANK_CREATE
FINGERBANK_UPDATE
FINGERBANK_DELETE
FIREWALL_SSO_READ
FIREWALL_SSO_CREATE
FIREWALL_SSO_UPDATE
FIREWALL_SSO_DELETE
FLOATING_DEVICES_CREATE
FLOATING_DEVICES_DELETE
FLOATING_DEVICES_READ
FLOATING_DEVICES_UPDATE
INTERFACES_CREATE
INTERFACES_DELETE
INTERFACES_READ
INTERFACES_UPDATE
MAC_READ
MAC_UPDATE
NODES_CREATE
NODES_DELETE
NODES_READ
NODES_UPDATE
MSE_READ
PORTAL_PROFILES_CREATE
PORTAL_PROFILES_DELETE
PORTAL_PROFILES_READ
PORTAL_PROFILES_UPDATE
PROVISIONING_CREATE
PROVISIONING_DELETE
PROVISIONING_READ
PROVISIONING_UPDATE
REPORTS
SERVICES
SOH_CREATE
SOH_DELETE
SOH_READ
SOH_UPDATE
SWITCHES_CREATE
SWITCHES_DELETE
SWITCHES_READ
SWITCHES_UPDATE
USERAGENTS_READ
USERS_READ
USERS_CREATE
USERS_CREATE_MULTIPLE
USERS_UPDATE
USERS_DELETE
USERS_SET_ROLE
USERS_SET_ACCESS_DURATION
USERS_SET_UNREG_DATE
USERS_SET_ACCESS_LEVEL
USERS_MARK_AS_SPONSOR
USERS_ROLES_CREATE
USERS_ROLES_DELETE
USERS_ROLES_READ
USERS_ROLES_UPDATE
USERS_SOURCES_CREATE
USERS_SOURCES_DELETE
USERS_SOURCES_READ
USERS_SOURCES_UPDATE
VIOLATIONS_CREATE
VIOLATIONS_DELETE
VIOLATIONS_READ
VIOLATIONS_UPDATE
USERAGENTS_READ
RADIUS_LOG_READ
REALM_READ
REALM_CREATE
REALM_UPDATE
REALM_DELETE
DOMAIN_READ
DOMAIN_CREATE
DOMAIN_UPDATE
DOMAIN_DELETE
SCAN_READ
SCAN_CREATE
SCAN_UPDATE
SCAN_DELETE
WMI_READ
WMI_CREATE
WMI_UPDATE
WMI_DELETE
WRIX_CREATE
WRIX_DELETE
WRIX_READ
WRIX_UPDATE
PKI_PROVIDER_CREATE
PKI_PROVIDER_DELETE
PKI_PROVIDER_READ
PKI_PROVIDER_UPDATE
PFDETECT_CREATE
PFDETECT_DELETE
PFDETECT_READ
PFDETECT_UPDATE
BILLING_TIER_CREATE
BILLING_TIER_DELETE
BILLING_TIER_READ
BILLING_TIER_UPDATE
SWITCH_LOGIN_READ
SWITCH_LOGIN_WRITE
FILTERS_READ
FILTERS_UPDATE
PORTAL_MODULE_CREATE
PORTAL_MODULE_DELETE
PORTAL_MODULE_READ
PORTAL_MODULE_UPDATE
);
=head1 AUTHOR
Inverse inc. <info@inverse.ca>
=head1 COPYRIGHT
Copyright (C) 2005-2017 Inverse inc.
=head1 LICENSE
This program is free software; you can redistribute it and::or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
=cut
1;
| Java |
<?php
/****************************************************************************************\
** @name EXP Autos 2.0 **
** @package Joomla 1.6 **
** @author EXP TEAM::Alexey Kurguz (Grusha) **
** @copyright Copyright (C) 2005 - 2011 EXP TEAM::Alexey Kurguz (Grusha) **
** @link http://www.feellove.eu **
** @license Commercial License **
\****************************************************************************************/
defined('_JEXEC') or die;
jimport('joomla.application.component.controllerform');
class ExpautosproControllerExplist extends JControllerForm
{
public function getModel($name = '', $prefix = '', $config = array('ignore_request' => true))
{
return parent::getModel($name, $prefix, array('ignore_request' => false));
}
public function solid(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$value = (int) JRequest::getInt('value','0');
$field = 'solid';
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->insertdata($id,$field,$value)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&id='.(int)$id, false));
}
public function expreserved(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$value = (int) JRequest::getInt('value','0');
$field = 'expreserved';
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->insertdata($id,$field,$value)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&id='.(int)$id, false));
}
public function deletelink(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->delete_ads($id)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
}
public function extend(){
$user = JFactory::getUser();
$userid = (int) $user->id;
$id = (int) JRequest::getInt('id','0');
$model = $this->getModel('Explist', 'ExpAutosProModel');
if (!$model->extend_ads($id)) {
$errors = $model->getError();
JError::raiseWarning(500, JText::_('COM_EXPAUTOSPRO_CP_PAYMENT_PERMISSION_DENIED_TEXT'));
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&userid='.(int)$userid, false));
return false;
}
$this->setRedirect(JRoute::_('index.php?option=com_expautospro&view=explist&id='.(int)$id, false));
}
} | Java |
<?php $captcha_word = 'BKPS'; ?> | Java |
#include"population.h"
population::population() {
pop.clear();
}
population::population(Random *r) {
pop.clear();
this->r = r;
}
population::population(int n_individuos, int n_gene, Random *r) {
pop.clear();
for(int i = 0; i < n_individuos; i++) pop.push_back(*(new individuo(n_gene, r)));
this->r = r;
}
population::population(vector<individuo> i, Random *r) {
pop = i;
this->r = r;
}
vector<individuo> population::get_population() {
return pop;
}
void population::set_population(vector<individuo> i) {
pop = i;
}
void population::set_population(population p) {
pop = p.get_population();
}
int population::size() {
return pop.size();
}
void population::print() {
for(int i = 0; i < size(); i++) pop[i].print();
}
population *population::elitismo(double pel) {
int num = (int) (pel * ((double) size()));
return elitismo(num);
}
population *population::elitismo(int num) {
ranking();
vector<individuo> newp;
newp.clear();
for(int i = 0; i < num; i++)
newp.push_back(pop[i]);
return (new population(newp, r));
}
void population::calc_fitness() {
for(int i = 0; i < size(); i++) pop[i].get_objective();
}
void population::ranking() {
calc_fitness();
for(int i = 0; i < size() - 1; i++) {
for(int j = i + 1; j < size(); j++) {
if(pop[i] < pop[j]) {
individuo aux = pop[i];
pop[i] = pop[j];
pop[j] = aux;
}
}
}
int counter = 0;
pop[size() - 1].set_rank(0);
for(int i = size() - 2; i >= 0; i--) {
if(pop[i] > pop[i+1]) counter++;
pop[i].set_rank(counter);
}
}
void population::crowd() {
calc_fitness();
double *crowd = new double[size()];
for(int i = 0; i < size(); i++)
crowd[i] = 0;
for(int i = 0; i < pop[0].get_objective().size(); i++) {
// ordena por objetivo.
for(int j = 0; j < size(); j++) {
for(int k = j + 1; k < size(); k++) {
if(pop[j].get_objective(i) > pop[k].get_objective(i))
swap(pop[j], pop[k]);
}
}
for(int j = 1; j < size() - 1; j++)
crowd[j] += pop[j + 1].get_objective(i) - pop[j - 1].get_objective(i);
crowd[0] = crowd[size() - 1] = 3000; //numeric_limits<double>::infinity();
}
for(int i = 0; i < size(); i++)
pop[i].set_crowd(crowd[i]);
}
void population::sort() {
for(int i = 0; i < size() - 1; i++) {
for(int j = i + 1; j < size(); j++) {
if(pop[i].get_rank() < pop[j].get_rank()) {
swap(pop[i], pop[j]);
} else if(pop[i].get_rank() == pop[j].get_rank() && pop[i].get_crowd() < pop[j].get_crowd()) {
swap(pop[i], pop[j]);
}
}
}
}
population population::operator+(const population &p) {
vector<individuo> n;
n = p.pop;
for(int i = 0; i < pop.size(); i++) n.push_back(pop[i]);
return *(new population(n, r));
}
//population population::operator+=(const population &p) {return *this = *this + p;}
population *population::mutation(int num_ind, int num_gene) {
printf("mut a\n");
population *newp = new population(num_ind, pop[0].get_cromossomo().get_n_gene(), r);
printf("mut b\n");
for(int i = 0; i < num_ind; i++) {
newp->pop[i] = pop[r->nextLongInt(pop.size())].mutation(num_gene);
}
printf("mut c\n");
return newp;
}
population *population::mutation(int num_ind) { return mutation(num_ind, 1);}
population *population::mutation(double pmut, int num_gene) {
int num_ind = (int) (pmut * ((double) pop.size()));
return mutation(num_ind,num_gene);
}
population *population::mutation(double pmut) { return mutation(pmut, 1);}
individuo population::get_individuo(int index){
return pop[index];
}
void population::add_individuo(individuo i){ pop.push_back(i);}
void population::add_individuo(vector<individuo> i){
for (int index = 0; index < i.size(); index ++){
add_individuo(i[index]);
}
}
population *population::crossover( double pcrv){
int ncrv = (int) (pcrv * ((double) size()));
return crossover(ncrv);
}
population *population::crossover( int ncrv){
population *p = new population();
for (int i = 0; i < ncrv; i ++ ) {
p->add_individuo(pop[r->nextLongInt(size())] + pop[r->nextLongInt(size())]);
}
return p;
}
population *population::tournament(int num_ind, int num_group) {
printf("inicio\n");
vector<individuo> group;
if(num_ind < 1) return NULL;
population *newp = new population(r);
for(int i = 0; i < num_ind; i++) {
group.clear();
for(int j = 0; j < num_group; j++)
group.push_back(pop[r->nextLongInt(pop.size())]);
individuo maior = group[0];
for(int j = 1; j < group.size(); j++)
if(group[j] > maior)
maior = group[j];
newp->add_individuo(maior);
}
printf("fim\n");
return newp;
}
population *population::roulette(int num_ind, int param) {
population *newp = new population(r);
double max = 0;
vector<double> roulette;
roulette.clear();
if(param == ROULETTE_RANK || param == ROULETTE_MULTIPOINTER_RANK) {
for(int i = 0; i < pop.size(); i++) {
max += (double) pop[i].get_rank();
roulette.push_back(max);
}
} else {
for(int i = 0; i < pop.size(); i++) {
max += pop[i].get_objective(0);
roulette.push_back(max);
}
}
if(param == ROULETTE_RANK || param == ROULETTE_OBJECTIVE) {
for(int i = 0; i < num_ind; i++) {
double pointer = r->nextDouble(max);
int j;
for(j = 0; roulette[j] < pointer; j++);
newp->add_individuo(pop[j]);
}
}
else {
double pointer;
double delta = max / (double) num_ind;
pointer = r->nextDouble(max / (double) num_ind);
int j = 0;
for(int i = 0; i < num_ind; i++) {
for(j; roulette[j] < pointer; j++);
newp->add_individuo(pop[j]);
pointer += delta;
}
}
return newp;
}
void population::resize(int n ){
if(n < pop.size())
pop.resize(n);
}
| Java |
#Date: 2015-10-01 16:06:58 UTC
#Software: Joomla Platform 13.1.0 Stable [ Curiosity ] 24-Apr-2013 00:00 GMT
#Fields: datetime priority message
2015-10-01T16:06:58+00:00 INFO |¯¯¯ Starting
2015-10-01T16:06:58+00:00 INFO | ^^ Connecting to ...
2015-10-01T16:06:58+00:00 ERROR | XX Unable to connect to FTP server
2015-10-01T16:06:58+00:00 ERROR |___ :(
2015-10-01T16:06:58+00:00 ERROR
| Java |
/*
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Player.h"
#include "Language.h"
#include "Database/DatabaseEnv.h"
#include "Log.h"
#include "Opcodes.h"
#include "SpellMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "UpdateMask.h"
#include "QuestDef.h"
#include "GossipDef.h"
#include "UpdateData.h"
#include "Channel.h"
#include "ChannelMgr.h"
#include "MapManager.h"
#include "MapPersistentStateMgr.h"
#include "InstanceData.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "ObjectMgr.h"
#include "ObjectAccessor.h"
#include "CreatureAI.h"
#include "Formulas.h"
#include "Group.h"
#include "Guild.h"
#include "GuildMgr.h"
#include "Pet.h"
#include "Util.h"
#include "Transports.h"
#include "Weather.h"
#include "BattleGround.h"
#include "BattleGroundAV.h"
#include "BattleGroundMgr.h"
#include "WorldPvP/WorldPvP.h"
#include "WorldPvP/WorldPvPMgr.h"
#include "ArenaTeam.h"
#include "Chat.h"
#include "Database/DatabaseImpl.h"
#include "Spell.h"
#include "ScriptMgr.h"
#include "SocialMgr.h"
#include "AchievementMgr.h"
#include "Mail.h"
#include "SpellAuras.h"
#include <cmath>
// Playerbot mod:
#include "playerbot/PlayerbotAI.h"
#include "playerbot/PlayerbotMgr.h"
#include "Config/Config.h"
#define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS)
#define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
#define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
#define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
#define SKILL_VALUE(x) PAIR32_LOPART(x)
#define SKILL_MAX(x) PAIR32_HIPART(x)
#define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
#define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
#define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
#define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
enum CharacterFlags
{
CHARACTER_FLAG_NONE = 0x00000000,
CHARACTER_FLAG_UNK1 = 0x00000001,
CHARACTER_FLAG_UNK2 = 0x00000002,
CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
CHARACTER_FLAG_UNK4 = 0x00000008,
CHARACTER_FLAG_UNK5 = 0x00000010,
CHARACTER_FLAG_UNK6 = 0x00000020,
CHARACTER_FLAG_UNK7 = 0x00000040,
CHARACTER_FLAG_UNK8 = 0x00000080,
CHARACTER_FLAG_UNK9 = 0x00000100,
CHARACTER_FLAG_UNK10 = 0x00000200,
CHARACTER_FLAG_HIDE_HELM = 0x00000400,
CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
CHARACTER_FLAG_UNK13 = 0x00001000,
CHARACTER_FLAG_GHOST = 0x00002000,
CHARACTER_FLAG_RENAME = 0x00004000,
CHARACTER_FLAG_UNK16 = 0x00008000,
CHARACTER_FLAG_UNK17 = 0x00010000,
CHARACTER_FLAG_UNK18 = 0x00020000,
CHARACTER_FLAG_UNK19 = 0x00040000,
CHARACTER_FLAG_UNK20 = 0x00080000,
CHARACTER_FLAG_UNK21 = 0x00100000,
CHARACTER_FLAG_UNK22 = 0x00200000,
CHARACTER_FLAG_UNK23 = 0x00400000,
CHARACTER_FLAG_UNK24 = 0x00800000,
CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
CHARACTER_FLAG_DECLINED = 0x02000000,
CHARACTER_FLAG_UNK27 = 0x04000000,
CHARACTER_FLAG_UNK28 = 0x08000000,
CHARACTER_FLAG_UNK29 = 0x10000000,
CHARACTER_FLAG_UNK30 = 0x20000000,
CHARACTER_FLAG_UNK31 = 0x40000000,
CHARACTER_FLAG_UNK32 = 0x80000000
};
enum CharacterCustomizeFlags
{
CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
};
// corpse reclaim times
#define DEATH_EXPIRE_STEP (5*MINUTE)
#define MAX_DEATH_COUNT 3
static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
//== PlayerTaxi ================================================
PlayerTaxi::PlayerTaxi()
{
// Taxi nodes
memset(m_taximask, 0, sizeof(m_taximask));
}
void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
{
// class specific initial known nodes
switch(chrClass)
{
case CLASS_DEATH_KNIGHT:
{
for(int i = 0; i < TaxiMaskSize; ++i)
m_taximask[i] |= sOldContinentsNodesMask[i];
break;
}
}
// race specific initial known nodes: capital and taxi hub masks
switch(race)
{
case RACE_HUMAN: SetTaximaskNode(2); break; // Human
case RACE_ORC: SetTaximaskNode(23); break; // Orc
case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
case RACE_NIGHTELF: SetTaximaskNode(26);
SetTaximaskNode(27); break; // Night Elf
case RACE_UNDEAD: SetTaximaskNode(11); break; // Undead
case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
case RACE_TROLL: SetTaximaskNode(23); break; // Troll
case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
}
// new continent starting masks (It will be accessible only at new map)
switch(Player::TeamForRace(race))
{
case ALLIANCE: SetTaximaskNode(100); break;
case HORDE: SetTaximaskNode(99); break;
default: break;
}
// level dependent taxi hubs
if (level>=68)
SetTaximaskNode(213); //Shattered Sun Staging Area
}
void PlayerTaxi::LoadTaxiMask(const char* data)
{
Tokens tokens(data, ' ');
int index;
Tokens::iterator iter;
for (iter = tokens.begin(), index = 0;
(index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
{
// load and set bits only for existing taxi nodes
m_taximask[index] = sTaxiNodesMask[index] & uint32(atol(*iter));
}
}
void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
{
if (all)
{
for (uint8 i=0; i<TaxiMaskSize; ++i)
data << uint32(sTaxiNodesMask[i]); // all existing nodes
}
else
{
for (uint8 i=0; i<TaxiMaskSize; ++i)
data << uint32(m_taximask[i]); // known nodes
}
}
bool PlayerTaxi::LoadTaxiDestinationsFromString(const std::string& values, Team team)
{
ClearTaxiDestinations();
Tokens tokens(values, ' ');
for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
{
uint32 node = uint32(atol(*iter));
AddTaxiDestination(node);
}
if (m_TaxiDestinations.empty())
return true;
// Check integrity
if (m_TaxiDestinations.size() < 2)
return false;
for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
{
uint32 cost;
uint32 path;
sObjectMgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i], path, cost);
if (!path)
return false;
}
// can't load taxi path without mount set (quest taxi path?)
if (!sObjectMgr.GetTaxiMountDisplayId(GetTaxiSource(), team, true))
return false;
return true;
}
std::string PlayerTaxi::SaveTaxiDestinationsToString()
{
if (m_TaxiDestinations.empty())
return "";
std::ostringstream ss;
for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
ss << m_TaxiDestinations[i] << " ";
return ss.str();
}
uint32 PlayerTaxi::GetCurrentTaxiPath() const
{
if (m_TaxiDestinations.size() < 2)
return 0;
uint32 path;
uint32 cost;
sObjectMgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
return path;
}
std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
{
for(int i = 0; i < TaxiMaskSize; ++i)
ss << taxi.m_taximask[i] << " ";
return ss;
}
//== TradeData =================================================
TradeData* TradeData::GetTraderData() const
{
return m_trader->GetTradeData();
}
Item* TradeData::GetItem( TradeSlots slot ) const
{
return m_items[slot] ? m_player->GetItemByGuid(m_items[slot]) : NULL;
}
bool TradeData::HasItem( ObjectGuid item_guid ) const
{
for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
if (m_items[i] == item_guid)
return true;
return false;
}
Item* TradeData::GetSpellCastItem() const
{
return m_spellCastItem ? m_player->GetItemByGuid(m_spellCastItem) : NULL;
}
void TradeData::SetItem( TradeSlots slot, Item* item )
{
ObjectGuid itemGuid = item ? item->GetObjectGuid() : ObjectGuid();
if (m_items[slot] == itemGuid)
return;
m_items[slot] = itemGuid;
SetAccepted(false);
GetTraderData()->SetAccepted(false);
Update();
// need remove possible trader spell applied to changed item
if (slot == TRADE_SLOT_NONTRADED)
GetTraderData()->SetSpell(0);
// need remove possible player spell applied (possible move reagent)
SetSpell(0);
}
void TradeData::SetSpell( uint32 spell_id, Item* castItem /*= NULL*/ )
{
ObjectGuid itemGuid = castItem ? castItem->GetObjectGuid() : ObjectGuid();
if (m_spell == spell_id && m_spellCastItem == itemGuid)
return;
m_spell = spell_id;
m_spellCastItem = itemGuid;
SetAccepted(false);
GetTraderData()->SetAccepted(false);
Update(true); // send spell info to item owner
Update(false); // send spell info to caster self
}
void TradeData::SetMoney( uint32 money )
{
if (m_money == money)
return;
m_money = money;
SetAccepted(false);
GetTraderData()->SetAccepted(false);
Update();
}
void TradeData::Update( bool for_trader /*= true*/ )
{
if (for_trader)
m_trader->GetSession()->SendUpdateTrade(true); // player state for trader
else
m_player->GetSession()->SendUpdateTrade(false); // player state for player
}
void TradeData::SetAccepted(bool state, bool crosssend /*= false*/)
{
m_accepted = state;
if (!state)
{
if (crosssend)
m_trader->GetSession()->SendTradeStatus(TRADE_STATUS_BACK_TO_TRADE);
else
m_player->GetSession()->SendTradeStatus(TRADE_STATUS_BACK_TO_TRADE);
}
}
//== Player ====================================================
UpdateMask Player::updateVisualBits;
Player::Player (WorldSession *session): Unit(), m_mover(this), m_camera(this), m_achievementMgr(this), m_reputationMgr(this)
{
m_speakTime = 0;
m_speakCount = 0;
m_objectType |= TYPEMASK_PLAYER;
m_objectTypeId = TYPEID_PLAYER;
m_valuesCount = PLAYER_END;
SetActiveObjectState(true); // player is always active object
m_session = session;
m_ExtraFlags = 0;
if (GetSession()->GetSecurity() >= SEC_GAMEMASTER)
SetAcceptTicket(true);
// players always accept
if (GetSession()->GetSecurity() == SEC_PLAYER)
SetAcceptWhispers(true);
m_usedTalentCount = 0;
m_questRewardTalentCount = 0;
m_regenTimer = REGEN_TIME_FULL;
m_weaponChangeTimer = 0;
m_zoneUpdateId = 0;
m_zoneUpdateTimer = 0;
m_areaUpdateId = 0;
m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
// randomize first save time in range [CONFIG_UINT32_INTERVAL_SAVE] around [CONFIG_UINT32_INTERVAL_SAVE]
// this must help in case next save after mass player load after server startup
m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
clearResurrectRequestData();
memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
m_social = NULL;
// group is initialized in the reference constructor
SetGroupInvite(NULL);
m_groupUpdateMask = 0;
m_auraUpdateMask = 0;
duel = NULL;
m_GuildIdInvited = 0;
m_ArenaTeamIdInvited = 0;
m_atLoginFlags = AT_LOGIN_NONE;
mSemaphoreTeleport_Near = false;
mSemaphoreTeleport_Far = false;
m_DelayedOperations = 0;
m_bCanDelayTeleport = false;
m_bHasDelayedTeleport = false;
m_bHasBeenAliveAtDelayedTeleport = true; // overwrite always at setup teleport data, so not used infact
m_teleport_options = 0;
m_trade = NULL;
m_cinematic = 0;
PlayerTalkClass = new PlayerMenu( GetSession() );
m_currentBuybackSlot = BUYBACK_SLOT_START;
m_DailyQuestChanged = false;
m_WeeklyQuestChanged = false;
for (int i=0; i<MAX_TIMERS; ++i)
m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
m_MirrorTimerFlags = UNDERWATER_NONE;
m_MirrorTimerFlagsLast = UNDERWATER_NONE;
m_isInWater = false;
m_drunkTimer = 0;
m_drunk = 0;
m_restTime = 0;
m_deathTimer = 0;
m_deathExpireTime = 0;
m_swingErrorMsg = 0;
m_DetectInvTimer = 1*IN_MILLISECONDS;
for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
{
m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
m_bgBattleGroundQueueID[j].invitedToInstance = 0;
}
m_logintime = time(NULL);
m_Last_tick = m_logintime;
m_WeaponProficiency = 0;
m_ArmorProficiency = 0;
m_canParry = false;
m_canBlock = false;
m_canDualWield = false;
m_canTitanGrip = false;
m_ammoDPS = 0.0f;
m_temporaryUnsummonedPetNumber.clear();
////////////////////Rest System/////////////////////
time_inn_enter=0;
inn_trigger_id=0;
m_rest_bonus=0;
rest_type=REST_TYPE_NO;
////////////////////Rest System/////////////////////
m_mailsUpdated = false;
unReadMails = 0;
m_nextMailDelivereTime = 0;
m_resetTalentsCost = 0;
m_resetTalentsTime = 0;
m_itemUpdateQueueBlocked = false;
for (int i = 0; i < MAX_MOVE_TYPE; ++i)
m_forced_speed_changes[i] = 0;
m_stableSlots = 0;
/////////////////// Instance System /////////////////////
m_HomebindTimer = 0;
m_InstanceValid = true;
m_Difficulty = 0;
SetDungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL);
SetRaidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL);
m_lastPotionId = 0;
m_activeSpec = 0;
m_specsCount = 1;
for (int i = 0; i < BASEMOD_END; ++i)
{
m_auraBaseMod[i][FLAT_MOD] = 0.0f;
m_auraBaseMod[i][PCT_MOD] = 1.0f;
}
for (int i = 0; i < MAX_COMBAT_RATING; ++i)
m_baseRatingValue[i] = 0;
m_baseSpellPower = 0;
m_baseFeralAP = 0;
m_baseManaRegen = 0;
m_baseHealthRegen = 0;
m_armorPenetrationPct = 0.0f;
m_spellPenetrationItemMod = 0;
// Honor System
m_lastHonorUpdateTime = time(NULL);
m_IsBGRandomWinner = false;
// Player summoning
m_summon_expire = 0;
m_summon_mapid = 0;
m_summon_x = 0.0f;
m_summon_y = 0.0f;
m_summon_z = 0.0f;
m_contestedPvPTimer = 0;
m_declinedname = NULL;
m_runes = NULL;
m_lastFallTime = 0;
m_lastFallZ = 0;
// Refer-A-Friend
m_GrantableLevelsCount = 0;
// Playerbot mod:
m_playerbotAI = NULL;
m_playerbotMgr = NULL;
m_anticheat = new AntiCheat(this);
SetPendingBind(NULL, 0);
m_LFGState = new LFGPlayerState(this);
m_cachedGS = 0;
}
Player::~Player ()
{
CleanupsBeforeDelete();
// it must be unloaded already in PlayerLogout and accessed only for loggined player
//m_social = NULL;
// Note: buy back item already deleted from DB when player was saved
for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
{
if (m_items[i])
delete m_items[i];
}
CleanupChannels();
//all mailed items should be deleted, also all mail should be deallocated
for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
delete *itr;
for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
delete PlayerTalkClass;
if (m_transport)
m_transport->RemovePassenger(this);
for(size_t x = 0; x < ItemSetEff.size(); x++)
if (ItemSetEff[x])
delete ItemSetEff[x];
// clean up player-instance binds, may unload some instance saves
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
itr->second.state->RemovePlayer(this);
delete m_declinedname;
delete m_runes;
delete m_anticheat;
delete m_LFGState;
// Playerbot mod
if (m_playerbotAI)
{
delete m_playerbotAI;
m_playerbotAI = NULL;
}
if (m_playerbotMgr)
{
delete m_playerbotMgr;
m_playerbotMgr = NULL;
}
}
void Player::CleanupsBeforeDelete()
{
if (m_uint32Values) // only for fully created Object
{
TradeCancel(false);
DuelComplete(DUEL_INTERUPTED);
}
// notify zone scripts for player logout
sWorldPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
Unit::CleanupsBeforeDelete();
}
bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 /*outfitId */)
{
//FIXME: outfitId not used in player creating
Object::_Create(ObjectGuid(HIGHGUID_PLAYER, guidlow));
m_name = name;
PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, class_);
if(!info)
{
sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
return false;
}
ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
if(!cEntry)
{
sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
return false;
}
// player store gender in single bit
if (gender != uint8(GENDER_MALE) && gender != uint8(GENDER_FEMALE))
{
sLog.outError("Invalid gender %u at player creating", uint32(gender));
return false;
}
for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
m_items[i] = NULL;
SetLocationMapId(info->mapId);
Relocate(info->positionX,info->positionY,info->positionZ, info->orientation);
setFactionForRace(race);
SetMap(sMapMgr.CreateMap(info->mapId, this));
uint8 powertype = cEntry->powerType;
SetByteValue(UNIT_FIELD_BYTES_0, 0, race);
SetByteValue(UNIT_FIELD_BYTES_0, 1, class_);
SetByteValue(UNIT_FIELD_BYTES_0, 2, gender);
SetByteValue(UNIT_FIELD_BYTES_0, 3, powertype);
InitDisplayIds(); // model, scale and model data
SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, -1); // -1 is default value
SetByteValue(PLAYER_BYTES, 0, skin);
SetByteValue(PLAYER_BYTES, 1, face);
SetByteValue(PLAYER_BYTES, 2, hairStyle);
SetByteValue(PLAYER_BYTES, 3, hairColor);
SetByteValue(PLAYER_BYTES_2, 0, facialHair);
LoadAccountLinkedState();
if (GetAccountLinkedState() != STATE_NOT_LINKED)
SetByteValue(PLAYER_BYTES_2, 3, 0x06); // rest state = refer-a-friend
else
SetByteValue(PLAYER_BYTES_2, 3, 0x02); // rest state = normal
SetUInt16Value(PLAYER_BYTES_3, 0, gender); // only GENDER_MALE/GENDER_FEMALE (1 bit) allowed, drunk state = 0
SetByteValue(PLAYER_BYTES_3, 3, 0); // BattlefieldArenaFaction (0 or 1)
SetUInt32Value( PLAYER_GUILDID, 0 );
SetUInt32Value( PLAYER_GUILDRANK, 0 );
SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
for(int i = 0; i < KNOWN_TITLES_SIZE; ++i)
SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES + i, 0); // 0=disabled
SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
// set starting level
uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
? sWorld.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL)
: sWorld.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL);
if (GetSession()->GetSecurity() >= SEC_MODERATOR)
{
uint32 gm_level = sWorld.getConfig(CONFIG_UINT32_START_GM_LEVEL);
if (gm_level > start_level)
start_level = gm_level;
}
SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
InitRunes();
SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_UINT32_START_PLAYER_MONEY));
SetHonorPoints(sWorld.getConfig(CONFIG_UINT32_START_HONOR_POINTS));
SetArenaPoints(sWorld.getConfig(CONFIG_UINT32_START_ARENA_POINTS));
// Played time
m_Last_tick = time(NULL);
m_Played_time[PLAYED_TIME_TOTAL] = 0;
m_Played_time[PLAYED_TIME_LEVEL] = 0;
// base stats and related field values
InitStatsForLevel();
InitTaxiNodesForLevel();
InitGlyphsForLevel();
InitTalentForLevel();
InitPrimaryProfessions(); // to max set before any spell added
// apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
SetHealth(GetMaxHealth());
if (getPowerType() == POWER_MANA)
{
UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
}
if (getPowerType() != POWER_MANA) // hide additional mana bar if we have no mana
{
SetPower(POWER_MANA, 0);
SetMaxPower(POWER_MANA, 0);
}
// original spells
learnDefaultSpells();
// original action bar
for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
addActionButton(0, action_itr->button,action_itr->action,action_itr->type);
// original items
uint32 raceClassGender = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0x00FFFFFF;
CharStartOutfitEntry const* oEntry = NULL;
for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
{
if (CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
{
if (entry->RaceClassGender == raceClassGender)
{
oEntry = entry;
break;
}
}
}
if (oEntry)
{
for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
{
if (oEntry->ItemId[j] <= 0)
continue;
uint32 item_id = oEntry->ItemId[j];
// just skip, reported in ObjectMgr::LoadItemPrototypes
ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id);
if(!iProto)
continue;
// BuyCount by default
int32 count = iProto->BuyCount;
// special amount for foor/drink
if (iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
{
switch(iProto->Spells[0].SpellCategory)
{
case 11: // food
count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
break;
case 59: // drink
count = 2;
break;
}
if (iProto->Stackable < count)
count = iProto->Stackable;
}
StoreNewItemInBestSlots(item_id, count);
}
}
for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr != info->item.end(); ++item_id_itr)
StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
// bags and main-hand weapon must equipped at this moment
// now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
// or ammo not equipped in special bag
for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
uint16 eDest;
// equip offhand weapon/shield if it attempt equipped before main-hand weapon
InventoryResult msg = CanEquipItem(NULL_SLOT, eDest, pItem, false);
if (msg == EQUIP_ERR_OK)
{
RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
EquipItem(eDest, pItem, true);
}
// move other items to more appropriate slots (ammo not equipped in special bag)
else
{
ItemPosCountVec sDest;
msg = CanStoreItem(NULL_BAG, NULL_SLOT, sDest, pItem, false);
if (msg == EQUIP_ERR_OK)
{
RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
pItem = StoreItem( sDest, pItem, true);
}
// if this is ammo then use it
msg = CanUseAmmo(pItem->GetEntry());
if (msg == EQUIP_ERR_OK)
SetAmmo(pItem->GetEntry());
}
}
}
// all item positions resolved
return true;
}
bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
{
DEBUG_LOG("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
// attempt equip by one
while(titem_amount > 0)
{
uint16 eDest;
uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
if ( msg != EQUIP_ERR_OK )
break;
EquipNewItem( eDest, titem_id, true);
AutoUnequipOffhandIfNeed();
--titem_amount;
}
if (titem_amount == 0)
return true; // equipped
// attempt store
ItemPosCountVec sDest;
// store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
if ( msg == EQUIP_ERR_OK )
{
StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
return true; // stored
}
// item can't be added
sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
return false;
}
// helper function, mainly for script side, but can be used for simple task in mangos also.
Item* Player::StoreNewItemInInventorySlot(uint32 itemEntry, uint32 amount)
{
ItemPosCountVec vDest;
uint8 msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, vDest, itemEntry, amount);
if (msg == EQUIP_ERR_OK)
{
if (Item* pItem = StoreNewItem(vDest, itemEntry, true, Item::GenerateItemRandomPropertyId(itemEntry)))
return pItem;
}
return NULL;
}
void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
{
if (int(MaxValue) == DISABLED_MIRROR_TIMER)
{
if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
StopMirrorTimer(Type);
return;
}
WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
data << (uint32)Type;
data << CurrentValue;
data << MaxValue;
data << Regen;
data << (uint8)0;
data << (uint32)0; // spell id
GetSession()->SendPacket( &data );
}
void Player::StopMirrorTimer(MirrorTimerType Type)
{
m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
data << (uint32)Type;
GetSession()->SendPacket( &data );
}
uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
{
if(!isAlive() || isGameMaster())
return 0;
// Absorb, resist some environmental damage type
uint32 absorb = 0;
uint32 resist = 0;
if (type == DAMAGE_LAVA)
CalculateDamageAbsorbAndResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
else if (type == DAMAGE_SLIME)
CalculateDamageAbsorbAndResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
damage-=absorb+resist;
DealDamageMods(this,damage,&absorb);
WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
data << GetObjectGuid();
data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
data << uint32(damage);
data << uint32(absorb);
data << uint32(resist);
SendMessageToSet(&data, true);
uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
if(!isAlive())
{
if (type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
{
DEBUG_LOG("We are fall to death, loosing 10 percents durability");
DurabilityLossAll(0.10f,false);
// durability lost message
WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
GetSession()->SendPacket(&data2);
}
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
}
return final_damage;
}
int32 Player::getMaxTimer(MirrorTimerType timer)
{
switch (timer)
{
case FATIGUE_TIMER:
if (GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_GMLEVEL))
return DISABLED_MIRROR_TIMER;
return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_MAX)*IN_MILLISECONDS;
case BREATH_TIMER:
{
if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) ||
GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL))
return DISABLED_MIRROR_TIMER;
int32 UnderWaterTime = sWorld.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_MAX)*IN_MILLISECONDS;
AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
return UnderWaterTime;
}
case FIRE_TIMER:
{
if (!isAlive() || GetSession()->GetSecurity() >= (AccountTypes)sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_GMLEVEL))
return DISABLED_MIRROR_TIMER;
return sWorld.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_MAX)*IN_MILLISECONDS;
}
default:
return 0;
}
return 0;
}
void Player::UpdateMirrorTimers()
{
// Desync flags for update on next HandleDrowning
if (m_MirrorTimerFlags)
m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
}
void Player::HandleDrowning(uint32 time_diff)
{
if (!m_MirrorTimerFlags)
return;
// In water
if (m_MirrorTimerFlags & UNDERWATER_INWATER)
{
// Breath timer not activated - activate it
if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
{
m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
}
else // If activated - do tick
{
m_MirrorTimer[BREATH_TIMER]-=time_diff;
// Timer limit - need deal damage
if (m_MirrorTimer[BREATH_TIMER] < 0)
{
m_MirrorTimer[BREATH_TIMER] += 2 * IN_MILLISECONDS;
// Calculate and deal damage
// TODO: Check this formula
uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
EnvironmentalDamage(DAMAGE_DROWNING, damage);
}
else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
}
}
else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
{
int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
// Need breath regen
m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
StopMirrorTimer(BREATH_TIMER);
else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
}
// In dark water
if (m_MirrorTimerFlags & UNDERWATER_INDARKWATER)
{
// Fatigue timer not activated - activate it
if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
{
m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
}
else
{
m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
// Timer limit - need deal damage or teleport ghost to graveyard
if (m_MirrorTimer[FATIGUE_TIMER] < 0)
{
m_MirrorTimer[FATIGUE_TIMER] += 2 * IN_MILLISECONDS;
if (isAlive()) // Calculate and deal damage
{
uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
}
else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
RepopAtGraveyard();
}
else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER))
SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
}
}
else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
{
int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
StopMirrorTimer(FATIGUE_TIMER);
else if (m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER)
SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
}
if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
{
// Breath timer not activated - activate it
if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
else
{
m_MirrorTimer[FIRE_TIMER]-=time_diff;
if (m_MirrorTimer[FIRE_TIMER] < 0)
{
m_MirrorTimer[FIRE_TIMER] += 2 * IN_MILLISECONDS;
// Calculate and deal damage
// TODO: Check this formula
uint32 damage = urand(600, 700);
if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
EnvironmentalDamage(DAMAGE_LAVA, damage);
// need to skip Slime damage in Undercity and Ruins of Lordaeron arena
// maybe someone can find better way to handle environmental damage
else if (m_zoneUpdateId != 1497 && m_zoneUpdateId != 3968)
EnvironmentalDamage(DAMAGE_SLIME, damage);
}
}
}
else
m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
// Recheck timers flag
m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
for (int i = 0; i< MAX_TIMERS; ++i)
if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
{
m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
break;
}
m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
}
///The player sobers by 256 every 10 seconds
void Player::HandleSobering()
{
m_drunkTimer = 0;
uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
SetDrunkValue(drunk);
}
DrunkenState Player::GetDrunkenstateByValue(uint16 value)
{
if (value >= 23000)
return DRUNKEN_SMASHED;
if (value >= 12800)
return DRUNKEN_DRUNK;
if (value & 0xFFFE)
return DRUNKEN_TIPSY;
return DRUNKEN_SOBER;
}
void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
{
uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
m_drunk = newDrunkenValue;
SetUInt16Value(PLAYER_BYTES_3, 0, uint16(getGender()) | (m_drunk & 0xFFFE));
uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
// special drunk invisibility detection
if (newDrunkenState >= DRUNKEN_DRUNK)
m_detectInvisibilityMask |= (1<<6);
else
m_detectInvisibilityMask &= ~(1<<6);
if (newDrunkenState == oldDrunkenState)
return;
WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
data << GetObjectGuid();
data << uint32(newDrunkenState);
data << uint32(itemId);
SendMessageToSet(&data, true);
}
void Player::Update( uint32 update_diff, uint32 p_time )
{
if(!IsInWorld())
return;
// remove failed timed Achievements
GetAchievementMgr().DoFailedTimedAchievementCriterias();
// undelivered mail
if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
{
SendNewMail();
++unReadMails;
// It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
m_nextMailDelivereTime = 0;
}
//used to implement delayed far teleports
SetCanDelayTeleport(true);
Unit::Update( update_diff, p_time );
SetCanDelayTeleport(false);
// update player only attacks
if (uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
{
setAttackTimer(RANGED_ATTACK, (update_diff >= ranged_att ? 0 : ranged_att - update_diff) );
}
time_t now = time (NULL);
UpdatePvPFlag(now);
UpdateContestedPvP(update_diff);
UpdateDuelFlag(now);
CheckDuelDistance(now);
UpdateAfkReport(now);
// Update items that have just a limited lifetime
if (now>m_Last_tick)
UpdateItemDuration(uint32(now- m_Last_tick));
if (now > m_Last_tick + IN_MILLISECONDS)
UpdateSoulboundTradeItems();
if (!m_timedquests.empty())
{
QuestSet::iterator iter = m_timedquests.begin();
while (iter != m_timedquests.end())
{
QuestStatusData& q_status = mQuestStatus[*iter];
if ( q_status.m_timer <= update_diff )
{
uint32 quest_id = *iter;
++iter; // current iter will be removed in FailQuest
FailQuest(quest_id);
}
else
{
q_status.m_timer -= update_diff;
if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
++iter;
}
}
}
if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
{
UpdateMeleeAttackingState();
Unit *pVictim = getVictim();
if (pVictim && !IsNonMeleeSpellCasted(false))
{
Player *vOwner = pVictim->GetCharmerOrOwnerPlayerOrPlayerItself();
if (vOwner && vOwner->IsPvP() && !IsInDuelWith(vOwner))
{
UpdatePvP(true);
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
}
}
}
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
{
if (roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
{
time_t time_inn = time(NULL)-GetTimeInnEnter();
if (time_inn >= 10) //freeze update
{
float bubble = 0.125f*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_INGAME);
//speed collect rest bonus (section/in hour)
SetRestBonus( float(GetRestBonus()+ time_inn*(GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble ));
UpdateInnerTime(time(NULL));
}
}
}
if (m_regenTimer)
{
if (update_diff >= m_regenTimer)
m_regenTimer = 0;
else
m_regenTimer -= update_diff;
}
if (m_weaponChangeTimer > 0)
{
if (update_diff >= m_weaponChangeTimer)
m_weaponChangeTimer = 0;
else
m_weaponChangeTimer -= update_diff;
}
if (m_zoneUpdateTimer > 0)
{
if (update_diff >= m_zoneUpdateTimer)
{
uint32 newzone, newarea;
GetZoneAndAreaId(newzone,newarea);
if ( m_zoneUpdateId != newzone )
UpdateZone(newzone,newarea); // also update area
else
{
// use area updates as well
// needed for free far all arenas for example
if ( m_areaUpdateId != newarea )
UpdateArea(newarea);
m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
}
}
else
m_zoneUpdateTimer -= update_diff;
}
if (m_timeSyncTimer > 0)
{
if (update_diff >= m_timeSyncTimer)
SendTimeSync();
else
m_timeSyncTimer -= update_diff;
}
if (isAlive())
{
// if no longer casting, set regen power as soon as it is up.
if (!IsUnderLastManaUseEffect() && !HasAuraType(SPELL_AURA_STOP_NATURAL_MANA_REGEN))
SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
if (!m_regenTimer)
RegenerateAll(IsUnderLastManaUseEffect() ? REGEN_TIME_PRECISE : REGEN_TIME_FULL);
}
if (!isAlive() && !HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) && getDeathState() != GHOULED )
SetHealth(0);
if (m_deathState == JUST_DIED)
KillPlayer();
if (m_nextSave > 0)
{
if (update_diff >= m_nextSave)
{
// m_nextSave reseted in SaveToDB call
SaveToDB();
DETAIL_LOG("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
}
else
m_nextSave -= update_diff;
}
//Handle Water/drowning
HandleDrowning(update_diff);
//Handle detect stealth players
if (m_DetectInvTimer > 0)
{
if (update_diff >= m_DetectInvTimer)
{
HandleStealthedUnitsDetection();
m_DetectInvTimer = 3000;
}
else
m_DetectInvTimer -= update_diff;
}
// Played time
if (now > m_Last_tick)
{
uint32 elapsed = uint32(now - m_Last_tick);
m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
m_Last_tick = now;
}
if (m_drunk)
{
m_drunkTimer += update_diff;
if (m_drunkTimer > 10*IN_MILLISECONDS)
HandleSobering();
}
if (HasPendingBind())
{
if (_pendingBindTimer <= p_time)
{
BindToInstance();
SetPendingBind(NULL, 0);
}
else
_pendingBindTimer -= p_time;
}
// not auto-free ghost from body in instances
if (m_deathTimer > 0 && !GetMap()->Instanceable() && getDeathState() != GHOULED)
{
if (p_time >= m_deathTimer)
{
m_deathTimer = 0;
BuildPlayerRepop();
RepopAtGraveyard();
}
else
m_deathTimer -= p_time;
}
UpdateEnchantTime(update_diff);
UpdateHomebindTime(update_diff);
// group update
SendUpdateToOutOfRangeGroupMembers();
Pet* pet = GetPet();
if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGuid() && (pet->GetObjectGuid() != GetCharmGuid())))
pet->Unsummon(PET_SAVE_REAGENTS, this);
if (IsHasDelayedTeleport())
TeleportTo(m_teleport_dest, m_teleport_options);
// Playerbot mod
if (!sWorld.getConfig(CONFIG_BOOL_PLAYERBOT_DISABLE))
{
if (m_playerbotAI)
m_playerbotAI->UpdateAI(p_time);
else if (m_playerbotMgr)
m_playerbotMgr->UpdateAI(p_time);
}
}
void Player::SetDeathState(DeathState s)
{
uint32 ressSpellId = 0;
bool cur = isAlive();
if (s == JUST_DIED && cur)
{
// drunken state is cleared on death
SetDrunkValue(0);
// lost combo points at any target (targeted combo points clear in Unit::SetDeathState)
ClearComboPoints();
clearResurrectRequestData();
// remove form before other mods to prevent incorrect stats calculation
RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
if (Pet* pet = GetPet())
{
if (pet->isControlled())
SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
//FIXME: is pet dismissed at dying or releasing spirit? if second, add SetDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
RemovePet(PET_SAVE_REAGENTS);
}
// save value before aura remove in Unit::SetDeathState
ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
// passive spell
if(!ressSpellId)
ressSpellId = GetResurrectionSpellId();
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
if (InstanceData* mapInstance = GetInstanceData())
mapInstance->OnPlayerDeath(this);
}
Unit::SetDeathState(s);
// restore resurrection spell id for player after aura remove
if (s == JUST_DIED && cur && ressSpellId)
SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
if (!cur && s == ALIVE)
{
_RemoveAllItemMods();
_ApplyAllItemMods();
}
if (isAlive() && !cur)
{
//clear aura case after resurrection by another way (spells will be applied before next death)
SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
// restore default warrior stance
if (getClass()== CLASS_WARRIOR)
CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
}
}
bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
{
// 0 1 2 3 4 5 6 7
// "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
// 8 9 10 11 12 13 14
// "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
// 15 16 17 18 19 20
// "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.equipmentCache, character_declinedname.genitive "
Field *fields = result->Fetch();
uint32 guid = fields[0].GetUInt32();
uint8 pRace = fields[2].GetUInt8();
uint8 pClass = fields[3].GetUInt8();
PlayerInfo const *info = sObjectMgr.GetPlayerInfo(pRace, pClass);
if(!info)
{
sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
return false;
}
*p_data << ObjectGuid(HIGHGUID_PLAYER, guid);
*p_data << fields[1].GetString(); // name
*p_data << uint8(pRace); // race
*p_data << uint8(pClass); // class
*p_data << uint8(fields[4].GetUInt8()); // gender
uint32 playerBytes = fields[5].GetUInt32();
*p_data << uint8(playerBytes); // skin
*p_data << uint8(playerBytes >> 8); // face
*p_data << uint8(playerBytes >> 16); // hair style
*p_data << uint8(playerBytes >> 24); // hair color
uint32 playerBytes2 = fields[6].GetUInt32();
*p_data << uint8(playerBytes2 & 0xFF); // facial hair
*p_data << uint8(fields[7].GetUInt8()); // level
*p_data << uint32(fields[8].GetUInt32()); // zone
*p_data << uint32(fields[9].GetUInt32()); // map
*p_data << fields[10].GetFloat(); // x
*p_data << fields[11].GetFloat(); // y
*p_data << fields[12].GetFloat(); // z
*p_data << uint32(fields[13].GetUInt32()); // guild id
uint32 char_flags = 0;
uint32 playerFlags = fields[14].GetUInt32();
uint32 atLoginFlags = fields[15].GetUInt32();
if (playerFlags & PLAYER_FLAGS_HIDE_HELM)
char_flags |= CHARACTER_FLAG_HIDE_HELM;
if (playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
if (playerFlags & PLAYER_FLAGS_GHOST)
char_flags |= CHARACTER_FLAG_GHOST;
if (atLoginFlags & AT_LOGIN_RENAME)
char_flags |= CHARACTER_FLAG_RENAME;
if (sWorld.getConfig(CONFIG_BOOL_DECLINED_NAMES_USED))
{
if(!fields[20].GetCppString().empty())
char_flags |= CHARACTER_FLAG_DECLINED;
}
else
char_flags |= CHARACTER_FLAG_DECLINED;
*p_data << uint32(char_flags); // character flags
// character customize/faction/race change flags
if(atLoginFlags & AT_LOGIN_CUSTOMIZE)
*p_data << uint32(CHAR_CUSTOMIZE_FLAG_CUSTOMIZE);
else if(atLoginFlags & AT_LOGIN_CHANGE_FACTION)
*p_data << uint32(CHAR_CUSTOMIZE_FLAG_FACTION);
else if(atLoginFlags & AT_LOGIN_CHANGE_RACE)
*p_data << uint32(CHAR_CUSTOMIZE_FLAG_RACE);
else
*p_data << uint32(CHAR_CUSTOMIZE_FLAG_NONE);
// First login
*p_data << uint8(atLoginFlags & AT_LOGIN_FIRST ? 1 : 0);
// Pets info
{
uint32 petDisplayId = 0;
uint32 petLevel = 0;
uint32 petFamily = 0;
// show pet at selection character in character list only for non-ghost character
if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
{
uint32 entry = fields[16].GetUInt32();
CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
if (cInfo)
{
petDisplayId = fields[17].GetUInt32();
petLevel = fields[18].GetUInt32();
petFamily = cInfo->family;
}
}
*p_data << uint32(petDisplayId);
*p_data << uint32(petLevel);
*p_data << uint32(petFamily);
}
Tokens data(fields[19].GetCppString(), ' ');
for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
{
uint32 visualbase = slot * 2;
uint32 item_id = atoi(data[visualbase]);
const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
if(!proto)
{
*p_data << uint32(0);
*p_data << uint8(0);
*p_data << uint32(0);
continue;
}
SpellItemEnchantmentEntry const *enchant = NULL;
uint32 enchants = atoi(data[visualbase + 1]);
for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
{
// values stored in 2 uint16
uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
if(!enchantId)
continue;
if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
break;
}
*p_data << uint32(proto->DisplayInfoID);
*p_data << uint8(proto->InventoryType);
*p_data << uint32(enchant ? enchant->aura_id : 0);
}
*p_data << uint32(0); // bag 1 display id
*p_data << uint8(0); // bag 1 inventory type
*p_data << uint32(0); // enchant?
*p_data << uint32(0); // bag 2 display id
*p_data << uint8(0); // bag 2 inventory type
*p_data << uint32(0); // enchant?
*p_data << uint32(0); // bag 3 display id
*p_data << uint8(0); // bag 3 inventory type
*p_data << uint32(0); // enchant?
*p_data << uint32(0); // bag 4 display id
*p_data << uint8(0); // bag 4 inventory type
*p_data << uint32(0); // enchant?
return true;
}
void Player::ToggleAFK()
{
ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
// afk player not allowed in battleground
if (isAFK() && InBattleGround() && !InArena())
LeaveBattleground();
}
void Player::ToggleDND()
{
ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
}
uint8 Player::chatTag() const
{
// it's bitmask
// 0x1 - afk
// 0x2 - dnd
// 0x4 - gm
// 0x8 - ??
if (isGMChat()) // Always show GM icons if activated
return 4;
if (isAFK())
return 1;
if (isDND())
return 3;
return 0;
}
bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
{
if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
{
sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
return false;
}
if (GetMapId() != mapid)
{
if (!(options & TELE_TO_CHECKED))
{
if (!CheckTransferPossibility(mapid))
{
if (GetTransport())
TeleportToHomebind();
DEBUG_LOG("Player::TeleportTo %s is NOT teleported to map %u (requirements check failed)", GetName(), mapid);
return false; // normal client can't teleport to this map...
}
else
options |= TELE_TO_CHECKED;
}
DEBUG_LOG("Player::TeleportTo %s is being far teleported to map %u", GetName(), mapid);
}
else
{
DEBUG_LOG("Player::TeleportTo %s is being near teleported to map %u", GetName(), mapid);
}
// preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
Pet* pet = GetPet();
// Playerbot mod: if this user has bots, tell them to stop following master
// so they don't try to follow the master after the master teleports
if (GetPlayerbotMgr())
GetPlayerbotMgr()->Stay();
MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
if(!mEntry)
{
sLog.outError("TeleportTo: invalid map entry (id %d). possible disk or memory error.", mapid);
return false;
}
// don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
// don't let gm level > 1 either
if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
return false;
// client without expansion support
if (Group* grp = GetGroup())
grp->SetPlayerMap(GetObjectGuid(), mapid);
// if we were on a transport, leave
if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
{
m_transport->RemovePassenger(this);
SetTransport(NULL);
m_movementInfo.ClearTransportData();
}
if (GetVehicleKit())
GetVehicleKit()->RemoveAllPassengers();
ExitVehicle();
// The player was ported to another map and looses the duel immediately.
// We have to perform this check before the teleport, otherwise the
// ObjectAccessor won't find the flag.
if (duel && GetMapId() != mapid)
if (GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER)))
DuelComplete(DUEL_FLED);
// reset movement flags at teleport, because player will continue move with these flags after teleport
m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
DisableSpline();
if (GetMapId() == mapid && !m_transport)
{
//lets reset far teleport flag if it wasn't reset during chained teleports
SetSemaphoreTeleportFar(false);
//setup delayed teleport flag
//if teleport spell is casted in Unit::Update() func
//then we need to delay it until update process will be finished
if (SetDelayedTeleportFlagIfCan())
{
SetSemaphoreTeleportNear(true);
//lets save teleport destination for player
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
m_teleport_options = options;
return true;
}
if (!(options & TELE_TO_NOT_UNSUMMON_PET))
{
//same map, only remove pet if out of range for new position
if (pet && !pet->IsWithinDist3d(x, y, z, GetMap()->GetVisibilityDistance()))
UnsummonPetTemporaryIfAny();
}
if (!(options & TELE_TO_NOT_LEAVE_COMBAT))
CombatStop();
// this will be used instead of the current location in SaveToDB
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
SetFallInformation(0, z);
// code for finish transfer called in WorldSession::HandleMovementOpcodes()
// at client packet MSG_MOVE_TELEPORT_ACK
SetSemaphoreTeleportNear(true);
// near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
if(!GetSession()->PlayerLogout())
{
WorldPacket data;
BuildTeleportAckMsg(data, x, y, z, orientation);
GetSession()->SendPacket(&data);
}
}
else
{
// far teleport to another map
Map* oldmap = IsInWorld() ? GetMap() : NULL;
// check if we can enter before stopping combat / removing pet / totems / interrupting spells
// Check enter rights before map getting to avoid creating instance copy for player
// this check not dependent from map instance copy and same for all instance copies of selected map
if (!sMapMgr.CanPlayerEnter(mapid, this))
return false;
// If the map is not created, assume it is possible to enter it.
// It will be created in the WorldPortAck.
DungeonPersistentState* state = GetBoundInstanceSaveForSelfOrGroup(mapid);
Map *map = sMapMgr.FindMap(mapid, state ? state->GetInstanceId() : 0);
if (!map || map->CanEnter(this))
{
//lets reset near teleport flag if it wasn't reset during chained teleports
SetSemaphoreTeleportNear(false);
//setup delayed teleport flag
//if teleport spell is casted in Unit::Update() func
//then we need to delay it until update process will be finished
if (SetDelayedTeleportFlagIfCan())
{
SetSemaphoreTeleportFar(true);
//lets save teleport destination for player
m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
m_teleport_options = options;
return true;
}
SetSelectionGuid(ObjectGuid());
CombatStop();
ResetContestedPvP();
// remove player from battleground on far teleport (when changing maps)
if (BattleGround const* bg = GetBattleGround())
{
// Note: at battleground join battleground id set before teleport
// and we already will found "current" battleground
// just need check that this is targeted map or leave
if (bg->GetMapId() != mapid)
LeaveBattleground(false); // don't teleport to entry point
}
// remove pet on map change
UnsummonPetTemporaryIfAny();
// remove all dyn objects
RemoveAllDynObjects();
// stop spellcasting
// not attempt interrupt teleportation spell at caster teleport
if (!(options & TELE_TO_SPELL))
if (IsNonMeleeSpellCasted(true))
InterruptNonMeleeSpells(true);
//remove auras before removing from map...
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
if (!GetSession()->PlayerLogout())
{
// send transfer packet to display load screen
WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
data << uint32(mapid);
if (m_transport)
{
data << uint32(m_transport->GetEntry());
data << uint32(GetMapId());
}
GetSession()->SendPacket(&data);
}
// remove from old map now
if (oldmap)
oldmap->Remove(this, false);
// new final coordinates
float final_x = x;
float final_y = y;
float final_z = z;
float final_o = orientation;
if (m_transport)
{
final_x += m_movementInfo.GetTransportPos()->x;
final_y += m_movementInfo.GetTransportPos()->y;
final_z += m_movementInfo.GetTransportPos()->z;
final_o += m_movementInfo.GetTransportPos()->o;
}
m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
SetFallInformation(0, final_z);
// if the player is saved before worldport ack (at logout for example)
// this will be used instead of the current location in SaveToDB
// move packet sent by client always after far teleport
// code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
SetSemaphoreTeleportFar(true);
if (!GetSession()->PlayerLogout())
{
// transfer finished, inform client to start load
WorldPacket data(SMSG_NEW_WORLD, (20));
data << uint32(mapid);
if (m_transport)
{
data << float(m_movementInfo.GetTransportPos()->x);
data << float(m_movementInfo.GetTransportPos()->y);
data << float(m_movementInfo.GetTransportPos()->z);
data << float(m_movementInfo.GetTransportPos()->o);
}
else
{
data << float(final_x);
data << float(final_y);
data << float(final_z);
data << float(final_o);
}
GetSession()->SendPacket( &data );
SendSavedInstances();
}
}
else
return false;
}
return true;
}
bool Player::TeleportToBGEntryPoint()
{
RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
RemoveSpellsCausingAura(SPELL_AURA_FLY);
ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
return TeleportTo(m_bgData.joinPos);
}
void Player::ProcessDelayedOperations()
{
if (m_DelayedOperations == 0)
return;
if (m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
{
ResurrectPlayer(0.0f, false);
if (GetMaxHealth() > m_resurrectHealth)
SetHealth( m_resurrectHealth );
else
SetHealth( GetMaxHealth() );
if (GetMaxPower(POWER_MANA) > m_resurrectMana)
SetPower(POWER_MANA, m_resurrectMana );
else
SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
SetPower(POWER_RAGE, 0 );
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
SpawnCorpseBones();
}
if (m_DelayedOperations & DELAYED_SAVE_PLAYER)
{
SaveToDB();
}
if (m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
{
CastSpell(this, 26013, true); // Deserter
}
if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
{
if (m_bgData.mountSpell)
{
CastSpell(this, m_bgData.mountSpell, true);
m_bgData.mountSpell = 0;
}
}
if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
{
if (m_bgData.HasTaxiPath())
{
m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
m_bgData.ClearTaxiPath();
ContinueTaxiFlight();
}
}
//we have executed ALL delayed ops, so clear the flag
m_DelayedOperations = 0;
}
void Player::AddToWorld()
{
///- Do not add/remove the player from the object storage
///- It will crash when updating the ObjectAccessor
///- The player should only be added when logging in
Unit::AddToWorld();
for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
{
if (m_items[i])
m_items[i]->AddToWorld();
}
}
void Player::RemoveFromWorld()
{
for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
{
if (m_items[i])
m_items[i]->RemoveFromWorld();
}
///- Do not add/remove the player from the object storage
///- It will crash when updating the ObjectAccessor
///- The player should only be removed when logging out
if (IsInWorld())
GetCamera().ResetView();
Unit::RemoveFromWorld();
}
void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
{
float addRage;
float rageconversion = float((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911f;
if (attacker)
{
addRage = ((damage/rageconversion*7.5f + weaponSpeedHitFactor)/2.0f);
// talent who gave more rage on attack
addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
}
else
{
addRage = damage/rageconversion*2.5f;
// Berserker Rage effect
if (HasAura(18499, EFFECT_INDEX_0))
addRage *= 1.3f;
}
addRage *= sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_INCOME);
ModifyPower(POWER_RAGE, uint32(addRage*10));
}
void Player::RegenerateAll(uint32 diff)
{
// Not in combat or they have regeneration
if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() || m_baseHealthRegen )
{
RegenerateHealth(diff);
if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
{
Regenerate(POWER_RAGE, diff);
if (getClass() == CLASS_DEATH_KNIGHT)
Regenerate(POWER_RUNIC_POWER, diff);
}
}
Regenerate(POWER_ENERGY, diff);
Regenerate(POWER_MANA, diff);
if (getClass() == CLASS_DEATH_KNIGHT)
Regenerate(POWER_RUNE, diff);
m_regenTimer = IsUnderLastManaUseEffect() ? REGEN_TIME_PRECISE : REGEN_TIME_FULL;
}
// diff contains the time in milliseconds since last regen.
void Player::Regenerate(Powers power, uint32 diff)
{
uint32 curValue = GetPower(power);
uint32 maxValue = GetMaxPower(power);
float addvalue = 0.0f;
switch (power)
{
case POWER_MANA:
{
if (HasAuraType(SPELL_AURA_STOP_NATURAL_MANA_REGEN))
break;
float ManaIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_MANA);
if (IsUnderLastManaUseEffect())
{
// Mangos Updates Mana in intervals of 2s, which is correct
addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * (float)REGEN_TIME_FULL/IN_MILLISECONDS;
}
else
{
addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * (float)REGEN_TIME_FULL/IN_MILLISECONDS;
}
break;
}
case POWER_RAGE: // Regenerate rage
{
float RageDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_LOSS);
addvalue += 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
break;
}
case POWER_ENERGY: // Regenerate energy (rogue)
{
float EnergyRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_ENERGY);
addvalue += 20 * EnergyRate;
break;
}
case POWER_RUNIC_POWER:
{
float RunicPowerDecreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS);
addvalue += 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
break;
}
case POWER_RUNE:
{
if (getClass() != CLASS_DEATH_KNIGHT)
break;
for(uint32 rune = 0; rune < MAX_RUNES; ++rune)
{
if (uint16 cd = GetRuneCooldown(rune)) // if we have cooldown, reduce it...
{
uint32 cd_diff = diff;
AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
if ((*i)->GetModifier()->m_miscvalue == int32(power) && (*i)->GetMiscBValue()==GetCurrentRune(rune))
cd_diff = cd_diff * ((*i)->GetModifier()->m_amount + 100) / 100;
SetRuneCooldown(rune, (cd < cd_diff) ? 0 : cd - cd_diff);
// check if we don't have cooldown, need convert and that our rune wasn't already converted
if (cd < cd_diff && m_runes->IsRuneNeedsConvert(rune) && GetBaseRune(rune) == GetCurrentRune(rune))
{
// currently all delayed rune converts happen with rune death
// ConvertedBy was initialized at proc
ConvertRune(rune, RUNE_DEATH);
SetNeedConvertRune(rune, false);
}
}
else if (m_runes->IsRuneNeedsConvert(rune) && GetBaseRune(rune) == GetCurrentRune(rune))
{
// currently all delayed rune converts happen with rune death
// ConvertedBy was initialized at proc
ConvertRune(rune, RUNE_DEATH);
SetNeedConvertRune(rune, false);
}
}
break;
}
case POWER_FOCUS:
case POWER_HAPPINESS:
case POWER_HEALTH:
default:
break;
}
// Mana regen calculated in Player::UpdateManaRegen()
// Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
if (power != POWER_MANA)
{
AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
if ((*i)->GetModifier()->m_miscvalue == int32(power))
addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
}
// addvalue computed on a 2sec basis. => update to diff time
uint32 _addvalue = ceil(fabs(addvalue * float(diff) / (float)REGEN_TIME_FULL));
if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
{
curValue += _addvalue;
if (curValue > maxValue)
curValue = maxValue;
}
else
{
if (curValue <= _addvalue)
curValue = 0;
else
curValue -= _addvalue;
}
SetPower(power, curValue);
}
void Player::RegenerateHealth(uint32 diff)
{
uint32 curValue = GetHealth();
uint32 maxValue = GetMaxHealth();
if (curValue >= maxValue) return;
float HealthIncreaseRate = sWorld.getConfig(CONFIG_FLOAT_RATE_HEALTH);
float addvalue = 0.0f;
// polymorphed case
if ( IsPolymorphed() )
addvalue = (float)GetMaxHealth()/3;
// normal regen case (maybe partly in combat case)
else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
{
addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
if (!isInCombat())
{
AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
}
else if (HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
if(!IsStandState())
addvalue *= 1.5;
}
// always regeneration bonus (including combat)
addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
addvalue += m_baseHealthRegen / 2.5f; //From ITEM_MOD_HEALTH_REGEN. It is correct tick amount?
if (addvalue < 0)
addvalue = 0;
addvalue *= (float)diff / REGEN_TIME_FULL;
ModifyHealth(int32(addvalue));
}
Creature* Player::GetNPCIfCanInteractWith(ObjectGuid guid, uint32 npcflagmask)
{
// some basic checks
if (!guid || !IsInWorld() || IsTaxiFlying())
return NULL;
// not in interactive state
if (hasUnitState(UNIT_STAT_CAN_NOT_REACT_OR_LOST_CONTROL) && !hasUnitState(UNIT_STAT_ON_VEHICLE))
return NULL;
// exist (we need look pets also for some interaction (quest/etc)
Creature *unit = GetMap()->GetAnyTypeCreature(guid);
if (!unit)
return NULL;
// appropriate npc type
if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
return NULL;
if (npcflagmask == UNIT_NPC_FLAG_STABLEMASTER)
{
if (getClass() != CLASS_HUNTER)
return NULL;
}
// if a dead unit should be able to talk - the creature must be alive and have special flags
if (!unit->isAlive())
return NULL;
if (isAlive() && unit->isInvisibleForAlive())
return NULL;
// not allow interaction under control, but allow with own pets
if (unit->GetCharmerGuid())
return NULL;
// not enemy
if (unit->IsHostileTo(this))
return NULL;
// not too far
if (!unit->IsWithinDistInMap(this, INTERACTION_DISTANCE))
return NULL;
return unit;
}
GameObject* Player::GetGameObjectIfCanInteractWith(ObjectGuid guid, uint32 gameobject_type) const
{
// some basic checks
if (!guid || !IsInWorld() || IsTaxiFlying())
return NULL;
// not in interactive state
if (hasUnitState(UNIT_STAT_CAN_NOT_REACT_OR_LOST_CONTROL) && !hasUnitState(UNIT_STAT_ON_VEHICLE))
return NULL;
if (GameObject *go = GetMap()->GetGameObject(guid))
{
if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE)
{
float maxdist;
switch(go->GetGoType())
{
// TODO: find out how the client calculates the maximal usage distance to spellless working
// gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
case GAMEOBJECT_TYPE_GUILD_BANK:
case GAMEOBJECT_TYPE_MAILBOX:
maxdist = 10.0f;
break;
case GAMEOBJECT_TYPE_FISHINGHOLE:
maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
break;
default:
maxdist = INTERACTION_DISTANCE;
break;
}
if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned())
return go;
sLog.outError("GetGameObjectIfCanInteractWith: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal %f is allowed)",
go->GetGOInfo()->name, go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this), maxdist);
}
}
return NULL;
}
bool Player::IsUnderWater() const
{
return GetTerrain()->IsUnderWater(GetPositionX(), GetPositionY(), GetPositionZ()+2);
}
void Player::SetInWater(bool apply)
{
if (m_isInWater==apply)
return;
//define player in water by opcodes
//move player's guid into HateOfflineList of those mobs
//which can't swim and move guid back into ThreatList when
//on surface.
//TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
m_isInWater = apply;
// remove auras that need water/land
RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
getHostileRefManager().updateThreatTables();
}
struct SetGameMasterOnHelper
{
explicit SetGameMasterOnHelper() {}
void operator()(Unit* unit) const
{
unit->setFaction(35);
unit->getHostileRefManager().setOnlineOfflineState(false);
}
};
struct SetGameMasterOffHelper
{
explicit SetGameMasterOffHelper(uint32 _faction) : faction(_faction) {}
void operator()(Unit* unit) const
{
unit->setFaction(faction);
unit->getHostileRefManager().setOnlineOfflineState(true);
}
uint32 faction;
};
void Player::SetGameMaster(bool on)
{
if (on)
{
m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
setFaction(35);
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
CallForAllControlledUnits(SetGameMasterOnHelper(), CONTROLLED_PET|CONTROLLED_TOTEMS|CONTROLLED_GUARDIANS|CONTROLLED_CHARM);
SetFFAPvP(false);
ResetContestedPvP();
getHostileRefManager().setOnlineOfflineState(false);
CombatStopWithPets();
SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
}
else
{
m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
setFactionForRace(getRace());
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
// restore phase
AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()), CONTROLLED_PET|CONTROLLED_TOTEMS|CONTROLLED_GUARDIANS|CONTROLLED_CHARM);
// restore FFA PvP Server state
if (sWorld.IsFFAPvPRealm())
SetFFAPvP(true);
// restore FFA PvP area state, remove not allowed for GM mounts
UpdateArea(m_areaUpdateId);
getHostileRefManager().setOnlineOfflineState(true);
}
m_camera.UpdateVisibilityForOwner();
UpdateObjectVisibility();
UpdateForQuestWorldObjects();
}
void Player::SetGMVisible(bool on)
{
if (on)
{
m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
// Reapply stealth/invisibility if active or show if not any
if (HasAuraType(SPELL_AURA_MOD_STEALTH))
SetVisibility(VISIBILITY_GROUP_STEALTH);
else if (HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
else
SetVisibility(VISIBILITY_ON);
}
else
{
m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
SetAcceptWhispers(false);
SetGameMaster(true);
SetVisibility(VISIBILITY_OFF);
}
}
bool Player::IsGroupVisibleFor(Player* p) const
{
switch(sWorld.getConfig(CONFIG_UINT32_GROUP_VISIBILITY))
{
default: return IsInSameGroupWith(p);
case 1: return IsInSameRaidWith(p);
case 2: return GetTeam()==p->GetTeam();
}
}
bool Player::IsInSameGroupWith(Player const* p) const
{
return (p==this || (GetGroup() != NULL &&
GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
}
///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
/// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
void Player::UninviteFromGroup()
{
Group* group = GetGroupInvite();
if(!group)
return;
group->RemoveInvite(this);
if (group->GetMembersCount() <= 1) // group has just 1 member => disband
{
if (group->IsCreated())
{
group->Disband(true);
sObjectMgr.RemoveGroup(group);
}
else
group->RemoveAllInvites();
delete group;
}
}
void Player::RemoveFromGroup(Group* group, ObjectGuid guid)
{
if (group)
{
// remove all auras affecting only group members
if (Player *pLeaver = sObjectMgr.GetPlayer(guid))
{
for(GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
if (Player *pGroupGuy = itr->getSource())
{
// dont remove my auras from myself
if (pGroupGuy->GetObjectGuid() == guid)
continue;
// remove all buffs cast by me from group members before leaving
pGroupGuy->RemoveAllGroupBuffsFromCaster(guid);
// remove from me all buffs cast by group members
pLeaver->RemoveAllGroupBuffsFromCaster(pGroupGuy->GetObjectGuid());
}
}
}
// remove member from group
if (group->RemoveMember(guid, 0) <= 1)
{
// group->Disband(); already disbanded in RemoveMember
sObjectMgr.RemoveGroup(group);
delete group;
// removemember sets the player's group pointer to NULL
}
}
}
void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool ReferAFriend)
{
WorldPacket data(SMSG_LOG_XPGAIN, 21);
data << (victim ? victim->GetObjectGuid() : ObjectGuid());// guid
data << uint32(GivenXP+BonusXP); // total experience
data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
if (victim)
{
data << uint32(GivenXP); // experience without rested bonus
data << float(1); // 1 - none 0 - 100% group bonus output
}
data << uint8(ReferAFriend ? 1 : 0); // Refer-A-Friend State
GetSession()->SendPacket(&data);
}
void Player::GiveXP(uint32 xp, Unit* victim)
{
if ( xp < 1 )
return;
if(!isAlive())
return;
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_XP_USER_DISABLED))
return;
if (hasUnitState(UNIT_STAT_ON_VEHICLE))
return;
uint32 level = getLevel();
//prevent Northrend Level Leeching :P
if (level < 66 && GetMapId() == 571)
return;
// XP to money conversion processed in Player::RewardQuest
if (level >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
return;
if (victim)
{
// handle SPELL_AURA_MOD_KILL_XP_PCT auras
Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
}
else
{
// handle SPELL_AURA_MOD_QUEST_XP_PCT auras
Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
}
uint32 bonus_xp = 0;
bool ReferAFriend = false;
if (CheckRAFConditions())
{
// RAF bonus exp don't decrease rest exp
ReferAFriend = true;
bonus_xp = xp * (sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_XP) - 1);
}
else
// XP resting bonus for kill
bonus_xp = victim ? GetXPRestBonus(xp) : 0;
SendLogXPGain(xp,victim,bonus_xp,ReferAFriend);
uint32 curXP = GetUInt32Value(PLAYER_XP);
uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
uint32 newXP = curXP + xp + bonus_xp;
while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
{
newXP -= nextLvlXP;
if ( level < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
{
GiveLevel(level + 1);
level = getLevel();
// Refer-A-Friend
if (GetAccountLinkedState() == STATE_REFERRAL || GetAccountLinkedState() == STATE_DUAL)
{
if (level < sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL))
{
if (sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL) < 1.0f)
{
if ( level%uint8(1.0f/sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL)) == 0 )
ChangeGrantableLevels(1);
}
else
ChangeGrantableLevels(uint8(sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL)));
}
}
}
level = getLevel();
nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
}
SetUInt32Value(PLAYER_XP, newXP);
}
// Update player to next level
// Current player experience not update (must be update by caller)
void Player::GiveLevel(uint32 level)
{
if ( level == getLevel() )
return;
PlayerLevelInfo info;
sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
PlayerClassLevelInfo classInfo;
sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
// send levelup info to client
WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
data << uint32(level);
data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
// for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
data << uint32(0);
// end for
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
GetSession()->SendPacket(&data);
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level));
//update level, max level of skills
m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
_ApplyAllLevelScaleItemMods(false);
SetLevel(level);
UpdateSkillsForLevel ();
// save base values (bonuses already included in stored stats
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
SetCreateStat(Stats(i), info.stats[i]);
SetCreateHealth(classInfo.basehealth);
SetCreateMana(classInfo.basemana);
InitTalentForLevel();
InitTaxiNodesForLevel();
InitGlyphsForLevel();
UpdateAllStats();
// set current level health and mana/energy to maximum after applying all mods.
if (isAlive())
SetHealth(GetMaxHealth());
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
SetPower(POWER_FOCUS, 0);
SetPower(POWER_HAPPINESS, 0);
_ApplyAllLevelScaleItemMods(true);
// update level to hunter/summon pet
if (Pet* pet = GetPet())
pet->SynchronizeLevelWithOwner();
if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask()))
MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
GetLFGState()->Update();
}
void Player::UpdateFreeTalentPoints(bool resetIfNeed)
{
uint32 level = getLevel();
// talents base at level diff ( talents = level - 9 but some can be used already)
if (level < 10)
{
// Remove all talent points
if (m_usedTalentCount > 0) // Free any used talents
{
if (resetIfNeed)
resetTalents(true);
SetFreeTalentPoints(0);
}
}
else
{
if (m_specsCount == 0)
{
m_specsCount = 1;
m_activeSpec = 0;
}
uint32 talentPointsForLevel = CalculateTalentsPoints();
// if used more that have then reset
if (m_usedTalentCount > talentPointsForLevel)
{
if (resetIfNeed && GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
resetTalents(true);
else
SetFreeTalentPoints(0);
}
// else update amount of free points
else
SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
}
ResetTalentsCount();
}
void Player::InitTalentForLevel()
{
UpdateFreeTalentPoints();
if (!GetSession()->PlayerLoading())
SendTalentsInfoData(false); // update at client
}
void Player::InitStatsForLevel(bool reapplyMods)
{
if (reapplyMods) //reapply stats values only on .reset stats (level) command
_RemoveAllStatBonuses();
PlayerClassLevelInfo classInfo;
sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
PlayerLevelInfo info;
sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) );
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel()));
// reset before any aura state sources (health set/aura apply)
SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
UpdateSkillsForLevel ();
// set default cast time multiplier
SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
// save base values (bonuses already included in stored stats
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
SetCreateStat(Stats(i), info.stats[i]);
for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
SetStat(Stats(i), info.stats[i]);
SetCreateHealth(classInfo.basehealth);
//set create powers
SetCreateMana(classInfo.basemana);
SetArmor(int32(m_createStats[STAT_AGILITY]*2));
InitStatBuffMods();
//reset rating fields values
for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
SetUInt32Value(index, 0);
SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
{
SetInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
}
//reset attack power, damage and attack speed fields
SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
// Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
// Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
// Dodge percentage
SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
// set armor (resistance 0) to original value (create_agility*2)
SetArmor(int32(m_createStats[STAT_AGILITY]*2));
SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
// set other resistance to original value (0)
for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
{
SetResistance(SpellSchools(i), 0);
SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
}
SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
{
SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
}
// Reset no reagent cost field
for(int i = 0; i < 3; ++i)
SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
// Init data for form but skip reapply item mods for form
InitDataForForm(reapplyMods);
// save new stats
for (int i = POWER_MANA; i < MAX_POWERS; ++i)
SetMaxPower(Powers(i), GetCreatePowers(Powers(i)));
SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
// cleanup mounted state (it will set correctly at aura loading if player saved at mount.
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
// cleanup unit flags (will be re-applied if need at aura load).
RemoveFlag( UNIT_FIELD_FLAGS,
UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_PASSIVE | UNIT_FLAG_LOOTING |
UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
// cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
// restore if need some important flags
SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
if (reapplyMods) //reapply stats values only on .reset stats (level) command
_ApplyAllStatBonuses();
// set current level health and mana/energy to maximum after applying all mods.
SetHealth(GetMaxHealth());
SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
SetPower(POWER_FOCUS, 0);
SetPower(POWER_HAPPINESS, 0);
SetPower(POWER_RUNIC_POWER, 0);
// update level to hunter/summon pet
if (Pet* pet = GetPet())
pet->SynchronizeLevelWithOwner();
}
void Player::SendInitialSpells()
{
time_t curTime = time(NULL);
time_t infTime = curTime + infinityCooldownDelayCheck;
uint16 spellCount = 0;
WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
data << uint8(0);
size_t countPos = data.wpos();
data << uint16(spellCount); // spell count placeholder
for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED)
continue;
if(!itr->second.active || itr->second.disabled)
continue;
data << uint32(itr->first);
data << uint16(0); // it's not slot id
spellCount +=1;
}
data.put<uint16>(countPos,spellCount); // write real count value
uint16 spellCooldowns = m_spellCooldowns.size();
data << uint16(spellCooldowns);
for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
{
SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
if(!sEntry)
continue;
data << uint32(itr->first);
data << uint16(itr->second.itemid); // cast item id
data << uint16(sEntry->Category); // spell category
// send infinity cooldown in special format
if (itr->second.end >= infTime)
{
data << uint32(1); // cooldown
data << uint32(0x80000000); // category cooldown
continue;
}
time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILLISECONDS : 0;
if (sEntry->Category) // may be wrong, but anyway better than nothing...
{
data << uint32(0); // cooldown
data << uint32(cooldown); // category cooldown
}
else
{
data << uint32(cooldown); // cooldown
data << uint32(0); // category cooldown
}
}
GetSession()->SendPacket(&data);
DETAIL_LOG( "CHARACTER: Sent Initial Spells" );
}
void Player::SendCalendarResult(CalendarResponseResult result, std::string str)
{
WorldPacket data(SMSG_CALENDAR_COMMAND_RESULT, 200);
data << uint32(0); // unused
data << uint8(0); // std::string, currently unused
data << str;
data << uint32(result);
GetSession()->SendPacket(&data);
}
void Player::RemoveMail(uint32 id)
{
for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
{
if ((*itr)->messageID == id)
{
//do not delete item, because Player::removeMail() is called when returning mail to sender.
m_mail.erase(itr);
return;
}
}
}
void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
{
WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
data << (uint32) mailId;
data << (uint32) mailAction;
data << (uint32) mailError;
if ( mailError == MAIL_ERR_EQUIP_ERROR )
data << (uint32) equipError;
else if ( mailAction == MAIL_ITEM_TAKEN )
{
data << (uint32) item_guid; // item guid low?
data << (uint32) item_count; // item count?
}
GetSession()->SendPacket(&data);
}
void Player::SendNewMail()
{
// deliver undelivered mail
WorldPacket data(SMSG_RECEIVED_MAIL, 4);
data << (uint32) 0;
GetSession()->SendPacket(&data);
}
void Player::UpdateNextMailTimeAndUnreads()
{
// calculate next delivery time (min. from non-delivered mails
// and recalculate unReadMail
time_t cTime = time(NULL);
m_nextMailDelivereTime = 0;
unReadMails = 0;
for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
{
if((*itr)->deliver_time > cTime)
{
if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
m_nextMailDelivereTime = (*itr)->deliver_time;
}
else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
++unReadMails;
}
}
void Player::AddNewMailDeliverTime(time_t deliver_time)
{
if (deliver_time <= time(NULL)) // ready now
{
++unReadMails;
SendNewMail();
}
else // not ready and no have ready mails
{
if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
m_nextMailDelivereTime = deliver_time;
}
}
bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
if (!spellInfo)
{
// do character spell book cleanup (all characters)
if(!IsInWorld() && !learning) // spell load case
{
sLog.outError("Player::addSpell: nonexistent in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
}
else
sLog.outError("Player::addSpell: nonexistent in SpellStore spell #%u request.",spell_id);
return false;
}
if(!SpellMgr::IsSpellValid(spellInfo,this,false))
{
// do character spell book cleanup (all characters)
if(!IsInWorld() && !learning) // spell load case
{
sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
}
else
sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
return false;
}
PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
bool dependent_set = false;
bool disabled_case = false;
bool superceded_old = false;
PlayerSpellMap::iterator itr = m_spells.find(spell_id);
if (itr != m_spells.end())
{
uint32 next_active_spell_id = 0;
// fix activate state for non-stackable low rank (and find next spell for !active case)
if (sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo))
{
SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
{
if (HasSpell(next_itr->second))
{
// high rank already known so this must !active
active = false;
next_active_spell_id = next_itr->second;
break;
}
}
}
// not do anything if already known in expected state
if (itr->second.state != PLAYERSPELL_REMOVED && itr->second.active == active &&
itr->second.dependent == dependent && itr->second.disabled == disabled)
{
if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
itr->second.state = PLAYERSPELL_UNCHANGED;
return false;
}
// dependent spell known as not dependent, overwrite state
if (itr->second.state != PLAYERSPELL_REMOVED && !itr->second.dependent && dependent)
{
itr->second.dependent = dependent;
if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
dependent_set = true;
}
// update active state for known spell
if (itr->second.active != active && itr->second.state != PLAYERSPELL_REMOVED && !itr->second.disabled)
{
itr->second.active = active;
if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
itr->second.state = PLAYERSPELL_UNCHANGED;
else if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
if (active)
{
if (IsNeedCastPassiveLikeSpellAtLearn(spellInfo))
CastSpell (this, spell_id, true);
}
else if (IsInWorld())
{
if (next_active_spell_id)
{
// update spell ranks in spellbook and action bar
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(spell_id);
data << uint32(next_active_spell_id);
GetSession()->SendPacket( &data );
}
else
{
WorldPacket data(SMSG_REMOVED_SPELL, 4);
data << uint32(spell_id);
GetSession()->SendPacket(&data);
}
}
return active; // learn (show in spell book if active now)
}
if (itr->second.disabled != disabled && itr->second.state != PLAYERSPELL_REMOVED)
{
if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
itr->second.disabled = disabled;
if (disabled)
return false;
disabled_case = true;
}
else switch(itr->second.state)
{
case PLAYERSPELL_UNCHANGED: // known saved spell
return false;
case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
{
m_spells.erase(itr);
state = PLAYERSPELL_CHANGED;
break; // need re-add
}
default: // known not saved yet spell (new or modified)
{
// can be in case spell loading but learned at some previous spell loading
if(!IsInWorld() && !learning && !dependent_set)
itr->second.state = PLAYERSPELL_UNCHANGED;
return false;
}
}
}
TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id);
if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
{
// talent: unlearn all other talent ranks (high and low)
if (talentPos)
{
if (TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
{
for(int i=0; i < MAX_TALENT_RANK; ++i)
{
// skip learning spell and no rank spell case
uint32 rankSpellId = talentInfo->RankID[i];
if(!rankSpellId || rankSpellId == spell_id)
continue;
removeSpell(rankSpellId, false, false);
}
}
}
// non talent spell: learn low ranks (recursive call)
else if (uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id))
{
if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
addSpell(prev_spell, active, true, true, disabled);
else // at normal learning
learnSpell(prev_spell, true);
}
PlayerSpell newspell;
newspell.state = state;
newspell.active = active;
newspell.dependent = dependent;
newspell.disabled = disabled;
// replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
if (newspell.active && !newspell.disabled && sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo))
{
for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
{
if (itr2->second.state == PLAYERSPELL_REMOVED) continue;
SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
if(!i_spellInfo) continue;
if ( sSpellMgr.IsRankSpellDueToSpell(spellInfo, itr2->first) )
{
if (itr2->second.active)
{
if (sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first))
{
if (IsInWorld()) // not send spell (re-/over-)learn packets at loading
{
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(itr2->first);
data << uint32(spell_id);
GetSession()->SendPacket( &data );
}
// mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
itr2->second.active = false;
if (itr2->second.state != PLAYERSPELL_NEW)
itr2->second.state = PLAYERSPELL_CHANGED;
superceded_old = true; // new spell replace old in action bars and spell book.
}
else if (sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id))
{
if (IsInWorld()) // not send spell (re-/over-)learn packets at loading
{
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(spell_id);
data << uint32(itr2->first);
GetSession()->SendPacket( &data );
}
// mark new spell as disable (not learned yet for client and will not learned)
newspell.active = false;
if (newspell.state != PLAYERSPELL_NEW)
newspell.state = PLAYERSPELL_CHANGED;
}
}
}
}
}
m_spells[spell_id] = newspell;
// return false if spell disabled
if (newspell.disabled)
return false;
}
if (talentPos)
{
// update talent map
PlayerTalentMap::iterator iter = m_talents[m_activeSpec].find(talentPos->talent_id);
if (iter != m_talents[m_activeSpec].end())
{
// check if ranks different or removed
if ((*iter).second.state == PLAYERSPELL_REMOVED || talentPos->rank != (*iter).second.currentRank)
{
(*iter).second.currentRank = talentPos->rank;
if ((*iter).second.state != PLAYERSPELL_NEW)
(*iter).second.state = PLAYERSPELL_CHANGED;
}
}
else
{
PlayerTalent talent;
talent.currentRank = talentPos->rank;
talent.talentEntry = sTalentStore.LookupEntry(talentPos->talent_id);
talent.state = IsInWorld() ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
m_talents[m_activeSpec][talentPos->talent_id] = talent;
}
// update used talent points count
m_usedTalentCount += GetTalentSpellCost(talentPos);
UpdateFreeTalentPoints(false);
}
// update free primary prof.points (if any, can be none in case GM .learn prof. learning)
if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
{
if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
SetFreePrimaryProfessions(freeProfs-1);
}
// cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
// note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
if (talentPos && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
{
// ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
CastSpell(this, spell_id, true);
}
// also cast passive (and passive like) spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
else if (IsNeedCastPassiveLikeSpellAtLearn(spellInfo))
{
CastSpell(this, spell_id, true);
}
else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
{
CastSpell(this, spell_id, true);
return false;
}
// add dependent skills
uint16 maxskill = GetMaxSkillValueForLevel();
SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
if (spellLearnSkill)
{
uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
if (skill_value < spellLearnSkill->value)
skill_value = spellLearnSkill->value;
uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
if (skill_max_value < new_skill_max_value)
skill_max_value = new_skill_max_value;
SetSkill(spellLearnSkill->skill, skill_value, skill_max_value, spellLearnSkill->step);
}
else
{
// not ranked skills
for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
{
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
if (!pSkill)
continue;
if (HasSkill(pSkill->id))
continue;
if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
// lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
{
switch(GetSkillRangeType(pSkill, _spell_idx->second->racemask != 0))
{
case SKILL_RANGE_LANGUAGE:
SetSkill(pSkill->id, 300, 300 );
break;
case SKILL_RANGE_LEVEL:
SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
break;
case SKILL_RANGE_MONO:
SetSkill(pSkill->id, 1, 1 );
break;
default:
break;
}
}
}
}
// learn dependent spells
SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
{
if (!itr2->second.autoLearned)
{
if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
addSpell(itr2->second.spell,itr2->second.active,true,true,false);
else // at normal learning
learnSpell(itr2->second.spell, true);
}
}
if (!GetSession()->PlayerLoading())
{
// not ranked skills
for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
{
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
}
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
}
// return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
return active && !disabled && !superceded_old;
}
bool Player::IsNeedCastPassiveLikeSpellAtLearn(SpellEntry const* spellInfo) const
{
ShapeshiftForm form = GetShapeshiftForm();
if (IsNeedCastSpellAtFormApply(spellInfo, form)) // SPELL_ATTR_PASSIVE | SPELL_ATTR_HIDDEN_CLIENTSIDE spells
return true; // all stance req. cases, not have auarastate cases
if (!(spellInfo->Attributes & SPELL_ATTR_PASSIVE))
return false;
// note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
// talent dependent passives activated at form apply have proper stance data
bool need_cast = (!spellInfo->Stances || (!form && (spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT)));
// Check CasterAuraStates
return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
}
void Player::learnSpell(uint32 spell_id, bool dependent)
{
PlayerSpellMap::iterator itr = m_spells.find(spell_id);
bool disabled = (itr != m_spells.end()) ? itr->second.disabled : false;
bool active = disabled ? itr->second.active : true;
bool learning = addSpell(spell_id, active, true, dependent, false);
// prevent duplicated entires in spell book, also not send if not in world (loading)
if (learning && IsInWorld())
{
WorldPacket data(SMSG_LEARNED_SPELL, 6);
data << uint32(spell_id);
data << uint16(0); // 3.3.3 unk
GetSession()->SendPacket(&data);
}
// learn all disabled higher ranks (recursive)
if (disabled)
{
SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
{
PlayerSpellMap::iterator iter = m_spells.find(i->second);
if (iter != m_spells.end() && iter->second.disabled)
learnSpell(i->second, false);
}
}
}
void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate)
{
PlayerSpellMap::iterator itr = m_spells.find(spell_id);
if (itr == m_spells.end())
return;
if (itr->second.state == PLAYERSPELL_REMOVED || (disabled && itr->second.disabled))
return;
// unlearn non talent higher ranks (recursive)
SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
if (HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
removeSpell(itr2->second, disabled, false);
// re-search, it can be corrupted in prev loop
itr = m_spells.find(spell_id);
if (itr == m_spells.end() || itr->second.state == PLAYERSPELL_REMOVED)
return; // already unleared
bool cur_active = itr->second.active;
bool cur_dependent = itr->second.dependent;
if (disabled)
{
itr->second.disabled = disabled;
if (itr->second.state != PLAYERSPELL_NEW)
itr->second.state = PLAYERSPELL_CHANGED;
}
else
{
if (itr->second.state == PLAYERSPELL_NEW)
m_spells.erase(itr);
else
itr->second.state = PLAYERSPELL_REMOVED;
}
RemoveAurasDueToSpell(spell_id);
// remove pet auras
for(int i = 0; i < MAX_EFFECT_INDEX; ++i)
if (PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, SpellEffectIndex(i)))
RemovePetAura(petSpell);
TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id);
if (talentPos)
{
// update talent map
PlayerTalentMap::iterator iter = m_talents[m_activeSpec].find(talentPos->talent_id);
if (iter != m_talents[m_activeSpec].end())
{
if ((*iter).second.state != PLAYERSPELL_NEW)
(*iter).second.state = PLAYERSPELL_REMOVED;
else
m_talents[m_activeSpec].erase(iter);
}
else
sLog.outError("removeSpell: Player (GUID: %u) has talent spell (id: %u) but doesn't have talent",GetGUIDLow(), spell_id );
// free talent points
uint32 talentCosts = GetTalentSpellCost(talentPos);
if (talentCosts < m_usedTalentCount)
m_usedTalentCount -= talentCosts;
else
m_usedTalentCount = 0;
UpdateFreeTalentPoints(false);
}
// update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
{
uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
uint32 maxProfs = GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_MAX_PRIMARY_COUNT)) ? sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL) : 10;
if (freeProfs <= maxProfs)
SetFreePrimaryProfessions(freeProfs);
}
// remove dependent skill
SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
if (spellLearnSkill)
{
uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id);
if(!prev_spell) // first rank, remove skill
SetSkill(spellLearnSkill->skill, 0, 0);
else
{
// search prev. skill setting by spell ranks chain
SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell);
while(!prevSkill && prev_spell)
{
prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell);
prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell));
}
if (!prevSkill) // not found prev skill setting, remove skill
SetSkill(spellLearnSkill->skill, 0, 0);
else // set to prev. skill setting values
{
uint32 skill_value = GetPureSkillValue(prevSkill->skill);
uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
if (skill_value > prevSkill->value)
skill_value = prevSkill->value;
uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
if (skill_max_value > new_skill_max_value)
skill_max_value = new_skill_max_value;
SetSkill(prevSkill->skill, skill_value, skill_max_value, prevSkill->step);
}
}
}
else
{
// not ranked skills
SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
if (!pSkill)
continue;
if ((_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
pSkill->categoryId != SKILL_CATEGORY_CLASS) ||// not unlearn class skills (spellbook/talent pages)
// lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0))
{
// not reset skills for professions and racial abilities
if ((pSkill->categoryId == SKILL_CATEGORY_SECONDARY || pSkill->categoryId == SKILL_CATEGORY_PROFESSION) &&
(IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask != 0))
continue;
SetSkill(pSkill->id, 0, 0);
}
}
}
// remove dependent spells
SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
removeSpell(itr2->second.spell, disabled);
// activate lesser rank in spellbook/action bar, and cast it if need
bool prev_activate = false;
if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id))
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
// if talent then lesser rank also talent and need learn
if (talentPos)
{
if (learn_low_rank)
learnSpell(prev_id, false);
}
// if ranked non-stackable spell: need activate lesser rank and update dependence state
else if (cur_active && sSpellMgr.IsRankedSpellNonStackableInSpellBook(spellInfo))
{
// need manually update dependence state (learn spell ignore like attempts)
PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
if (prev_itr != m_spells.end())
{
if (prev_itr->second.dependent != cur_dependent)
{
prev_itr->second.dependent = cur_dependent;
if (prev_itr->second.state != PLAYERSPELL_NEW)
prev_itr->second.state = PLAYERSPELL_CHANGED;
}
// now re-learn if need re-activate
if (cur_active && !prev_itr->second.active && learn_low_rank)
{
if (addSpell(prev_id, true, false, prev_itr->second.dependent, prev_itr->second.disabled))
{
// downgrade spell ranks in spellbook and action bar
WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
data << uint32(spell_id);
data << uint32(prev_id);
GetSession()->SendPacket( &data );
prev_activate = true;
}
}
}
}
}
// for Titan's Grip and shaman Dual-wield
if (CanDualWield() || CanTitanGrip())
{
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
if (CanDualWield() && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_DUAL_WIELD))
SetCanDualWield(false);
if (CanTitanGrip() && IsSpellHaveEffect(spellInfo, SPELL_EFFECT_TITAN_GRIP))
{
SetCanTitanGrip(false);
// Remove Titan's Grip damage penalty now
RemoveAurasDueToSpell(49152);
}
}
// for talents and normal spell unlearn that allow offhand use for some weapons
if (sWorld.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET))
AutoUnequipOffhandIfNeed();
// remove from spell book if not replaced by lesser rank
if (!prev_activate && sendUpdate)
{
WorldPacket data(SMSG_REMOVED_SPELL, 4);
data << uint32(spell_id);
GetSession()->SendPacket(&data);
}
}
void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
{
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
m_spellCooldowns.erase(spell_id);
if (update)
SendClearCooldown(spell_id, this);
}
void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
{
if (m_spellCooldowns.empty())
return;
SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
if (ct == sSpellCategoryStore.end())
return;
const SpellCategorySet& ct_set = ct->second;
SpellCategorySet current_set;
SpellCategorySet intersection_set;
{
MAPLOCK_READ(this, MAP_LOCK_TYPE_DEFAULT);
std::transform(m_spellCooldowns.begin(), m_spellCooldowns.end(), std::inserter(current_set, current_set.begin()), select1st<SpellCooldowns::value_type>());
}
std::set_intersection(ct_set.begin(),ct_set.end(), current_set.begin(),current_set.end(),std::inserter(intersection_set,intersection_set.begin()));
if (intersection_set.empty())
return;
for (SpellCategorySet::const_iterator itr = intersection_set.begin(); itr != intersection_set.end(); ++itr)
RemoveSpellCooldown(*itr, update);
}
void Player::RemoveArenaSpellCooldowns()
{
// remove cooldowns on spells that has < 15 min CD
SpellCooldowns::iterator itr, next;
// iterate spell cooldowns
for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
{
next = itr;
++next;
SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
// check if spellentry is present and if the cooldown is less than 15 mins
if ( entry &&
entry->RecoveryTime <= 15 * MINUTE * IN_MILLISECONDS &&
entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILLISECONDS )
{
// remove & notify
RemoveSpellCooldown(itr->first, true);
}
}
if (Pet *pet = GetPet())
{
// notify player
for (CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
SendClearCooldown(itr->first, pet);
// actually clear cooldowns
pet->m_CreatureSpellCooldowns.clear();
}
}
void Player::RemoveAllSpellCooldown()
{
if(!m_spellCooldowns.empty())
{
for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
SendClearCooldown(itr->first, this);
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
m_spellCooldowns.clear();
}
}
void Player::_LoadSpellCooldowns(QueryResult *result)
{
// some cooldowns can be already set at aura loading...
//QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
if (result)
{
time_t curTime = time(NULL);
do
{
Field *fields = result->Fetch();
uint32 spell_id = fields[0].GetUInt32();
uint32 item_id = fields[1].GetUInt32();
time_t db_time = (time_t)fields[2].GetUInt64();
if(!sSpellStore.LookupEntry(spell_id))
{
sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
continue;
}
// skip outdated cooldown
if (db_time <= curTime)
continue;
AddSpellCooldown(spell_id, item_id, db_time);
DEBUG_LOG("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
}
while( result->NextRow() );
delete result;
}
}
void Player::_SaveSpellCooldowns()
{
static SqlStatementID deleteSpellCooldown ;
static SqlStatementID insertSpellCooldown ;
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteSpellCooldown, "DELETE FROM character_spell_cooldown WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
time_t curTime = time(NULL);
time_t infTime = curTime + infinityCooldownDelayCheck;
// remove outdated and save active
for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
{
if (itr->second.end <= curTime)
{
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
m_spellCooldowns.erase(itr++);
}
else if (itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
{
stmt = CharacterDatabase.CreateStatement(insertSpellCooldown, "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES( ?, ?, ?, ?)");
stmt.PExecute(GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
++itr;
}
else
++itr;
}
}
uint32 Player::resetTalentsCost() const
{
// The first time reset costs 1 gold
if (m_resetTalentsCost < 1*GOLD)
return 1*GOLD;
// then 5 gold
else if (m_resetTalentsCost < 5*GOLD)
return 5*GOLD;
// After that it increases in increments of 5 gold
else if (m_resetTalentsCost < 10*GOLD)
return 10*GOLD;
else
{
time_t months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
if (months > 0)
{
// This cost will be reduced by a rate of 5 gold per month
int32 new_cost = int32((m_resetTalentsCost) - 5*GOLD*months);
// to a minimum of 10 gold.
return uint32(new_cost < 10*GOLD ? 10*GOLD : new_cost);
}
else
{
// After that it increases in increments of 5 gold
int32 new_cost = m_resetTalentsCost + 5*GOLD;
// until it hits a cap of 50 gold.
if (new_cost > 50*GOLD)
new_cost = 50*GOLD;
return new_cost;
}
}
}
bool Player::resetTalents(bool no_cost, bool all_specs)
{
// not need after this call
if (HasAtLoginFlag(AT_LOGIN_RESET_TALENTS) && all_specs)
RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
if (m_usedTalentCount == 0 && !all_specs)
{
UpdateFreeTalentPoints(false); // for fix if need counter
return false;
}
uint32 cost = 0;
if(!no_cost)
{
cost = resetTalentsCost();
if (GetMoney() < cost)
{
SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
return false;
}
}
RemoveAllEnchantments(TEMP_ENCHANTMENT_SLOT);
for (PlayerTalentMap::iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end();)
{
if (iter->second.state == PLAYERSPELL_REMOVED)
{
++iter;
continue;
}
TalentEntry const* talentInfo = iter->second.talentEntry;
if (!talentInfo)
{
m_talents[m_activeSpec].erase(iter++);
continue;
}
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
if (!talentTabInfo)
{
m_talents[m_activeSpec].erase(iter++);
continue;
}
// unlearn only talents for character class
// some spell learned by one class as normal spells or know at creation but another class learn it as talent,
// to prevent unexpected lost normal learned spell skip another class talents
if ((getClassMask() & talentTabInfo->ClassMask) == 0)
{
++iter;
continue;
}
for (int j = 0; j < MAX_TALENT_RANK; ++j)
if (talentInfo->RankID[j])
{
removeSpell(talentInfo->RankID[j],!IsPassiveSpell(talentInfo->RankID[j]),false);
SpellEntry const *spellInfo = sSpellStore.LookupEntry(talentInfo->RankID[j]);
for (int k = 0; k < MAX_EFFECT_INDEX; ++k)
if (spellInfo->EffectTriggerSpell[k])
removeSpell(spellInfo->EffectTriggerSpell[k]);
}
iter = m_talents[m_activeSpec].begin();
}
// for not current spec just mark removed all saved to DB case and drop not saved
if (all_specs)
{
for (uint8 spec = 0; spec < MAX_TALENT_SPEC_COUNT; ++spec)
{
if (spec == m_activeSpec)
continue;
for (PlayerTalentMap::iterator iter = m_talents[spec].begin(); iter != m_talents[spec].end();)
{
switch (iter->second.state)
{
case PLAYERSPELL_REMOVED:
++iter;
break;
case PLAYERSPELL_NEW:
m_talents[spec].erase(iter++);
break;
default:
iter->second.state = PLAYERSPELL_REMOVED;
++iter;
break;
}
}
}
}
UpdateFreeTalentPoints(false);
if(!no_cost)
{
ModifyMoney(-(int32)cost);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
m_resetTalentsCost = cost;
m_resetTalentsTime = time(NULL);
}
//FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
RemovePet(PET_SAVE_REAGENTS);
/* when prev line will dropped use next line
if (Pet* pet = GetPet())
{
if (pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
pet->Unsummon(PET_SAVE_REAGENTS, this);
}
*/
return true;
}
Mail* Player::GetMail(uint32 id)
{
for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
{
if ((*itr)->messageID == id)
{
return (*itr);
}
}
return NULL;
}
void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
{
if (target == this)
{
Object::_SetCreateBits(updateMask, target);
}
else
{
for(uint16 index = 0; index < m_valuesCount; index++)
{
if (GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
updateMask->SetBit(index);
}
}
}
void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
{
if (target == this)
{
Object::_SetUpdateBits(updateMask, target);
}
else
{
Object::_SetUpdateBits(updateMask, target);
*updateMask &= updateVisualBits;
}
}
void Player::InitVisibleBits()
{
updateVisualBits.SetCount(PLAYER_END);
updateVisualBits.SetBit(OBJECT_FIELD_GUID);
updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
updateVisualBits.SetBit(UNIT_FIELD_POWER1);
updateVisualBits.SetBit(UNIT_FIELD_POWER2);
updateVisualBits.SetBit(UNIT_FIELD_POWER3);
updateVisualBits.SetBit(UNIT_FIELD_POWER4);
updateVisualBits.SetBit(UNIT_FIELD_POWER5);
updateVisualBits.SetBit(UNIT_FIELD_POWER6);
updateVisualBits.SetBit(UNIT_FIELD_POWER7);
updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
updateVisualBits.SetBit(PLAYER_FLAGS);
updateVisualBits.SetBit(PLAYER_GUILDID);
updateVisualBits.SetBit(PLAYER_GUILDRANK);
updateVisualBits.SetBit(PLAYER_BYTES);
updateVisualBits.SetBit(PLAYER_BYTES_2);
updateVisualBits.SetBit(PLAYER_BYTES_3);
updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
updateVisualBits.SetBit(UNIT_NPC_FLAGS);
// PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
updateVisualBits.SetBit(i);
// Players visible items are not inventory stuff
for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
uint32 offset = i * 2;
// item entry
updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
// enchant
updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
}
updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
}
void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
{
if (target == this)
{
for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
}
for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
}
}
Unit::BuildCreateUpdateBlockForPlayer( data, target );
}
void Player::DestroyForPlayer( Player *target, bool anim ) const
{
Unit::DestroyForPlayer( target, anim );
for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->DestroyForPlayer( target );
}
if (target == this)
{
for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->DestroyForPlayer( target );
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (m_items[i] == NULL)
continue;
m_items[i]->DestroyForPlayer( target );
}
}
}
bool Player::HasSpell(uint32 spell) const
{
PlayerSpellMap::const_iterator itr = m_spells.find(spell);
return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
!itr->second.disabled);
}
bool Player::HasActiveSpell(uint32 spell) const
{
PlayerSpellMap::const_iterator itr = m_spells.find(spell);
return (itr != m_spells.end() && itr->second.state != PLAYERSPELL_REMOVED &&
itr->second.active && !itr->second.disabled);
}
TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell, uint32 reqLevel) const
{
if (!trainer_spell)
return TRAINER_SPELL_RED;
if (!trainer_spell->learnedSpell)
return TRAINER_SPELL_RED;
// known spell
if (HasSpell(trainer_spell->learnedSpell))
return TRAINER_SPELL_GRAY;
// check race/class requirement
if (!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
return TRAINER_SPELL_RED;
bool prof = SpellMgr::IsProfessionSpell(trainer_spell->learnedSpell);
// check level requirement
if (!prof || GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_LEVEL)))
if (getLevel() < reqLevel)
return TRAINER_SPELL_RED;
if (SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell))
{
// check prev.rank requirement
if (spell_chain->prev && !HasSpell(spell_chain->prev))
return TRAINER_SPELL_RED;
// check additional spell requirement
if (spell_chain->req && !HasSpell(spell_chain->req))
return TRAINER_SPELL_RED;
}
// check skill requirement
if (!prof || GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_SKILL)))
if (trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
return TRAINER_SPELL_RED;
// exist, already checked at loading
SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
// secondary prof. or not prof. spell
uint32 skill = spell->EffectMiscValue[1];
if (spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
return TRAINER_SPELL_GREEN;
// check primary prof. limit
if (sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
return TRAINER_SPELL_GREEN_DISABLED;
return TRAINER_SPELL_GREEN;
}
/**
* Deletes a character from the database
*
* The way, how the characters will be deleted is decided based on the config option.
*
* @see Player::DeleteOldCharacters
*
* @param playerguid the low-GUID from the player which should be deleted
* @param accountId the account id from the player
* @param updateRealmChars when this flag is set, the amount of characters on that realm will be updated in the realmlist
* @param deleteFinally if this flag is set, the config option will be ignored and the character will be permanently removed from the database
*/
void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRealmChars, bool deleteFinally)
{
// for nonexistent account avoid update realm
if (accountId == 0)
updateRealmChars = false;
uint32 charDelete_method = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_METHOD);
uint32 charDelete_minLvl = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_MIN_LEVEL);
// if we want to finally delete the character or the character does not meet the level requirement, we set it to mode 0
if (deleteFinally || Player::GetLevelFromDB(playerguid) < charDelete_minLvl)
charDelete_method = 0;
uint32 lowguid = playerguid.GetCounter();
// convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
// bones will be deleted by corpse/bones deleting thread shortly
sObjectAccessor.ConvertCorpseForPlayer(playerguid);
// remove from guild
if (uint32 guildId = GetGuildIdFromDB(playerguid))
{
if (Guild* guild = sGuildMgr.GetGuildById(guildId))
{
if (guild->DelMember(playerguid))
{
guild->Disband();
delete guild;
}
}
}
// remove from arena teams
LeaveAllArenaTeams(playerguid);
// the player was uninvited already on logout so just remove from group
QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", lowguid);
if (resultGroup)
{
uint32 groupId = (*resultGroup)[0].GetUInt32();
delete resultGroup;
if (Group* group = sObjectMgr.GetGroupById(groupId))
RemoveFromGroup(group, playerguid);
}
// remove signs from petitions (also remove petitions if owner);
RemovePetitionsAndSigns(playerguid, 10);
switch(charDelete_method)
{
// completely remove from the database
case 0:
{
// return back all mails with COD and Item 0 1 2 3 4 5 6 7
QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,body,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", lowguid);
if (resultMail)
{
do
{
Field *fields = resultMail->Fetch();
uint32 mail_id = fields[0].GetUInt32();
uint16 mailType = fields[1].GetUInt16();
uint16 mailTemplateId= fields[2].GetUInt16();
uint32 sender = fields[3].GetUInt32();
std::string subject = fields[4].GetCppString();
std::string body = fields[5].GetCppString();
uint32 money = fields[6].GetUInt32();
bool has_items = fields[7].GetBool();
//we can return mail now
//so firstly delete the old one
CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
// mail not from player
if (mailType != MAIL_NORMAL)
{
if (has_items)
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
continue;
}
MailDraft draft;
if (mailTemplateId)
draft.SetMailTemplate(mailTemplateId, false);// items already included
else
draft.SetSubjectAndBody(subject, body);
if (has_items)
{
// data needs to be at first place for Item::LoadFromDB
// 0 1 2 3
QueryResult *resultItems = CharacterDatabase.PQuery("SELECT data,text,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id);
if (resultItems)
{
do
{
Field *fields2 = resultItems->Fetch();
uint32 item_guidlow = fields2[2].GetUInt32();
uint32 item_template = fields2[3].GetUInt32();
ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
if (!itemProto)
{
CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
continue;
}
Item *pItem = NewItemOrBag(itemProto);
if (!pItem->LoadFromDB(item_guidlow, fields2, playerguid))
{
pItem->FSetState(ITEM_REMOVED);
pItem->SaveToDB(); // it also deletes item object !
continue;
}
draft.AddItem(pItem);
}
while (resultItems->NextRow());
delete resultItems;
}
}
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
uint32 pl_account = sAccountMgr.GetPlayerAccountIdByGUID(playerguid);
draft.SetMoney(money).SendReturnToSender(pl_account, playerguid, ObjectGuid(HIGHGUID_PLAYER, sender));
}
while (resultMail->NextRow());
delete resultMail;
}
// unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
// Get guids of character's pets, will deleted in transaction
QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'", lowguid);
// delete char from friends list when selected chars is online (non existing - error)
QueryResult *resultFriend = CharacterDatabase.PQuery("SELECT DISTINCT guid FROM character_social WHERE friend = '%u'", lowguid);
// NOW we can finally clear other DB data related to character
CharacterDatabase.BeginTransaction();
if (resultPets)
{
do
{
Field *fields3 = resultPets->Fetch();
uint32 petguidlow = fields3[0].GetUInt32();
//do not create separate transaction for pet delete otherwise we will get fatal error!
Pet::DeleteFromDB(petguidlow, false);
} while (resultPets->NextRow());
delete resultPets;
}
// cleanup friends for online players, offline case will cleanup later in code
if (resultFriend)
{
do
{
Field* fieldsFriend = resultFriend->Fetch();
if (Player* sFriend = sObjectAccessor.FindPlayer(ObjectGuid(HIGHGUID_PLAYER, fieldsFriend[0].GetUInt32())))
{
if (sFriend->IsInWorld())
{
sFriend->GetSocial()->RemoveFromSocialList(playerguid, false);
sSocialMgr.SendFriendStatus(sFriend, FRIEND_REMOVED, playerguid, false);
}
}
} while (resultFriend->NextRow());
delete resultFriend;
}
CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_queststatus_weekly WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'", lowguid, lowguid);
CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u' OR PlayerGuid2 = '%u'", lowguid, lowguid);
CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'", lowguid);
CharacterDatabase.CommitTransaction();
break;
}
// The character gets unlinked from the account, the name gets freed up and appears as deleted ingame
case 1:
CharacterDatabase.PExecute("UPDATE characters SET deleteInfos_Name=name, deleteInfos_Account=account, deleteDate='" UI64FMTD "', name='', account=0 WHERE guid=%u", uint64(time(NULL)), lowguid);
break;
default:
sLog.outError("Player::DeleteFromDB: Unsupported delete method: %u.", charDelete_method);
}
if (updateRealmChars)
sAccountMgr.UpdateCharactersCount(accountId, realmID);
}
/**
* Characters which were kept back in the database after being deleted and are now too old (see config option "CharDelete.KeepDays"), will be completely deleted.
*
* @see Player::DeleteFromDB
*/
void Player::DeleteOldCharacters()
{
uint32 keepDays = sWorld.getConfig(CONFIG_UINT32_CHARDELETE_KEEP_DAYS);
if (!keepDays)
return;
Player::DeleteOldCharacters(keepDays);
}
/**
* Characters which were kept back in the database after being deleted and are older than the specified amount of days, will be completely deleted.
*
* @see Player::DeleteFromDB
*
* @param keepDays overrite the config option by another amount of days
*/
void Player::DeleteOldCharacters(uint32 keepDays)
{
sLog.outString("Player::DeleteOldChars: Deleting all characters which have been deleted %u days before...", keepDays);
QueryResult *resultChars = CharacterDatabase.PQuery("SELECT guid, deleteInfos_Account FROM characters WHERE deleteDate IS NOT NULL AND deleteDate < '" UI64FMTD "'", uint64(time(NULL) - time_t(keepDays * DAY)));
if (resultChars)
{
sLog.outString("Player::DeleteOldChars: Found %u character(s) to delete",uint32(resultChars->GetRowCount()));
do
{
Field *charFields = resultChars->Fetch();
ObjectGuid guid = ObjectGuid(HIGHGUID_PLAYER, charFields[0].GetUInt32());
Player::DeleteFromDB(guid, charFields[1].GetUInt32(), true, true);
} while(resultChars->NextRow());
delete resultChars;
}
}
void Player::SetMovement(PlayerMovementType pType)
{
WorldPacket data;
switch(pType)
{
case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
default:
sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
return;
}
data << GetPackGUID();
data << uint32(0);
GetSession()->SendPacket( &data );
}
/* Preconditions:
- a resurrectable corpse must not be loaded for the player (only bones)
- the player must be in world
*/
void Player::BuildPlayerRepop()
{
WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
data << GetPackGUID();
GetSession()->SendPacket(&data);
if (getRace() == RACE_NIGHTELF)
CastSpell(this, 20584, true); // auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
// there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
// there must be SMSG.STOP_MIRROR_TIMER
// there we must send 888 opcode
// the player cannot have a corpse already, only bones which are not returned by GetCorpse
if (GetCorpse())
{
sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
MANGOS_ASSERT(false);
}
// create a corpse and place it at the player's location
Corpse *corpse = CreateCorpse();
if(!corpse)
{
sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
return;
}
GetMap()->Add(corpse);
// convert player body to ghost
if (getDeathState() != GHOULED)
SetHealth( 1 );
SetMovement(MOVE_WATER_WALK);
if(!GetSession()->isLogingOut())
SetMovement(MOVE_UNROOT);
// BG - remove insignia related
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
if (getDeathState() != GHOULED)
SendCorpseReclaimDelay();
// to prevent cheating
corpse->ResetGhostTime();
StopMirrorTimers(); //disable timers(bars)
// set and clear other
SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
}
void Player::ResurrectPlayer(float restore_percent, bool applySickness)
{
WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
data << uint32(-1);
data << float(0);
data << float(0);
data << float(0);
GetSession()->SendPacket(&data);
// speed change, land walk
// remove death flag + set aura
SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
SetDeathState(ALIVE);
if (getRace() == RACE_NIGHTELF)
RemoveAurasDueToSpell(20584); // speed bonuses
RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
// refer-a-friend flag - maybe wrong and hacky
if (GetAccountLinkedState() != STATE_NOT_LINKED)
SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND);
SetMovement(MOVE_LAND_WALK);
SetMovement(MOVE_UNROOT);
m_deathTimer = 0;
// set health/powers (0- will be set in caller)
if (restore_percent>0.0f)
{
SetHealth(uint32(GetMaxHealth()*restore_percent));
SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
SetPower(POWER_RAGE, 0);
SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
}
// trigger update zone for alive state zone updates
uint32 newzone, newarea;
GetZoneAndAreaId(newzone,newarea);
UpdateZone(newzone,newarea);
// update visibility of world around viewpoint
m_camera.UpdateVisibilityForOwner();
// update visibility of player for nearby cameras
UpdateObjectVisibility();
if(!applySickness)
return;
//Characters from level 1-10 are not affected by resurrection sickness.
//Characters from level 11-19 will suffer from one minute of sickness
//for each level they are above 10.
//Characters level 20 and up suffer from ten minutes of sickness.
int32 startLevel = sWorld.getConfig(CONFIG_INT32_DEATH_SICKNESS_LEVEL);
if (int32(getLevel()) >= startLevel)
{
// set resurrection sickness
CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
// not full duration
if (int32(getLevel()) < startLevel+9)
{
int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
if (SpellAuraHolderPtr holder = GetSpellAuraHolder(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS))
{
holder->SetAuraDuration(delta*IN_MILLISECONDS);
holder->SendAuraUpdate(false);
}
}
}
}
void Player::KillPlayer()
{
SetMovement(MOVE_ROOT);
StopMirrorTimers(); //disable timers(bars)
SetDeathState(CORPSE);
//SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_NONE);
ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
// 6 minutes until repop at graveyard
m_deathTimer = 6*MINUTE*IN_MILLISECONDS;
UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
// don't create corpse at this moment, player might be falling
// update visibility
UpdateObjectVisibility();
}
Corpse* Player::CreateCorpse()
{
// prevent existence 2 corpse for player
SpawnCorpseBones();
Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
SetPvPDeath(false);
if (!corpse->Create(sObjectMgr.GenerateCorpseLowGuid(), this))
{
delete corpse;
return NULL;
}
uint8 skin = GetByteValue(PLAYER_BYTES, 0);
uint8 face = GetByteValue(PLAYER_BYTES, 1);
uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
corpse->SetByteValue(CORPSE_FIELD_BYTES_1, 1, getRace());
corpse->SetByteValue(CORPSE_FIELD_BYTES_1, 2, getGender());
corpse->SetByteValue(CORPSE_FIELD_BYTES_1, 3, skin);
corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 0, face);
corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 1, hairstyle);
corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 2, haircolor);
corpse->SetByteValue(CORPSE_FIELD_BYTES_2, 3, facialhair);
uint32 flags = CORPSE_FLAG_UNK2;
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
flags |= CORPSE_FLAG_HIDE_HELM;
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
flags |= CORPSE_FLAG_HIDE_CLOAK;
if (InBattleGround() && !InArena())
flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
uint32 iDisplayID;
uint32 iIventoryType;
uint32 _cfi;
for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
if (m_items[i])
{
iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
iIventoryType = m_items[i]->GetProto()->InventoryType;
_cfi = iDisplayID | (iIventoryType << 24);
corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
}
}
// we not need saved corpses for BG/arenas
if (!GetMap()->IsBattleGroundOrArena())
corpse->SaveToDB();
// register for player, but not show
sObjectAccessor.AddCorpse(corpse);
return corpse;
}
void Player::SpawnCorpseBones()
{
if (sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid()))
if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
SaveToDB(); // prevent loading as ghost without corpse
}
Corpse* Player::GetCorpse() const
{
return sObjectAccessor.GetCorpseForPlayerGUID(GetObjectGuid());
}
void Player::DurabilityLossAll(double percent, bool inventory)
{
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
DurabilityLoss(pItem,percent);
if (inventory)
{
// bags not have durability
// for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
DurabilityLoss(pItem,percent);
// keys not have durability
//for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = GetItemByPos( i, j ))
DurabilityLoss(pItem,percent);
}
}
void Player::DurabilityLoss(Item* item, double percent)
{
if(!item )
return;
uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
if(!pMaxDurability)
return;
uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
if (pDurabilityLoss < 1 )
pDurabilityLoss = 1;
DurabilityPointsLoss(item,pDurabilityLoss);
}
void Player::DurabilityPointsLossAll(int32 points, bool inventory)
{
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
DurabilityPointsLoss(pItem,points);
if (inventory)
{
// bags not have durability
// for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
DurabilityPointsLoss(pItem,points);
// keys not have durability
//for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = GetItemByPos( i, j ))
DurabilityPointsLoss(pItem,points);
}
}
void Player::DurabilityPointsLoss(Item* item, int32 points)
{
int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
int32 pNewDurability = pOldDurability - points;
if (pNewDurability < 0)
pNewDurability = 0;
else if (pNewDurability > pMaxDurability)
pNewDurability = pMaxDurability;
if (pOldDurability != pNewDurability)
{
// modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
_ApplyItemMods(item,item->GetSlot(), false);
item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
// modify item stats _after_ restore durability to pass _ApplyItemMods internal check
if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
_ApplyItemMods(item,item->GetSlot(), true);
item->SetState(ITEM_CHANGED, this);
}
}
void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
DurabilityPointsLoss(pItem,1);
}
uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
{
uint32 TotalCost = 0;
// equipped, backpack, bags itself
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
// bank, buyback and keys not repaired
// items in inventory bags
for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
for(int i = 0; i < MAX_BAG_SIZE; ++i)
TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
return TotalCost;
}
uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
{
Item* item = GetItemByPos(pos);
uint32 TotalCost = 0;
if(!item)
return TotalCost;
uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
if(!maxDurability)
return TotalCost;
uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
if (cost)
{
uint32 LostDurability = maxDurability - curDurability;
if (LostDurability>0)
{
ItemPrototype const *ditemProto = item->GetProto();
DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
if(!dcost)
{
sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
return TotalCost;
}
uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
if(!dQualitymodEntry)
{
sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
return TotalCost;
}
uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
costs = uint32(costs * discountMod);
if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
costs = 1;
if (guildBank)
{
if (GetGuildId()==0)
{
DEBUG_LOG("You are not member of a guild");
return TotalCost;
}
Guild* pGuild = sGuildMgr.GetGuildById(GetGuildId());
if (!pGuild)
return TotalCost;
if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
{
DEBUG_LOG("You do not have rights to withdraw for repairs");
return TotalCost;
}
if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
{
DEBUG_LOG("You do not have enough money withdraw amount remaining");
return TotalCost;
}
if (pGuild->GetGuildBankMoney() < costs)
{
DEBUG_LOG("There is not enough money in bank");
return TotalCost;
}
pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
TotalCost = costs;
}
else if (GetMoney() < costs)
{
DEBUG_LOG("You do not have enough money");
return TotalCost;
}
else
ModifyMoney( -int32(costs) );
}
}
item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
item->SetState(ITEM_CHANGED, this);
// reapply mods for total broken and repaired item if equipped
if (IsEquipmentPos(pos) && !curDurability)
_ApplyItemMods(item,pos & 255, true);
return TotalCost;
}
void Player::RepopAtGraveyard()
{
// note: this can be called also when the player is alive
// for example from WorldSession::HandleMovementOpcodes
AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
// Such zones are considered unreachable as a ghost and the player must be automatically revived
if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport() || GetPositionZ() < -500.0f)
{
ResurrectPlayer(0.5f);
SpawnCorpseBones();
}
WorldSafeLocsEntry const *ClosestGrave = NULL;
// Special handle for battleground maps
if ( BattleGround *bg = GetBattleGround() )
ClosestGrave = bg->GetClosestGraveYard(this);
else
ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
// stop countdown until repop
m_deathTimer = 0;
// if no grave found, stay at the current location
// and don't show spirit healer location
if (ClosestGrave)
{
TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
if (isDead()) // not send if alive, because it used in TeleportTo()
{
WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
data << ClosestGrave->map_id;
data << ClosestGrave->x;
data << ClosestGrave->y;
data << ClosestGrave->z;
GetSession()->SendPacket(&data);
}
}
}
void Player::JoinedChannel(Channel *c)
{
m_channels.push_back(c);
}
void Player::LeftChannel(Channel *c)
{
m_channels.remove(c);
}
void Player::CleanupChannels()
{
while (!m_channels.empty())
{
Channel* ch = *m_channels.begin();
m_channels.erase(m_channels.begin()); // remove from player's channel list
ch->Leave(GetObjectGuid(), false); // not send to client, not remove from player's channel list
if (ChannelMgr* cMgr = channelMgr(GetTeam()))
cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
}
DEBUG_LOG("Player: channels cleaned up!");
}
void Player::UpdateLocalChannels(uint32 newZone )
{
if (m_channels.empty())
return;
AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
if(!current_zone)
return;
ChannelMgr* cMgr = channelMgr(GetTeam());
if(!cMgr)
return;
std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
{
next = i; ++next;
// skip non built-in channels
if(!(*i)->IsConstant())
continue;
ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
if(!ch)
continue;
if((ch->flags & 4) == 4) // global channel without zone name in pattern
continue;
// new channel
char new_channel_name_buf[100];
snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
if ((*i)!=new_channel)
{
new_channel->Join(GetObjectGuid(),""); // will output Changed Channel: N. Name
// leave old channel
(*i)->Leave(GetObjectGuid(),false); // not send leave channel, it already replaced at client
std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
LeftChannel(*i); // remove from player's channel list
cMgr->LeftChannel(name); // delete if empty
}
}
DEBUG_LOG("Player: channels cleaned up!");
}
void Player::LeaveLFGChannel()
{
for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
{
if ((*i)->IsLFG())
{
(*i)->Leave(GetObjectGuid());
break;
}
}
}
void Player::JoinLFGChannel()
{
for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
{
if((*i)->IsLFG())
{
(*i)->Join(GetObjectGuid(),"");
break;
}
}
}
void Player::UpdateDefense()
{
uint32 defense_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_DEFENSE);
if (UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
{
// update dependent from defense skill part
UpdateDefenseBonusesMod();
}
}
void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
{
if (modGroup >= BASEMOD_END || modType >= MOD_END)
{
sLog.outError("ERROR in HandleBaseModValue(): nonexistent BaseModGroup of wrong BaseModType!");
return;
}
float val = 1.0f;
switch(modType)
{
case FLAT_MOD:
m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
break;
case PCT_MOD:
if (amount <= -100.0f)
amount = -200.0f;
// Shield Block Value PCT_MODs should be added, not multiplied
if (modGroup == SHIELD_BLOCK_VALUE)
{
val = amount / 100.0f;
m_auraBaseMod[modGroup][modType] += apply ? val : -val;
}
else
{
val = (100.0f + amount) / 100.0f;
m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
}
break;
}
if(!CanModifyStats())
return;
switch(modGroup)
{
case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
default: break;
}
}
float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
{
if (modGroup >= BASEMOD_END || modType > MOD_END)
{
sLog.outError("trial to access nonexistent BaseModGroup or wrong BaseModType!");
return 0.0f;
}
if (modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
return 0.0f;
return m_auraBaseMod[modGroup][modType];
}
float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
{
if (modGroup >= BASEMOD_END)
{
sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
return 0.0f;
}
if (m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
return 0.0f;
return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
}
uint32 Player::GetShieldBlockValue() const
{
float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
value = (value < 0) ? 0 : value;
return uint32(value);
}
float Player::GetMeleeCritFromAgility()
{
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (critBase==NULL || critRatio==NULL)
return 0.0f;
float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
return crit*100.0f;
}
void Player::GetDodgeFromAgility(float &diminishing, float &nondiminishing)
{
// Table for base dodge values
const float dodge_base[MAX_CLASSES] =
{
0.036640f, // Warrior
0.034943f, // Paladin
-0.040873f, // Hunter
0.020957f, // Rogue
0.034178f, // Priest
0.036640f, // DK
0.021080f, // Shaman
0.036587f, // Mage
0.024211f, // Warlock
0.0f, // ??
0.056097f // Druid
};
// Crit/agility to dodge/agility coefficient multipliers; 3.2.0 increased required agility by 15%
const float crit_to_dodge[MAX_CLASSES] =
{
0.85f/1.15f, // Warrior
1.00f/1.15f, // Paladin
1.11f/1.15f, // Hunter
2.00f/1.15f, // Rogue
1.00f/1.15f, // Priest
0.85f/1.15f, // DK
1.60f/1.15f, // Shaman
1.00f/1.15f, // Mage
0.97f/1.15f, // Warlock (?)
0.0f, // ??
2.00f/1.15f // Druid
};
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
// Dodge per agility is proportional to crit per agility, which is available from DBC files
GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (dodgeRatio==NULL || pclass > MAX_CLASSES)
return;
// TODO: research if talents/effects that increase total agility by x% should increase non-diminishing part
float base_agility = GetCreateStat(STAT_AGILITY) * m_auraModifiersGroup[UNIT_MOD_STAT_START + STAT_AGILITY][BASE_PCT];
float bonus_agility = GetStat(STAT_AGILITY) - base_agility;
// calculate diminishing (green in char screen) and non-diminishing (white) contribution
diminishing = 100.0f * bonus_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1];
nondiminishing = 100.0f * (dodge_base[pclass-1] + base_agility * dodgeRatio->ratio * crit_to_dodge[pclass-1]);
}
float Player::GetSpellCritFromIntellect()
{
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (critBase==NULL || critRatio==NULL)
return 0.0f;
float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
return crit*100.0f;
}
float Player::GetRatingMultiplier(CombatRating cr) const
{
uint32 level = getLevel();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
// gtOCTClassCombatRatingScalarStore.dbc starts with 1, CombatRating with zero, so cr+1
GtOCTClassCombatRatingScalarEntry const *classRating = sGtOCTClassCombatRatingScalarStore.LookupEntry((getClass()-1)*GT_MAX_RATING+cr+1);
if (!Rating || !classRating)
return 1.0f; // By default use minimum coefficient (not must be called)
return classRating->ratio / Rating->ratio;
}
float Player::GetRatingBonusValue(CombatRating cr) const
{
return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) * GetRatingMultiplier(cr);
}
float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
{
switch (attType)
{
case BASE_ATTACK:
return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
case OFF_ATTACK:
return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
default:
break;
}
return 0.0f;
}
float Player::OCTRegenHPPerSpirit()
{
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (baseRatio==NULL || moreRatio==NULL)
return 0.0f;
// Formula from PaperDollFrame script
float spirit = GetStat(STAT_SPIRIT);
float baseSpirit = spirit;
if (baseSpirit>50) baseSpirit = 50;
float moreSpirit = spirit - baseSpirit;
float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
return regen;
}
float Player::OCTRegenMPPerSpirit()
{
uint32 level = getLevel();
uint32 pclass = getClass();
if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
// GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
if (moreRatio==NULL)
return 0.0f;
// Formula get from PaperDollFrame script
float spirit = GetStat(STAT_SPIRIT);
float regen = spirit * moreRatio->ratio;
return regen;
}
void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
{
m_baseRatingValue[cr]+=(apply ? value : -value);
// explicit affected values
switch (cr)
{
case CR_HASTE_MELEE:
{
float RatingChange = value * GetRatingMultiplier(cr);
ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
break;
}
case CR_HASTE_RANGED:
{
float RatingChange = value * GetRatingMultiplier(cr);
ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
break;
}
case CR_HASTE_SPELL:
{
float RatingChange = value * GetRatingMultiplier(cr);
ApplyCastTimePercentMod(RatingChange,apply);
break;
}
default:
break;
}
UpdateRating(cr);
}
void Player::UpdateRating(CombatRating cr)
{
int32 amount = m_baseRatingValue[cr];
// Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
// stat used stored in miscValueB for this aura
AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
if ((*i)->GetMiscValue() & (1<<cr))
amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
if (amount < 0)
amount = 0;
SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
bool affectStats = CanModifyStats();
switch (cr)
{
case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
case CR_DEFENSE_SKILL:
UpdateDefenseBonusesMod();
break;
case CR_DODGE:
UpdateDodgePercentage();
break;
case CR_PARRY:
UpdateParryPercentage();
break;
case CR_BLOCK:
UpdateBlockPercentage();
break;
case CR_HIT_MELEE:
UpdateMeleeHitChances();
break;
case CR_HIT_RANGED:
UpdateRangedHitChances();
break;
case CR_HIT_SPELL:
UpdateSpellHitChances();
break;
case CR_CRIT_MELEE:
if (affectStats)
{
UpdateCritPercentage(BASE_ATTACK);
UpdateCritPercentage(OFF_ATTACK);
}
break;
case CR_CRIT_RANGED:
if (affectStats)
UpdateCritPercentage(RANGED_ATTACK);
break;
case CR_CRIT_SPELL:
if (affectStats)
UpdateAllSpellCritChances();
break;
case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
case CR_HIT_TAKEN_RANGED:
break;
case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
break;
case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
case CR_CRIT_TAKEN_RANGED:
break;
case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
break;
case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
case CR_HASTE_RANGED:
case CR_HASTE_SPELL:
break;
case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
case CR_WEAPON_SKILL_OFFHAND:
case CR_WEAPON_SKILL_RANGED:
break;
case CR_EXPERTISE:
if (affectStats)
{
UpdateExpertise(BASE_ATTACK);
UpdateExpertise(OFF_ATTACK);
}
break;
case CR_ARMOR_PENETRATION:
if (affectStats)
UpdateArmorPenetration();
break;
}
}
void Player::UpdateAllRatings()
{
for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
UpdateRating(CombatRating(cr));
}
void Player::SetRegularAttackTime()
{
for(int i = 0; i < MAX_ATTACK; ++i)
{
Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false);
if (tmpitem)
{
ItemPrototype const *proto = tmpitem->GetProto();
if (proto->Delay)
SetAttackTime(WeaponAttackType(i), proto->Delay);
else
SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
}
}
}
//skill+step, checking for max value
bool Player::UpdateSkill(uint32 skill_id, uint32 step)
{
if(!skill_id)
return false;
SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return false;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint32 value = SKILL_VALUE(data);
uint32 max = SKILL_MAX(data);
if ((!max) || (!value) || (value >= max))
return false;
if (value*512 < max*urand(0,512))
{
uint32 new_value = value+step;
if (new_value > max)
new_value = max;
SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
return true;
}
return false;
}
inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
{
if ( SkillValue >= GrayLevel )
return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREY)*10;
if ( SkillValue >= GreenLevel )
return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREEN)*10;
if ( SkillValue >= YellowLevel )
return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_YELLOW)*10;
return sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_ORANGE)*10;
}
bool Player::UpdateCraftSkill(uint32 spellid)
{
DEBUG_LOG("UpdateCraftSkill spellid %d", spellid);
SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid);
for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
if (_spell_idx->second->skillId)
{
uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
// Alchemy Discoveries here
SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
if (spellEntry && spellEntry->Mechanic == MECHANIC_DISCOVERY)
{
if (uint32 discoveredSpell = sSpellMgr.GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
learnSpell(discoveredSpell, false);
}
uint32 craft_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING);
return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
_spell_idx->second->max_value,
(_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
_spell_idx->second->min_value),
craft_skill_gain);
}
}
return false;
}
bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
{
DEBUG_LOG("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
// For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
switch (SkillId)
{
case SKILL_HERBALISM:
case SKILL_LOCKPICKING:
case SKILL_JEWELCRAFTING:
case SKILL_INSCRIPTION:
return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
case SKILL_SKINNING:
if ( sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)==0)
return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
else
return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
case SKILL_MINING:
if (sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)==0)
return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
else
return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
}
return false;
}
bool Player::UpdateFishingSkill()
{
DEBUG_LOG("UpdateFishingSkill");
uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING);
return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
}
// levels sync. with spell requirement for skill levels to learn
// bonus abilities in sSkillLineAbilityStore
// Used only to avoid scan DBC at each skill grow
static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
{
DEBUG_LOG("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
if ( !SkillId )
return false;
if (Chance <= 0) // speedup in 0 chance case
{
DEBUG_LOG("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
return false;
}
SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return false;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint16 SkillValue = SKILL_VALUE(data);
uint16 MaxValue = SKILL_MAX(data);
if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
return false;
int32 Roll = irand(1,1000);
if ( Roll <= Chance )
{
uint32 new_value = SkillValue+step;
if (new_value > MaxValue)
new_value = MaxValue;
SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
{
if((SkillValue < *bsl && new_value >= *bsl))
{
learnSkillRewardedSpells( SkillId, new_value);
break;
}
}
// Update depended enchants
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
if (pEnchant->requiredSkill != SkillId)
continue;
if (SkillValue < pEnchant->requiredSkillValue && new_value >= pEnchant->requiredSkillValue)
ApplyEnchantment(pItem, EnchantmentSlot(slot), true);
}
}
}
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
DEBUG_LOG("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
return true;
}
DEBUG_LOG("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
return false;
}
void Player::UpdateWeaponSkill(WeaponAttackType attType)
{
// no skill gain in pvp
Unit* pVictim = getVictim();
if (pVictim && pVictim->IsCharmerOrOwnerPlayerOrPlayerItself())
return;
if (IsInFeralForm())
return; // always maximized SKILL_FERAL_COMBAT in fact
if (GetShapeshiftForm() == FORM_TREE)
return; // use weapon but not skill up
uint32 weaponSkillGain = sWorld.getConfig(CONFIG_UINT32_SKILL_GAIN_WEAPON);
Item* pWeapon = GetWeaponForAttack(attType, true, true);
if (pWeapon && pWeapon->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
UpdateSkill(pWeapon->GetSkill(), weaponSkillGain);
else if (!pWeapon && attType == BASE_ATTACK)
UpdateSkill(SKILL_UNARMED, weaponSkillGain);
UpdateAllCritPercentages();
}
void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
{
uint32 plevel = getLevel(); // if defense than pVictim == attacker
uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
uint32 moblevel = pVictim->GetLevelForTarget(this);
if (moblevel < greylevel)
return;
if (moblevel > plevel + 5)
moblevel = plevel + 5;
uint32 lvldif = moblevel - greylevel;
if (lvldif < 3)
lvldif = 3;
int32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
// Max skill reached for level.
// Can in some cases be less than 0: having max skill and then .level -1 as example.
if (skilldif <= 0)
return;
float chance = float(3 * lvldif * skilldif) / plevel;
if(!defence)
chance *= 0.1f * GetStat(STAT_INTELLECT);
chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
if (roll_chance_f(chance))
{
if (defence)
UpdateDefense();
else
UpdateWeaponSkill(attType);
}
else
return;
}
void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
{
SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return;
uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
uint32 bonus_val = GetUInt32Value(bonusIndex);
int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
if (talent) // permanent bonus stored in high part
SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
else // temporary/item bonus stored in low part
SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
}
void Player::UpdateSkillsForLevel()
{
uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
uint32 maxSkill = GetMaxSkillValueForLevel();
bool alwaysMaxSkill = sWorld.getConfig(CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL);
for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
{
if (itr->second.uState == SKILL_DELETED)
continue;
uint32 pskill = itr->first;
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
if(!pSkill)
continue;
if (GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
continue;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint32 max = SKILL_MAX(data);
uint32 val = SKILL_VALUE(data);
/// update only level dependent max skill values
if (max!=1)
{
/// maximize skill always
if (alwaysMaxSkill)
{
SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, pskill);
}
else if (max != maxconfskill) /// update max skill value if current max skill not maximized
{
SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
}
}
}
}
void Player::UpdateSkillsToMaxSkillsForLevel()
{
for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
{
if (itr->second.uState == SKILL_DELETED)
continue;
uint32 pskill = itr->first;
if ( IsProfessionOrRidingSkill(pskill))
continue;
uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
uint32 data = GetUInt32Value(valueIndex);
uint32 max = SKILL_MAX(data);
if (max > 1)
{
SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, pskill);
}
if (pskill == SKILL_DEFENSE)
UpdateDefenseBonusesMod();
}
}
// This functions sets a skill line value (and adds if doesn't exist yet)
// To "remove" a skill line, set it's values to zero
void Player::SetSkill(uint16 id, uint16 currVal, uint16 maxVal, uint16 step /*=0*/)
{
if(!id)
return;
SkillStatusMap::iterator itr = mSkillStatus.find(id);
// has skill
if (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
{
if (currVal)
{
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
if (pEnchant->requiredSkill != id)
continue;
ApplyEnchantment(pItem, EnchantmentSlot(slot), false);
}
}
}
if (step) // need update step
SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos), MAKE_PAIR32(id, step));
// update value
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), MAKE_SKILL_VALUE(currVal, maxVal));
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_CHANGED;
learnSkillRewardedSpells(id, currVal);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
if (pEnchant->requiredSkill != id)
continue;
ApplyEnchantment(pItem, EnchantmentSlot(slot), true);
}
}
}
}
else //remove
{
// Remove depended enchants
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(int slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(slot));
if (!enchant_id)
continue;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
if (pEnchant->requiredSkill != id)
continue;
ApplyEnchantment(pItem, EnchantmentSlot(slot), false);
}
}
}
// clear skill fields
SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos), 0);
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos), 0);
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos), 0);
// mark as deleted or simply remove from map if not saved yet
if (itr->second.uState != SKILL_NEW)
itr->second.uState = SKILL_DELETED;
else
mSkillStatus.erase(itr);
// remove all spells that related to this skill
for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
if (SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
if (pAbility->skillId == id)
removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId));
}
}
else if (currVal) // add
{
for (int i = 0; i < PLAYER_MAX_SKILLS; ++i)
{
if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
{
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
if(!pSkill)
{
sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
return;
}
SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id, step));
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal, maxVal));
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
// insert new entry or update if not deleted old entry yet
if (itr != mSkillStatus.end())
{
itr->second.pos = i;
itr->second.uState = SKILL_CHANGED;
}
else
mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
// apply skill bonuses
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i), 0);
// temporary bonuses
AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
if ((*j)->GetModifier()->m_miscvalue == int32(id))
(*j)->ApplyModifier(true);
// permanent bonuses
AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
if ((*j)->GetModifier()->m_miscvalue == int32(id))
(*j)->ApplyModifier(true);
// Learn all spells for skill
learnSkillRewardedSpells(id, currVal);
return;
}
}
}
}
bool Player::HasSkill(uint32 skill) const
{
if(!skill)
return false;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
}
uint16 Player::GetSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
result += SKILL_TEMP_BONUS(bonus);
result += SKILL_PERM_BONUS(bonus);
return result < 0 ? 0 : result;
}
uint16 Player::GetMaxSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
result += SKILL_TEMP_BONUS(bonus);
result += SKILL_PERM_BONUS(bonus);
return result < 0 ? 0 : result;
}
uint16 Player::GetPureMaxSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
}
uint16 Player::GetBaseSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
return result < 0 ? 0 : result;
}
uint16 Player::GetPureSkillValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
}
int16 Player::GetSkillPermBonusValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
}
int16 Player::GetSkillTempBonusValue(uint32 skill) const
{
if(!skill)
return 0;
SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
return 0;
return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
}
void Player::SendActionButtons(uint32 state) const
{
DETAIL_LOG( "Initializing Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec);
WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
data << uint8(state);
/*
state can be 0, 1, 2
0 - Looks to be sent when initial action buttons get sent, however on Trinity we use 1 since 0 had some difficulties
1 - Used in any SMSG_ACTION_BUTTONS packet with button data on Trinity. Only used after spec swaps on retail.
2 - Clears the action bars client sided. This is sent during spec swap before unlearning and before sending the new buttons
*/
if (state != 2)
{
ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
{
ActionButtonList::const_iterator itr = currentActionButtonList.find(button);
if (itr != currentActionButtonList.end() && itr->second.uState != ACTIONBUTTON_DELETED)
data << uint32(itr->second.packedData);
else
data << uint32(0);
}
}
GetSession()->SendPacket( &data );
DETAIL_LOG( "Action Buttons for '%u' spec '%u' Initialized", GetGUIDLow(), m_activeSpec );
}
void Player::SendLockActionButtons() const
{
DETAIL_LOG( "Locking Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec);
WorldPacket data(SMSG_ACTION_BUTTONS, 1);
// sending 2 locks actions bars, neither user can remove buttons, nor client removes buttons at spell unlearn
// they remain locked until server sends new action buttons
data << uint8(2);
GetSession()->SendPacket( &data );
}
bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player, bool msg)
{
if (button >= MAX_ACTION_BUTTONS)
{
if (msg)
{
if (player)
sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS );
else
sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS );
}
return false;
}
if (action >= MAX_ACTION_BUTTON_ACTION_VALUE)
{
if (msg)
{
if (player)
sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
else
sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE );
}
return false;
}
switch(type)
{
case ACTION_BUTTON_SPELL:
{
SpellEntry const* spellProto = sSpellStore.LookupEntry(action);
if(!spellProto)
{
if (msg)
{
if (player)
sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() );
else
sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button );
}
return false;
}
if (player)
{
if(!player->HasSpell(spellProto->Id))
{
if (msg)
sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() );
return false;
}
else if (IsPassiveSpell(spellProto))
{
if (msg)
sLog.outError( "Spell action %u not added into button %u for player %s: spell is passive", action, button, player->GetName() );
return false;
}
// current range for button of totem bar is from ACTION_BUTTON_SHAMAN_TOTEMS_BAR to (but not including) ACTION_BUTTON_SHAMAN_TOTEMS_BAR + 12
else if (button >= ACTION_BUTTON_SHAMAN_TOTEMS_BAR && button < (ACTION_BUTTON_SHAMAN_TOTEMS_BAR + 12)
&& !(spellProto->AttributesEx7 & SPELL_ATTR_EX7_TOTEM_SPELL))
{
if (msg)
sLog.outError( "Spell action %u not added into button %u for player %s: attempt to add non totem spell to totem bar", action, button, player->GetName() );
return false;
}
}
break;
}
case ACTION_BUTTON_ITEM:
{
if(!ObjectMgr::GetItemPrototype(action))
{
if (msg)
{
if (player)
sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() );
else
sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button );
}
return false;
}
break;
}
default:
break; // other cases not checked at this moment
}
return true;
}
ActionButton* Player::addActionButton(uint8 spec, uint8 button, uint32 action, uint8 type)
{
// check action only for active spec (so not check at copy/load passive spec)
if (spec == GetActiveSpec() && !IsActionButtonDataValid(button,action,type,this))
return NULL;
// it create new button (NEW state) if need or return existing
ActionButton& ab = m_actionButtons[spec][button];
// set data and update to CHANGED if not NEW
ab.SetActionAndType(action,ActionButtonType(type));
DETAIL_LOG("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action, uint32(type), button, spec);
return &ab;
}
void Player::removeActionButton(uint8 spec, uint8 button)
{
ActionButtonList& currentActionButtonList = m_actionButtons[spec];
ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
if (buttonItr == currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
return;
if (buttonItr->second.uState == ACTIONBUTTON_NEW)
currentActionButtonList.erase(buttonItr); // new and not saved
else
buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
DETAIL_LOG("Action Button '%u' Removed from Player '%u' for spec %u", button, GetGUIDLow(), spec);
}
ActionButton const* Player::GetActionButton(uint8 button)
{
ActionButtonList& currentActionButtonList = m_actionButtons[m_activeSpec];
ActionButtonList::iterator buttonItr = currentActionButtonList.find(button);
if (buttonItr==currentActionButtonList.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
return NULL;
return &buttonItr->second;
}
bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
{
if (!Unit::SetPosition(x, y, z, orientation, teleport))
return false;
// group update
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
if (GetTrader() && !IsWithinDistInMap(GetTrader(), INTERACTION_DISTANCE))
GetSession()->SendCancelTrade(); // will close both side trade windows
// code block for underwater state update
UpdateUnderwaterState(GetMap(), x, y, z);
CheckAreaExploreAndOutdoor();
return true;
}
void Player::SaveRecallPosition()
{
m_recallMap = GetMapId();
m_recallX = GetPositionX();
m_recallY = GetPositionY();
m_recallZ = GetPositionZ();
m_recallO = GetOrientation();
}
void Player::SendMessageToSet(WorldPacket *data, bool self)
{
if (IsInWorld())
GetMap()->MessageBroadcast(this, data, false);
//if player is not in world and map in not created/already destroyed
//no need to create one, just send packet for itself!
if (self)
GetSession()->SendPacket(data);
}
void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
{
if (IsInWorld())
GetMap()->MessageDistBroadcast(this, data, dist, false);
if (self)
GetSession()->SendPacket(data);
}
void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
{
if (IsInWorld())
GetMap()->MessageDistBroadcast(this, data, dist, false, own_team_only);
if (self)
GetSession()->SendPacket(data);
}
void Player::SendDirectMessage(WorldPacket *data)
{
GetSession()->SendPacket(data);
}
void Player::SendCinematicStart(uint32 CinematicSequenceId)
{
WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
data << uint32(CinematicSequenceId);
SendDirectMessage(&data);
}
void Player::SendMovieStart(uint32 MovieId)
{
WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
data << uint32(MovieId);
SendDirectMessage(&data);
}
void Player::CheckAreaExploreAndOutdoor()
{
if (!isAlive())
return;
if (IsTaxiFlying() || !GetMap())
return;
bool isOutdoor;
uint16 areaFlag = GetTerrain()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ(), &isOutdoor);
if (isOutdoor)
{
if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && GetRestType() == REST_TYPE_IN_TAVERN)
{
AreaTriggerEntry const* at = sAreaTriggerStore.LookupEntry(inn_trigger_id);
if (!at || !IsPointInAreaTriggerZone(at, GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ()))
{
// Player left inn (REST_TYPE_IN_CITY overrides REST_TYPE_IN_TAVERN, so just clear rest)
SetRestType(REST_TYPE_NO);
}
}
}
else if (sWorld.getConfig(CONFIG_BOOL_VMAP_INDOOR_CHECK) && !isGameMaster())
RemoveAurasWithAttribute(SPELL_ATTR_OUTDOORS_ONLY);
if (areaFlag==0xffff)
return;
int offset = areaFlag / 32;
if (offset >= PLAYER_EXPLORED_ZONES_SIZE)
{
sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < %u ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset, PLAYER_EXPLORED_ZONES_SIZE);
return;
}
uint32 val = (uint32)(1 << (areaFlag % 32));
uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
if (!(currFields & val))
{
SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
if(!p)
{
sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
}
else if (p->area_level > 0)
{
uint32 area = p->ID;
if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
{
SendExplorationExperience(area,0);
}
else
{
int32 diff = int32(getLevel()) - p->area_level;
uint32 XP = 0;
if (diff < -5)
{
XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
}
else if (diff > 5)
{
int32 exploration_percent = (100-((diff-5)*5));
if (exploration_percent > 100)
exploration_percent = 100;
else if (exploration_percent < 0)
exploration_percent = 0;
XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
}
else
{
XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE));
}
XP = uint32(XP * (GetSession()->IsPremium() + 1));
GiveXP( XP, NULL );
SendExplorationExperience(area,XP);
}
DETAIL_LOG("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
}
}
}
Team Player::TeamForRace(uint8 race)
{
ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
if (!rEntry)
{
sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
return ALLIANCE;
}
switch(rEntry->TeamID)
{
case 7: return ALLIANCE;
case 1: return HORDE;
}
sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
return TEAM_NONE;
}
uint32 Player::getFactionForRace(uint8 race)
{
ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
if(!rEntry)
{
sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
return 0;
}
return rEntry->FactionID;
}
void Player::setFactionForRace(uint8 race)
{
m_team = TeamForRace(race);
setFaction(getFactionForRace(race));
}
ReputationRank Player::GetReputationRank(uint32 faction) const
{
FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
return GetReputationMgr().GetRank(factionEntry);
}
//Calculate total reputation percent player gain with quest/creature level
int32 Player::CalculateReputationGain(ReputationSource source, int32 rep, int32 faction, uint32 creatureOrQuestLevel, bool noAuraBonus)
{
float percent = 100.0f;
float repMod = noAuraBonus ? 0.0f : (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
// faction specific auras only seem to apply to kills
if (source == REPUTATION_SOURCE_KILL)
repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
percent += rep > 0 ? repMod : -repMod;
float rate;
switch (source)
{
case REPUTATION_SOURCE_KILL:
rate = sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL);
break;
case REPUTATION_SOURCE_QUEST:
rate = sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST);
break;
case REPUTATION_SOURCE_SPELL:
default:
rate = 1.0f;
break;
}
if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
percent *= rate;
if (percent <= 0.0f)
return 0;
// Multiply result with the faction specific rate
if (const RepRewardRate *repData = sObjectMgr.GetRepRewardRate(faction))
{
float repRate = 0.0f;
switch (source)
{
case REPUTATION_SOURCE_KILL:
repRate = repData->creature_rate;
break;
case REPUTATION_SOURCE_QUEST:
repRate = repData->quest_rate;
break;
case REPUTATION_SOURCE_SPELL:
repRate = repData->spell_rate;
break;
}
// for custom, a rate of 0.0 will totally disable reputation gain for this faction/type
if (repRate <= 0.0f)
return 0;
percent *= repRate;
}
if (CheckRAFConditions())
{
percent *= sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_XP);
}
return int32(sWorld.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN)*rep*percent/100.0f);
}
//Calculates how many reputation points player gains in victim's enemy factions
void Player::RewardReputation(Unit *pVictim, float rate)
{
if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
return;
// used current difficulty creature entry instead normal version (GetEntry())
ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKillEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
if(!Rep)
return;
uint32 Repfaction1 = Rep->repfaction1;
uint32 Repfaction2 = Rep->repfaction2;
uint32 tabardFactionID = 0;
// Championning tabard reputation system
if (HasAura(Rep->championingAura))
{
if ( Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_TABARD ) )
{
if ( tabardFactionID = pItem->GetProto()->RequiredReputationFaction )
{
Repfaction1 = tabardFactionID;
Repfaction2 = tabardFactionID;
}
}
}
if (Repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
{
int32 donerep1 = CalculateReputationGain(REPUTATION_SOURCE_KILL, Rep->repvalue1, Repfaction1, pVictim->getLevel());
donerep1 = int32(donerep1*rate);
FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Repfaction1);
uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
// Wiki: Team factions value divided by 2
if (factionEntry1 && Rep->is_teamaward1)
{
FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
if (team1_factionEntry)
GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
}
}
if (Repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
{
int32 donerep2 = CalculateReputationGain(REPUTATION_SOURCE_KILL, Rep->repvalue2, Repfaction2, pVictim->getLevel());
donerep2 = int32(donerep2*rate);
FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Repfaction2);
uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
// Wiki: Team factions value divided by 2
if (factionEntry2 && Rep->is_teamaward2)
{
FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
if (team2_factionEntry)
GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
}
}
}
//Calculate how many reputation points player gain with the quest
void Player::RewardReputation(Quest const *pQuest)
{
// quest reputation reward/loss
for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
{
if (!pQuest->RewRepFaction[i])
continue;
// No diplomacy mod are applied to the final value (flat). Note the formula (finalValue = DBvalue/100)
if (pQuest->RewRepValue[i])
{
int32 rep = CalculateReputationGain(REPUTATION_SOURCE_QUEST, pQuest->RewRepValue[i]/100, pQuest->RewRepFaction[i], GetQuestLevelForPlayer(pQuest), true);
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
GetReputationMgr().ModifyReputation(factionEntry, rep);
}
else
{
uint32 row = ((pQuest->RewRepValueId[i] < 0) ? 1 : 0) + 1;
uint32 field = abs(pQuest->RewRepValueId[i]);
if (const QuestFactionRewardEntry *pRow = sQuestFactionRewardStore.LookupEntry(row))
{
int32 repPoints = pRow->rewardValue[field];
if (!repPoints)
continue;
repPoints = CalculateReputationGain(REPUTATION_SOURCE_QUEST, repPoints, pQuest->RewRepFaction[i], GetQuestLevelForPlayer(pQuest));
if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]))
GetReputationMgr().ModifyReputation(factionEntry, repPoints);
}
}
}
// TODO: implement reputation spillover
}
void Player::UpdateArenaFields(void)
{
/* arena calcs go here */
}
void Player::UpdateHonorFields()
{
/// called when rewarding honor and at each save
time_t now = time(NULL);
time_t today = (time(NULL) / DAY) * DAY;
if (m_lastHonorUpdateTime < today)
{
time_t yesterday = today - DAY;
uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
// update yesterday's contribution
if (m_lastHonorUpdateTime >= yesterday )
{
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
// this is the first update today, reset today's contribution
SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
}
else
{
// no honor/kills yesterday or today, reset
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
SetUInt32Value(PLAYER_FIELD_KILLS, 0);
}
}
m_lastHonorUpdateTime = now;
// START custom PvP Honor Kills Title System
if (sWorld.getConfig(CONFIG_BOOL_ALLOW_HONOR_KILLS_TITLES))
{
uint32 HonorKills = GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS);
uint32 victim_rank = 0;
// lets check if player fits to title brackets (none of players reached by now 50k HK. this is bad condition in aspect
// of making code generic, but allows to save some CPU and avoid fourther steps execution
if (HonorKills < 100 || HonorKills > 50000)
return;
if (HonorKills >= 100 && HonorKills < 200)
victim_rank = 1;
else if (HonorKills >= 200 && HonorKills < 500)
victim_rank = 2;
else if (HonorKills >= 500 && HonorKills < 1000)
victim_rank = 3;
else if (HonorKills >= 1000 && HonorKills < 2100)
victim_rank = 4;
else if (HonorKills >= 2100 && HonorKills < 3200)
victim_rank = 5;
else if (HonorKills >= 3200 && HonorKills < 4300)
victim_rank = 6;
else if (HonorKills >= 4300 && HonorKills < 5400)
victim_rank = 7;
else if (HonorKills >= 5400 && HonorKills < 6500)
victim_rank = 8;
else if (HonorKills >= 6500 && HonorKills < 7600)
victim_rank = 9;
else if (HonorKills >= 7600 && HonorKills < 9000)
victim_rank = 10;
else if (HonorKills >= 9000 && HonorKills < 15000)
victim_rank = 11;
else if (HonorKills >= 15000 && HonorKills < 30000)
victim_rank = 12;
else if (HonorKills >= 30000 && HonorKills < 50000)
victim_rank = 13;
else if (HonorKills == 50000)
victim_rank = 14;
// horde titles starting from 15+
if (GetTeam() == HORDE)
victim_rank += 14;
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(victim_rank))
{
// if player does have title there is no need to update fourther
if (!HasTitle(titleEntry))
{
// lets remove all previous ranks
for (uint8 i = 1; i < 29; ++i)
{
if (CharTitlesEntry const* title = sCharTitlesStore.LookupEntry(i))
{
if (HasTitle(title))
SetTitle(title, true);
}
}
// finaly apply and set as active new title
SetTitle(titleEntry);
SetUInt32Value(PLAYER_CHOSEN_TITLE, victim_rank);
}
}
}
// END custom PvP Honor Kills Title System
}
///Calculate the amount of honor gained based on the victim
///and the size of the group for which the honor is divided
///An exact honor value can also be given (overriding the calcs)
bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
{
// do not reward honor in arenas, but enable onkill spellproc
if (InArena())
{
if (!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
return false;
if (GetBGTeam() == ((Player*)uVictim)->GetBGTeam())
return false;
return true;
}
// 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
if (GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
return false;
ObjectGuid victim_guid;
uint32 victim_rank = 0;
// need call before fields update to have chance move yesterday data to appropriate fields before today data change.
UpdateHonorFields();
if (honor <= 0)
{
if (!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
return false;
victim_guid = uVictim->GetObjectGuid();
if (uVictim->GetTypeId() == TYPEID_PLAYER)
{
Player *pVictim = (Player *)uVictim;
if (GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm())
return false;
float f = 1; //need for total kills (?? need more info)
uint32 k_grey = 0;
uint32 k_level = getLevel();
uint32 v_level = pVictim->getLevel();
{
// PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
// [0] Just name
// [1..14] Alliance honor titles and player name
// [15..28] Horde honor titles and player name
// [29..38] Other title and player name
// [39+] Nothing
uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
// Get Killer titles, CharTitlesEntry::bit_index
// Ranks:
// title[1..14] -> rank[5..18]
// title[15..28] -> rank[5..18]
// title[other] -> 0
if (victim_title == 0)
victim_guid.Clear(); // Don't show HK: <rank> message, only log.
else if (victim_title < 15)
victim_rank = victim_title + 4;
else if (victim_title < 29)
victim_rank = victim_title - 14 + 4;
else
victim_guid.Clear(); // Don't show HK: <rank> message, only log.
}
k_grey = MaNGOS::XP::GetGrayLevel(k_level);
if (v_level<=k_grey)
return false;
float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
int32 v_rank =1; //need more info
honor = ((f * diff_level * (190 + v_rank*10))/6);
honor *= float(k_level) / 70.0f; //factor of dependence on levels of the killer
// count the number of playerkills in one day
ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
// and those in a lifetime
ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
}
else
{
Creature *cVictim = (Creature *)uVictim;
if (!cVictim->IsRacialLeader())
return false;
honor = 2000; // ??? need more info
victim_rank = 19; // HK: Leader
if (groupsize > 1)
honor *= groupsize;
}
}
if (uVictim != NULL)
{
honor *= sWorld.getConfig(CONFIG_FLOAT_RATE_HONOR);
honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
if (groupsize > 1)
honor /= groupsize;
honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
honor *= 2.0f; // as of 3.3.3 HK have had a 100% increase to honor
}
// honor - for show honor points in log
// victim_guid - for show victim name in log
// victim_rank [1..4] HK: <dishonored rank>
// victim_rank [5..19] HK: <alliance\horde rank>
// victim_rank [0,20+] HK: <>
WorldPacket data(SMSG_PVP_CREDIT, 4 + 8 + 4);
data << uint32(honor);
data << ObjectGuid(victim_guid);
data << uint32(victim_rank);
GetSession()->SendPacket(&data);
// add honor points
ModifyHonorPoints(int32(honor));
ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
return true;
}
void Player::SetHonorPoints(uint32 value)
{
if (value > sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS))
value = sWorld.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS);
SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, value);
}
void Player::SetArenaPoints(uint32 value)
{
if (value > sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS))
value = sWorld.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS);
SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, value);
}
void Player::ModifyHonorPoints(int32 value)
{
int32 newValue = (int32)GetHonorPoints() + value;
if (newValue < 0)
newValue = 0;
SetHonorPoints(newValue);
}
void Player::ModifyArenaPoints(int32 value)
{
int32 newValue = (int32)GetArenaPoints() + value;
if (newValue < 0)
newValue = 0;
SetArenaPoints(newValue);
}
uint32 Player::GetGuildIdFromDB(ObjectGuid guid)
{
uint32 lowguid = guid.GetCounter();
QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", lowguid);
if (!result)
return 0;
uint32 id = result->Fetch()[0].GetUInt32();
delete result;
return id;
}
uint32 Player::GetRankFromDB(ObjectGuid guid)
{
QueryResult *result = CharacterDatabase.PQuery("SELECT rank FROM guild_member WHERE guid='%u'", guid.GetCounter());
if (result)
{
uint32 v = result->Fetch()[0].GetUInt32();
delete result;
return v;
}
else
return 0;
}
uint32 Player::GetArenaTeamIdFromDB(ObjectGuid guid, ArenaType type)
{
QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", guid.GetCounter(), type);
if (!result)
return 0;
uint32 id = (*result)[0].GetUInt32();
delete result;
return id;
}
uint32 Player::GetZoneIdFromDB(ObjectGuid guid)
{
uint32 lowguid = guid.GetCounter();
QueryResult *result = CharacterDatabase.PQuery("SELECT zone FROM characters WHERE guid='%u'", lowguid);
if (!result)
return 0;
Field* fields = result->Fetch();
uint32 zone = fields[0].GetUInt32();
delete result;
if (!zone)
{
// stored zone is zero, use generic and slow zone detection
result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", lowguid);
if ( !result )
return 0;
fields = result->Fetch();
uint32 map = fields[0].GetUInt32();
float posx = fields[1].GetFloat();
float posy = fields[2].GetFloat();
float posz = fields[3].GetFloat();
delete result;
zone = sTerrainMgr.GetZoneId(map,posx,posy,posz);
if (zone > 0)
CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, lowguid);
}
return zone;
}
uint32 Player::GetLevelFromDB(ObjectGuid guid)
{
uint32 lowguid = guid.GetCounter();
QueryResult *result = CharacterDatabase.PQuery("SELECT level FROM characters WHERE guid='%u'", lowguid);
if (!result)
return 0;
Field* fields = result->Fetch();
uint32 level = fields[0].GetUInt32();
delete result;
return level;
}
void Player::UpdateArea(uint32 newArea)
{
m_areaUpdateId = newArea;
AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
// FFA_PVP flags are area and not zone id dependent
// so apply them accordingly
if (area && (area->flags & AREA_FLAG_ARENA))
{
if (!isGameMaster())
SetFFAPvP(true);
}
else
{
// remove ffa flag only if not ffapvp realm
// removal in sanctuaries and capitals is handled in zone update
if (IsFFAPvP() && !sWorld.IsFFAPvPRealm())
SetFFAPvP(false);
}
if (area)
{
// Dalaran restricted flight zone
if ((area->flags & AREA_FLAG_CANNOT_FLY) && IsFreeFlying() && !isGameMaster() && !HasAura(58600))
CastSpell(this, 58600, true); // Restricted Flight Area
// TODO: implement wintergrasp parachute when battle in progress
/* if ((area->flags & AREA_FLAG_OUTDOOR_PVP) && IsFreeFlying() && <WINTERGRASP_BATTLE_IN_PROGRESS> && !isGameMaster())
CastSpell(this, 58730, true); */
}
UpdateAreaDependentAuras();
}
WorldPvP* Player::GetWorldPvP() const
{
return sWorldPvPMgr.GetWorldPvPToZoneId(GetZoneId());
}
bool Player::IsWorldPvPActive()
{
return CanCaptureTowerPoint() &&
(IsPvP() || sWorld.IsPvPRealm()) &&
!HasMovementFlag(MOVEFLAG_FLYING) &&
!IsTaxiFlying() &&
!isGameMaster();
}
void Player::UpdateZone(uint32 newZone, uint32 newArea)
{
AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
if(!zone)
return;
if (m_zoneUpdateId != newZone)
{
//Called when a player leave zone
if (InstanceData* mapInstance = GetInstanceData())
mapInstance->OnPlayerLeaveZone(this, m_zoneUpdateId);
// handle world pvp zones
sWorldPvPMgr.HandlePlayerLeaveZone(this, m_zoneUpdateId);
SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
sWorldPvPMgr.HandlePlayerEnterZone(this, newZone);
// call this method in order to handle some scripted zones
if (InstanceData* mapInstance = GetInstanceData())
mapInstance->OnPlayerEnterZone(this, newZone, newArea);
if (sWorld.getConfig(CONFIG_BOOL_WEATHER))
{
if (Weather *wth = sWorld.FindWeather(zone->ID))
wth->SendWeatherUpdateToPlayer(this);
else if(!sWorld.AddWeather(zone->ID))
{
// send fine weather packet to remove old zone's weather
Weather::SendFineWeatherUpdateToPlayer(this);
}
}
}
m_zoneUpdateId = newZone;
m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
// zone changed, so area changed as well, update it
UpdateArea(newArea);
// in PvP, any not controlled zone (except zone->team == 6, default case)
// in PvE, only opposition team capital
switch(zone->team)
{
case AREATEAM_ALLY:
pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
break;
case AREATEAM_HORDE:
pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
break;
case AREATEAM_NONE:
// overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
break;
default: // 6 in fact
pvpInfo.inHostileArea = false;
break;
}
if (pvpInfo.inHostileArea) // in hostile area
{
if(!IsPvP() || pvpInfo.endTimer != 0)
UpdatePvP(true, true);
}
else // in friendly area
{
if (IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
pvpInfo.endTimer = time(0); // start toggle-off
}
if (zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
{
SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
if (sWorld.IsFFAPvPRealm())
SetFFAPvP(false);
}
else
{
RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
}
if (zone->flags & AREA_FLAG_CAPITAL) // in capital city
SetRestType(REST_TYPE_IN_CITY);
else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && GetRestType() != REST_TYPE_IN_TAVERN)
// resting and not in tavern (leave city then); tavern leave handled in CheckAreaExploreAndOutdoor
SetRestType(REST_TYPE_NO);
// remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
// if player resurrected at teleport this will be applied in resurrect code
if (isAlive())
DestroyZoneLimitedItem( true, newZone );
// check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
AutoUnequipOffhandIfNeed();
// recent client version not send leave/join channel packets for built-in local channels
UpdateLocalChannels( newZone );
// group update
if (GetGroup())
SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
UpdateZoneDependentAuras();
UpdateZoneDependentPets();
}
//If players are too far way of duel flag... then player loose the duel
void Player::CheckDuelDistance(time_t currTime)
{
if (!duel)
return;
GameObject* obj = GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER));
if (!obj)
{
// player not at duel start map
DuelComplete(DUEL_FLED);
return;
}
if (duel->outOfBound == 0)
{
if (!IsWithinDistInMap(obj, 50))
{
duel->outOfBound = currTime;
WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
GetSession()->SendPacket(&data);
}
}
else
{
if (IsWithinDistInMap(obj, 40))
{
duel->outOfBound = 0;
WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
GetSession()->SendPacket(&data);
}
else if (currTime >= (duel->outOfBound+10))
{
DuelComplete(DUEL_FLED);
}
}
}
void Player::DuelComplete(DuelCompleteType type)
{
// duel not requested
if (!duel)
return;
WorldPacket data(SMSG_DUEL_COMPLETE, (1));
data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
GetSession()->SendPacket(&data);
duel->opponent->GetSession()->SendPacket(&data);
if (type != DUEL_INTERUPTED)
{
data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
data << duel->opponent->GetName();
data << GetName();
SendMessageToSet(&data,true);
}
if (type == DUEL_WON)
{
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
if (duel->opponent)
duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
}
//Remove Duel Flag object
if (GameObject* obj = GetMap()->GetGameObject(GetGuidValue(PLAYER_DUEL_ARBITER)))
duel->initiator->RemoveGameObject(obj, true);
/* remove auras */
std::vector<uint32> auras2remove;
SpellAuraHolderMap const& vAuras = duel->opponent->GetSpellAuraHolderMap();
for (SpellAuraHolderMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
{
if (!i->second->IsPositive() && i->second->GetCasterGuid() == GetObjectGuid() && i->second->GetAuraApplyTime() >= duel->startTime)
auras2remove.push_back(i->second->GetId());
}
for(size_t i=0; i<auras2remove.size(); ++i)
duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
auras2remove.clear();
SpellAuraHolderMap const& auras = GetSpellAuraHolderMap();
for (SpellAuraHolderMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
{
if (!i->second->IsPositive() && i->second->GetCasterGuid() == duel->opponent->GetObjectGuid() && i->second->GetAuraApplyTime() >= duel->startTime)
auras2remove.push_back(i->second->GetId());
}
for (size_t i=0; i<auras2remove.size(); ++i)
RemoveAurasDueToSpell(auras2remove[i]);
// cleanup combo points
if (GetComboTargetGuid() == duel->opponent->GetObjectGuid())
ClearComboPoints();
else if (GetComboTargetGuid() == duel->opponent->GetPetGuid())
ClearComboPoints();
if (duel->opponent->GetComboTargetGuid() == GetObjectGuid())
duel->opponent->ClearComboPoints();
else if (duel->opponent->GetComboTargetGuid() == GetPetGuid())
duel->opponent->ClearComboPoints();
//cleanups
SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid());
SetUInt32Value(PLAYER_DUEL_TEAM, 0);
duel->opponent->SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid());
duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
delete duel->opponent->duel;
duel->opponent->duel = NULL;
delete duel;
duel = NULL;
}
//---------------------------------------------------------//
void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
{
if (slot >= INVENTORY_SLOT_BAG_END || !item)
return;
// not apply/remove mods for broken item
if (item->IsBroken())
return;
ItemPrototype const *proto = item->GetProto();
if(!proto)
return;
DETAIL_LOG("applying mods for item %u ",item->GetGUIDLow());
uint32 attacktype = Player::GetAttackBySlot(slot);
if (attacktype < MAX_ATTACK)
_ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
_ApplyItemBonuses(proto,slot,apply);
if ( slot==EQUIPMENT_SLOT_RANGED )
_ApplyAmmoBonuses();
ApplyItemEquipSpell(item,apply);
ApplyEnchantment(item, apply);
if (proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
CorrectMetaGemEnchants(slot, apply);
DEBUG_LOG("_ApplyItemMods complete.");
}
void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
{
if (slot >= INVENTORY_SLOT_BAG_END || !proto)
return;
ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
if (only_level_scale && !ssd)
return;
// req. check at equip, but allow use for extended range if range limit max level, set proper level
uint32 ssd_level = getLevel();
if (ssd && ssd_level > ssd->MaxLevel)
ssd_level = ssd->MaxLevel;
ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
if (only_level_scale && !ssv)
return;
for (uint32 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
{
uint32 statType = 0;
int32 val = 0;
// If set ScalingStatDistribution need get stats and values from it
if (ssd && ssv)
{
if (ssd->StatMod[i] < 0)
continue;
statType = ssd->StatMod[i];
val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
}
else
{
if (i >= proto->StatsCount)
continue;
statType = proto->ItemStat[i].ItemStatType;
val = proto->ItemStat[i].ItemStatValue;
}
if (val == 0)
continue;
switch (statType)
{
case ITEM_MOD_MANA:
HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
break;
case ITEM_MOD_HEALTH: // modify HP
HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
break;
case ITEM_MOD_AGILITY: // modify agility
HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
break;
case ITEM_MOD_STRENGTH: //modify strength
HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
break;
case ITEM_MOD_INTELLECT: //modify intellect
HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
break;
case ITEM_MOD_SPIRIT: //modify spirit
HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
break;
case ITEM_MOD_STAMINA: //modify stamina
HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
break;
case ITEM_MOD_DEFENSE_SKILL_RATING:
ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
break;
case ITEM_MOD_DODGE_RATING:
ApplyRatingMod(CR_DODGE, int32(val), apply);
break;
case ITEM_MOD_PARRY_RATING:
ApplyRatingMod(CR_PARRY, int32(val), apply);
break;
case ITEM_MOD_BLOCK_RATING:
ApplyRatingMod(CR_BLOCK, int32(val), apply);
break;
case ITEM_MOD_HIT_MELEE_RATING:
ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
break;
case ITEM_MOD_HIT_RANGED_RATING:
ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
break;
case ITEM_MOD_HIT_SPELL_RATING:
ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_MELEE_RATING:
ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
break;
case ITEM_MOD_CRIT_RANGED_RATING:
ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
break;
case ITEM_MOD_CRIT_SPELL_RATING:
ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_HASTE_MELEE_RATING:
ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
break;
case ITEM_MOD_HASTE_RANGED_RATING:
ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
break;
case ITEM_MOD_HASTE_SPELL_RATING:
ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
break;
case ITEM_MOD_HIT_RATING:
ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_RATING:
ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
break;
case ITEM_MOD_HIT_TAKEN_RATING:
ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_CRIT_TAKEN_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_RESILIENCE_RATING:
ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
break;
case ITEM_MOD_HASTE_RATING:
ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
break;
case ITEM_MOD_EXPERTISE_RATING:
ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
break;
case ITEM_MOD_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
break;
case ITEM_MOD_RANGED_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
break;
case ITEM_MOD_MANA_REGENERATION:
ApplyManaRegenBonus(int32(val), apply);
break;
case ITEM_MOD_ARMOR_PENETRATION_RATING:
ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
break;
case ITEM_MOD_SPELL_POWER:
ApplySpellPowerBonus(int32(val), apply);
break;
case ITEM_MOD_HEALTH_REGEN:
ApplyHealthRegenBonus(int32(val), apply);
break;
case ITEM_MOD_SPELL_PENETRATION:
ApplyModInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, -int32(val), apply);
m_spellPenetrationItemMod += apply ? val : -val;
break;
case ITEM_MOD_BLOCK_VALUE:
HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(val), apply);
break;
// deprecated item mods
case ITEM_MOD_FERAL_ATTACK_POWER:
case ITEM_MOD_SPELL_HEALING_DONE:
case ITEM_MOD_SPELL_DAMAGE_DONE:
break;
}
}
// Apply Spell Power from ScalingStatValue if set
if (ssv)
{
if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
ApplySpellPowerBonus(spellbonus, apply);
}
// If set ScalingStatValue armor get it or use item armor
uint32 armor = proto->Armor;
if (ssv)
{
if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
armor = ssvarmor;
}
// Add armor bonus from ArmorDamageModifier if > 0
if (proto->ArmorDamageModifier > 0)
armor += uint32(proto->ArmorDamageModifier);
if (armor)
{
switch(proto->InventoryType)
{
case INVTYPE_TRINKET:
case INVTYPE_NECK:
case INVTYPE_CLOAK:
case INVTYPE_FINGER:
HandleStatModifier(UNIT_MOD_ARMOR, TOTAL_VALUE, float(armor), apply);
break;
default:
HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
break;
}
}
if (proto->Block)
HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
if (proto->HolyRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
if (proto->FireRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
if (proto->NatureRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
if (proto->FrostRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
if (proto->ShadowRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
if (proto->ArcaneRes)
HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
WeaponAttackType attType = BASE_ATTACK;
float damage = 0.0f;
if ( slot == EQUIPMENT_SLOT_RANGED && (
proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
proto->InventoryType == INVTYPE_RANGEDRIGHT ))
{
attType = RANGED_ATTACK;
}
else if (slot==EQUIPMENT_SLOT_OFFHAND)
{
attType = OFF_ATTACK;
}
float minDamage = proto->Damage[0].DamageMin;
float maxDamage = proto->Damage[0].DamageMax;
int32 extraDPS = 0;
// If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
if (ssv)
{
if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
{
float average = extraDPS * proto->Delay / 1000.0f;
minDamage = 0.7f * average;
maxDamage = 1.3f * average;
}
}
if (minDamage > 0 )
{
damage = apply ? minDamage : BASE_MINDAMAGE;
SetBaseWeaponDamage(attType, MINDAMAGE, damage);
//sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
}
if (maxDamage > 0 )
{
damage = apply ? maxDamage : BASE_MAXDAMAGE;
SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
}
// Apply feral bonus from ScalingStatValue if set
if (ssv)
{
if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
ApplyFeralAPBonus(feral_bonus, apply);
}
// Druids get feral AP bonus from weapon dps (also use DPS from ScalingStatValue)
if (getClass() == CLASS_DRUID)
{
int32 feral_bonus = proto->getFeralBonus(extraDPS);
if (feral_bonus > 0)
ApplyFeralAPBonus(feral_bonus, apply);
}
if (!CanUseEquippedWeapon(attType))
return;
if (proto->Delay)
{
if (slot == EQUIPMENT_SLOT_RANGED)
SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
else if (slot==EQUIPMENT_SLOT_MAINHAND)
SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
else if (slot==EQUIPMENT_SLOT_OFFHAND)
SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
}
if (CanModifyStats() && (damage || proto->Delay))
UpdateDamagePhysical(attType);
}
void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
{
MAPLOCK_READ(this,MAP_LOCK_TYPE_AURAS);
AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
_ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
_ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
_ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
}
void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
{
// generic not weapon specific case processes in aura code
if (aura->GetSpellProto()->EquippedItemClass == -1)
return;
BaseModGroup mod = BASEMOD_END;
switch(attackType)
{
case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
default: return;
}
if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto()))
{
HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
}
}
void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
{
// ignore spell mods for not wands
Modifier const* modifier = aura->GetModifier();
if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
return;
// generic not weapon specific case processes in aura code
if (aura->GetSpellProto()->EquippedItemClass == -1)
return;
UnitMods unitMod = UNIT_MOD_END;
switch(attackType)
{
case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
default: return;
}
UnitModifierType unitModType = TOTAL_VALUE;
switch(modifier->m_auraname)
{
case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
default: return;
}
if (!item->IsBroken()&&item->IsFitToSpellRequirements(aura->GetSpellProto()))
{
HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
}
}
void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
{
if(!item)
return;
ItemPrototype const *proto = item->GetProto();
if(!proto)
return;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if(!spellData.SpellId )
continue;
if (apply)
{
// apply only at-equip spells
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
continue;
}
else
{
// at un-apply remove all spells (not only at-apply, so any at-use active affects from item and etc)
// except with at-use with negative charges, so allow consuming item spells (including with extra flag that prevent consume really)
// applied to player after item remove from equip slot
if (spellData.SpellTrigger == ITEM_SPELLTRIGGER_ON_USE && spellData.SpellCharges < 0)
continue;
}
// check if it is valid spell
SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
if(!spellproto)
continue;
ApplyEquipSpell(spellproto,item,apply,form_change);
}
}
void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
{
if (apply)
{
// Cannot be used in this stance/form
if (GetErrorAtShapeshiftedCast(spellInfo, GetShapeshiftForm()) != SPELL_CAST_OK)
return;
if (form_change) // check aura active state from other form
{
bool found = false;
for (int k=0; k < MAX_EFFECT_INDEX; ++k)
{
SpellAuraHolderBounds spair = GetSpellAuraHolderBounds(spellInfo->Id);
for (SpellAuraHolderMap::const_iterator iter = spair.first; iter != spair.second; ++iter)
{
if(!item || iter->second->GetCastItemGuid() == item->GetObjectGuid())
{
found = true;
break;
}
}
if (found)
break;
}
if (found) // and skip re-cast already active aura at form change
return;
}
DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
CastSpell(this,spellInfo,true,item);
}
else
{
if (form_change) // check aura compatibility
{
// Cannot be used in this stance/form
if (GetErrorAtShapeshiftedCast(spellInfo, GetShapeshiftForm()) == SPELL_CAST_OK)
return; // and remove only not compatible at form change
}
if (item)
RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
else
RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
}
}
void Player::UpdateEquipSpellsAtFormChange()
{
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i] && !m_items[i]->IsBroken())
{
ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
}
}
// item set bonuses not dependent from item broken state
for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
{
ItemSetEffect* eff = ItemSetEff[setindex];
if(!eff)
continue;
for(uint32 y=0;y<8; ++y)
{
SpellEntry const* spellInfo = eff->spells[y];
if(!spellInfo)
continue;
ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
}
}
}
/**
* (un-)Apply item spells triggered at adding item to inventory ITEM_SPELLTRIGGER_ON_STORE
*
* @param item added/removed item to/from inventory
* @param apply (un-)apply spell affects.
*
* Note: item moved from slot to slot in 2 steps RemoveItem and StoreItem/EquipItem
* In result function not called in RemoveItem for prevent unexpected re-apply auras from related spells
* with duration reset and etc. Instead unapply done in StoreItem/EquipItem and in specialized
* functions for item final remove/destroy from inventory. If new RemoveItem calls added need be sure that
* function will call after it in some way if need.
*/
void Player::ApplyItemOnStoreSpell(Item *item, bool apply)
{
if (!item)
return;
ItemPrototype const *proto = item->GetProto();
if (!proto)
return;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if (!spellData.SpellId)
continue;
// apply/unapply only at-store spells
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_STORE)
continue;
if (apply)
{
// can be attempt re-applied at move in inventory slots
if (!HasAura(spellData.SpellId))
CastSpell(this, spellData.SpellId, true, item);
}
else
RemoveAurasDueToItemSpell(item, spellData.SpellId);
}
}
void Player::DestroyItemWithOnStoreSpell(Item* item, uint32 spellId)
{
if (!item)
return;
ItemPrototype const *proto = item->GetProto();
if (!proto)
return;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
if (spellData.SpellId != spellId)
continue;
// apply/unapply only at-store spells
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_STORE)
continue;
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
break;
}
}
/// handles unique effect of Deadly Poison: apply poison of the other weapon when already at max. stack
void Player::_HandleDeadlyPoison(Unit* Target, WeaponAttackType attType, SpellEntry const *spellInfo)
{
SpellAuraHolderPtr dPoison = SpellAuraHolderPtr(NULL);
SpellAuraHolderConstBounds holders = Target->GetSpellAuraHolderBounds(spellInfo->Id);
for (SpellAuraHolderMap::const_iterator iter = holders.first; iter != holders.second; ++iter)
{
if (iter->second->GetCaster() == this)
{
dPoison = iter->second;
break;
}
}
if (dPoison && dPoison->GetStackAmount() == spellInfo->StackAmount)
{
Item *otherWeapon = GetWeaponForAttack(attType == BASE_ATTACK ? OFF_ATTACK : BASE_ATTACK );
if (!otherWeapon)
return;
// all poison enchantments are temporary
uint32 enchant_id = otherWeapon->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT);
if (!enchant_id)
return;
SpellItemEnchantmentEntry const* pSecondEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pSecondEnchant)
return;
for (int s = 0; s < 3; ++s)
{
if (pSecondEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
continue;
SpellEntry const* combatEntry = sSpellStore.LookupEntry(pSecondEnchant->spellid[s]);
if (combatEntry && combatEntry->Dispel == DISPEL_POISON)
CastSpell(Target, combatEntry, true, otherWeapon);
}
}
}
void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
{
Item *item = GetWeaponForAttack(attType, true, false);
if(!item)
return;
ItemPrototype const *proto = item->GetProto();
if(!proto)
return;
if (!Target || Target == this )
return;
for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if(!spellData.SpellId )
continue;
// wrong triggering type
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
if(!spellInfo)
{
sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
continue;
}
// not allow proc extra attack spell at extra attack
if ( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
return;
float chance = (float)spellInfo->procChance;
if (spellData.SpellPPMRate)
{
uint32 WeaponSpeed = proto->Delay;
chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
}
else if (chance > 100.0f)
{
chance = GetWeaponProcChance();
}
if (roll_chance_f(chance))
CastSpell(Target, spellInfo->Id, true, item);
}
// item combat enchantments
for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
{
uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!pEnchant) continue;
for (int s = 0; s < 3; ++s)
{
uint32 proc_spell_id = pEnchant->spellid[s];
if (pEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(proc_spell_id);
if (!spellInfo)
{
sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, proc_spell_id);
continue;
}
// Use first rank to access spell item enchant procs
float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id);
float chance = ppmRate
? GetPPMProcChance(proto->Delay, ppmRate)
: pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS, chance);
ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS, chance);
if (roll_chance_f(chance))
{
if (IsPositiveSpell(spellInfo->Id))
CastSpell(this, spellInfo->Id, true, item);
else
{
// Deadly Poison, unique effect needs to be handled before casting triggered spell
if (spellInfo->IsFitToFamily<SPELLFAMILY_ROGUE, CF_ROGUE_DEADLY_POISON>())
_HandleDeadlyPoison(Target, attType, spellInfo);
CastSpell(Target, spellInfo->Id, true, item);
}
}
}
}
}
void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
{
ItemPrototype const* proto = item->GetProto();
// special learning case
if (proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
{
uint32 learn_spell_id = proto->Spells[0].SpellId;
uint32 learning_spell_id = proto->Spells[1].SpellId;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
if (!spellInfo)
{
sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
SendEquipError(EQUIP_ERR_NONE, item);
return;
}
Spell *spell = new Spell(this, spellInfo, false);
spell->m_CastItem = item;
spell->m_cast_count = cast_count; //set count of casts
spell->m_currentBasePoints[EFFECT_INDEX_0] = learning_spell_id;
spell->prepare(&targets);
return;
}
// use triggered flag only for items with many spell casts and for not first cast
int count = 0;
// item spells casted at use
for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = proto->Spells[i];
// no spell
if (!spellData.SpellId)
continue;
// wrong triggering type
if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
if (!spellInfo)
{
sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
continue;
}
Spell *spell = new Spell(this, spellInfo, (count > 0));
spell->m_CastItem = item;
spell->m_cast_count = cast_count; // set count of casts
spell->m_glyphIndex = glyphIndex; // glyph index
spell->prepare(&targets);
++count;
}
// Item enchantments spells casted at use
for (int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
{
uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
continue;
for (int s = 0; s < 3; ++s)
{
if (pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
continue;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
if (!spellInfo)
{
sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
continue;
}
Spell *spell = new Spell(this, spellInfo, (count > 0));
spell->m_CastItem = item;
spell->m_cast_count = cast_count; // set count of casts
spell->m_glyphIndex = glyphIndex; // glyph index
spell->prepare(&targets);
++count;
}
}
}
void Player::_RemoveAllItemMods()
{
DEBUG_LOG("_RemoveAllItemMods start.");
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
// item set bonuses not dependent from item broken state
if (proto->ItemSet)
RemoveItemsSetItem(this,proto);
if (m_items[i]->IsBroken())
continue;
ApplyItemEquipSpell(m_items[i],false);
ApplyEnchantment(m_items[i], false);
}
}
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
if (m_items[i]->IsBroken())
continue;
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
uint32 attacktype = Player::GetAttackBySlot(i);
if (attacktype < MAX_ATTACK)
_ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
_ApplyItemBonuses(proto,i, false);
if ( i == EQUIPMENT_SLOT_RANGED )
_ApplyAmmoBonuses();
}
}
DEBUG_LOG("_RemoveAllItemMods complete.");
}
void Player::_ApplyAllItemMods()
{
DEBUG_LOG("_ApplyAllItemMods start.");
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
if (m_items[i]->IsBroken())
continue;
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
uint32 attacktype = Player::GetAttackBySlot(i);
if (attacktype < MAX_ATTACK)
_ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
_ApplyItemBonuses(proto,i, true);
if ( i == EQUIPMENT_SLOT_RANGED )
_ApplyAmmoBonuses();
}
}
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
// item set bonuses not dependent from item broken state
if (proto->ItemSet)
AddItemsSetItem(this,m_items[i]);
if (m_items[i]->IsBroken())
continue;
ApplyItemEquipSpell(m_items[i],true);
ApplyEnchantment(m_items[i], true);
}
}
DEBUG_LOG("_ApplyAllItemMods complete.");
}
void Player::_ApplyAllLevelScaleItemMods(bool apply)
{
for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (m_items[i])
{
if (m_items[i]->IsBroken())
continue;
ItemPrototype const *proto = m_items[i]->GetProto();
if(!proto)
continue;
_ApplyItemBonuses(proto,i, apply, true);
}
}
}
void Player::_ApplyAmmoBonuses()
{
// check ammo
uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
if(!ammo_id)
return;
float currentAmmoDPS;
ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
if ( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
currentAmmoDPS = 0.0f;
else
currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
if (currentAmmoDPS == GetAmmoDPS())
return;
m_ammoDPS = currentAmmoDPS;
if (CanModifyStats())
UpdateDamagePhysical(RANGED_ATTACK);
}
bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
{
if(!ammo_proto)
return false;
// check ranged weapon
Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false );
if (!weapon)
return false;
ItemPrototype const* weapon_proto = weapon->GetProto();
if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
return false;
// check ammo ws. weapon compatibility
switch(weapon_proto->SubClass)
{
case ITEM_SUBCLASS_WEAPON_BOW:
case ITEM_SUBCLASS_WEAPON_CROSSBOW:
if (ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
return false;
break;
case ITEM_SUBCLASS_WEAPON_GUN:
if (ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
return false;
break;
default:
return false;
}
return true;
}
/* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
Called by remove insignia spell effect */
void Player::RemovedInsignia(Player* looterPlr)
{
if (!GetBattleGroundId())
return;
// If not released spirit, do it !
if (m_deathTimer > 0)
{
m_deathTimer = 0;
BuildPlayerRepop();
RepopAtGraveyard();
}
Corpse *corpse = GetCorpse();
if (!corpse)
return;
// We have to convert player corpse to bones, not to be able to resurrect there
// SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid(), true);
if (!bones)
return;
// Now we must make bones lootable, and send player loot
bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
// We store the level of our player in the gold field
// We retrieve this information at Player::SendLoot()
bones->loot.gold = getLevel();
bones->lootRecipient = looterPlr;
looterPlr->SendLoot(bones->GetObjectGuid(), LOOT_INSIGNIA);
}
void Player::SendLootRelease(ObjectGuid guid)
{
WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
data << guid;
data << uint8(1);
SendDirectMessage( &data );
}
void Player::SendLoot(ObjectGuid guid, LootType loot_type)
{
if (ObjectGuid lootGuid = GetLootGuid())
m_session->DoLootRelease(lootGuid);
Loot* loot = NULL;
PermissionTypes permission = ALL_PERMISSION;
DEBUG_LOG("Player::SendLoot");
switch(guid.GetHigh())
{
case HIGHGUID_GAMEOBJECT:
{
DEBUG_LOG(" IS_GAMEOBJECT_GUID(guid)");
GameObject *go = GetMap()->GetGameObject(guid);
// not check distance for GO in case owned GO (fishing bobber case, for example)
// And permit out of range GO with no owner in case fishing hole
if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING && loot_type != LOOT_FISHING_FAIL || go->GetOwnerGuid() != GetObjectGuid()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
{
SendLootRelease(guid);
return;
}
loot = &go->loot;
Player* recipient = go->GetLootRecipient();
if (!recipient)
{
go->SetLootRecipient(this);
recipient = this;
}
// generate loot only if ready for open and spawned in world
if (go->getLootState() == GO_READY && go->isSpawned())
{
uint32 lootid = go->GetGOInfo()->GetLootId();
if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
if (BattleGround *bg = GetBattleGround())
if (bg->GetTypeID(true) == BATTLEGROUND_AV)
if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
{
SendLootRelease(guid);
return;
}
if (Group* group = this->GetGroup())
{
if (go->GetGoType() == GAMEOBJECT_TYPE_CHEST)
{
if (go->GetGOInfo()->chest.groupLootRules == 1 || sWorld.getConfig(CONFIG_BOOL_LOOT_CHESTS_IGNORE_DB))
{
group->UpdateLooterGuid(go,true);
switch (group->GetLootMethod())
{
case GROUP_LOOT:
// GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
group->GroupLoot(go, loot);
permission = GROUP_PERMISSION;
break;
case NEED_BEFORE_GREED:
group->NeedBeforeGreed(go, loot);
permission = GROUP_PERMISSION;
break;
case MASTER_LOOT:
group->MasterLoot(go, loot);
permission = MASTER_PERMISSION;
break;
default:
break;
}
}
else
permission = GROUP_PERMISSION;
}
}
// Entry 0 in fishing loot template used for store junk fish loot at fishing fail it junk allowed by config option
// this is overwrite fishinghole loot for example
if (loot_type == LOOT_FISHING_FAIL)
loot->FillLoot(0, LootTemplates_Fishing, this, true);
else if (lootid)
{
DEBUG_LOG(" if (lootid)");
loot->clear();
loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
loot->generateMoneyLoot(go->GetGOInfo()->MinMoneyLoot, go->GetGOInfo()->MaxMoneyLoot);
if (go->GetGoType() == GAMEOBJECT_TYPE_CHEST && go->GetGOInfo()->chest.groupLootRules)
{
if (Group* group = go->GetGroupLootRecipient())
{
group->UpdateLooterGuid(go, true);
switch (group->GetLootMethod())
{
case GROUP_LOOT:
// GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
group->GroupLoot(go, loot);
permission = GROUP_PERMISSION;
break;
case NEED_BEFORE_GREED:
group->NeedBeforeGreed(go, loot);
permission = GROUP_PERMISSION;
break;
case MASTER_LOOT:
group->MasterLoot(go, loot);
permission = MASTER_PERMISSION;
break;
default:
break;
}
}
}
}
else if (loot_type == LOOT_FISHING)
go->getFishLoot(loot,this);
go->SetLootState(GO_ACTIVATED);
}
if (go->getLootState() == GO_ACTIVATED &&
go->GetGoType() == GAMEOBJECT_TYPE_CHEST &&
(go->GetGOInfo()->chest.groupLootRules || sWorld.getConfig(CONFIG_BOOL_LOOT_CHESTS_IGNORE_DB)))
{
if (Group* group = go->GetGroupLootRecipient())
{
if (group == GetGroup())
{
if (group->GetLootMethod() == FREE_FOR_ALL)
permission = ALL_PERMISSION;
else if (group->GetLooterGuid() == GetObjectGuid())
{
if (group->GetLootMethod() == MASTER_LOOT)
permission = MASTER_PERMISSION;
else
permission = ALL_PERMISSION;
}
else
permission = GROUP_PERMISSION;
}
else
permission = NONE_PERMISSION;
}
else if (recipient == this)
permission = ALL_PERMISSION;
else
permission = NONE_PERMISSION;
}
break;
}
case HIGHGUID_ITEM:
{
Item *item = GetItemByGuid( guid );
if (!item)
{
SendLootRelease(guid);
return;
}
permission = OWNER_PERMISSION;
loot = &item->loot;
if (!item->HasGeneratedLoot())
{
item->loot.clear();
switch(loot_type)
{
case LOOT_DISENCHANTING:
loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this, true);
item->SetLootState(ITEM_LOOT_TEMPORARY);
break;
case LOOT_PROSPECTING:
loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this, true);
item->SetLootState(ITEM_LOOT_TEMPORARY);
break;
case LOOT_MILLING:
loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this, true);
item->SetLootState(ITEM_LOOT_TEMPORARY);
break;
default:
loot->FillLoot(item->GetEntry(), LootTemplates_Item, this, true, item->GetProto()->MaxMoneyLoot == 0);
loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot, item->GetProto()->MaxMoneyLoot);
item->SetLootState(ITEM_LOOT_CHANGED);
break;
}
}
break;
}
case HIGHGUID_CORPSE: // remove insignia
{
Corpse *bones = GetMap()->GetCorpse(guid);
if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
{
SendLootRelease(guid);
return;
}
loot = &bones->loot;
if (!bones->lootForBody)
{
bones->lootForBody = true;
uint32 pLevel = bones->loot.gold;
bones->loot.clear();
if (GetBattleGround() && GetBattleGround()->GetTypeID(true) == BATTLEGROUND_AV)
loot->FillLoot(0, LootTemplates_Creature, this, false);
// It may need a better formula
// Now it works like this: lvl10: ~6copper, lvl70: ~9silver
bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY) );
}
if (bones->lootRecipient != this)
permission = NONE_PERMISSION;
else
permission = OWNER_PERMISSION;
break;
}
case HIGHGUID_UNIT:
case HIGHGUID_VEHICLE:
{
Creature *creature = GetMap()->GetCreature(guid);
// must be in range and creature must be alive for pickpocket and must be dead for another loot
if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
{
SendLootRelease(guid);
return;
}
if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
{
SendLootRelease(guid);
return;
}
loot = &creature->loot;
if (loot_type == LOOT_PICKPOCKETING)
{
if (!creature->lootForPickPocketed)
{
creature->lootForPickPocketed = true;
loot->clear();
if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
// Generate extra money for pick pocket loot
const uint32 a = urand(0, creature->getLevel()/2);
const uint32 b = urand(0, getLevel()/2);
loot->gold = uint32(10 * (a + b) * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
permission = OWNER_PERMISSION;
}
}
else
{
// the player whose group may loot the corpse
Player *recipient = creature->GetLootRecipient();
if (!recipient)
{
creature->SetLootRecipient(this);
recipient = this;
}
if (creature->lootForPickPocketed)
{
creature->lootForPickPocketed = false;
loot->clear();
}
if (!creature->lootForBody)
{
creature->lootForBody = true;
loot->clear();
if (uint32 lootid = creature->GetCreatureInfo()->lootid)
loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
if (Group* group = creature->GetGroupLootRecipient())
{
group->UpdateLooterGuid(creature,true);
switch (group->GetLootMethod())
{
case GROUP_LOOT:
// GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
group->GroupLoot(creature, loot);
break;
case NEED_BEFORE_GREED:
group->NeedBeforeGreed(creature, loot);
break;
case MASTER_LOOT:
group->MasterLoot(creature, loot);
break;
default:
break;
}
}
}
// possible only if creature->lootForBody && loot->empty() at spell cast check
if (loot_type == LOOT_SKINNING)
{
if (!creature->lootForSkin)
{
creature->lootForSkin = true;
loot->clear();
loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
// let reopen skinning loot if will closed.
if (!loot->empty())
creature->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE);
permission = OWNER_PERMISSION;
}
}
// set group rights only for loot_type != LOOT_SKINNING
else
{
if (Group* group = creature->GetGroupLootRecipient())
{
if (group == GetGroup())
{
if (group->GetLootMethod() == FREE_FOR_ALL)
permission = ALL_PERMISSION;
else if (group->GetLooterGuid() == GetObjectGuid())
{
if (group->GetLootMethod() == MASTER_LOOT)
permission = MASTER_PERMISSION;
else
permission = ALL_PERMISSION;
}
else
permission = GROUP_PERMISSION;
}
else
permission = NONE_PERMISSION;
}
else if (recipient == this)
permission = OWNER_PERMISSION;
else
permission = NONE_PERMISSION;
}
}
break;
}
default:
{
sLog.outError("%s is unsupported for looting.", guid.GetString().c_str());
return;
}
}
SetLootGuid(guid);
// LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
switch(loot_type)
{
case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
case LOOT_FISHING_FAIL: loot_type = LOOT_FISHING; break;
case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
default: break;
}
// need know merged fishing/corpse loot type for achievements
loot->loot_type = loot_type;
WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
data << ObjectGuid(guid);
data << uint8(loot_type);
data << LootView(*loot, this, permission);
SendDirectMessage(&data);
// add 'this' player as one of the players that are looting 'loot'
if (permission != NONE_PERMISSION)
loot->AddLooter(GetObjectGuid());
if (loot_type == LOOT_CORPSE && !guid.IsItem())
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
}
void Player::SendNotifyLootMoneyRemoved()
{
WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
GetSession()->SendPacket( &data );
}
void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
{
WorldPacket data(SMSG_LOOT_REMOVED, 1);
data << uint8(lootSlot);
GetSession()->SendPacket( &data );
}
void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
{
WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
data << Field;
data << Value;
// Tempfix before WorldStateMgr implementing
if (IsInWorld() && GetSession())
GetSession()->SendPacket(&data);
}
static WorldStatePair AV_world_states[] =
{
{ 0x7ae, 0x1 }, // 1966 7 snowfall n
{ 0x532, 0x1 }, // 1330 8 frostwolfhut hc
{ 0x531, 0x0 }, // 1329 9 frostwolfhut ac
{ 0x52e, 0x0 }, // 1326 10 stormpike firstaid a_a
{ 0x571, 0x0 }, // 1393 11 east frostwolf tower horde assaulted -unused
{ 0x570, 0x0 }, // 1392 12 west frostwolf tower horde assaulted - unused
{ 0x567, 0x1 }, // 1383 13 frostwolfe c
{ 0x566, 0x1 }, // 1382 14 frostwolfw c
{ 0x550, 0x1 }, // 1360 15 irondeep (N) ally
{ 0x544, 0x0 }, // 1348 16 ice grave a_a
{ 0x536, 0x0 }, // 1334 17 stormpike grave h_c
{ 0x535, 0x1 }, // 1333 18 stormpike grave a_c
{ 0x518, 0x0 }, // 1304 19 stoneheart grave a_a
{ 0x517, 0x0 }, // 1303 20 stoneheart grave h_a
{ 0x574, 0x0 }, // 1396 21 unk
{ 0x573, 0x0 }, // 1395 22 iceblood tower horde assaulted -unused
{ 0x572, 0x0 }, // 1394 23 towerpoint horde assaulted - unused
{ 0x56f, 0x0 }, // 1391 24 unk
{ 0x56e, 0x0 }, // 1390 25 iceblood a
{ 0x56d, 0x0 }, // 1389 26 towerp a
{ 0x56c, 0x0 }, // 1388 27 frostwolfe a
{ 0x56b, 0x0 }, // 1387 28 froswolfw a
{ 0x56a, 0x1 }, // 1386 29 unk
{ 0x569, 0x1 }, // 1385 30 iceblood c
{ 0x568, 0x1 }, // 1384 31 towerp c
{ 0x565, 0x0 }, // 1381 32 stoneh tower a
{ 0x564, 0x0 }, // 1380 33 icewing tower a
{ 0x563, 0x0 }, // 1379 34 dunn a
{ 0x562, 0x0 }, // 1378 35 duns a
{ 0x561, 0x0 }, // 1377 36 stoneheart bunker alliance assaulted - unused
{ 0x560, 0x0 }, // 1376 37 icewing bunker alliance assaulted - unused
{ 0x55f, 0x0 }, // 1375 38 dunbaldar south alliance assaulted - unused
{ 0x55e, 0x0 }, // 1374 39 dunbaldar north alliance assaulted - unused
{ 0x55d, 0x0 }, // 1373 40 stone tower d
{ 0x3c6, 0x0 }, // 966 41 unk
{ 0x3c4, 0x0 }, // 964 42 unk
{ 0x3c2, 0x0 }, // 962 43 unk
{ 0x516, 0x1 }, // 1302 44 stoneheart grave a_c
{ 0x515, 0x0 }, // 1301 45 stonheart grave h_c
{ 0x3b6, 0x0 }, // 950 46 unk
{ 0x55c, 0x0 }, // 1372 47 icewing tower d
{ 0x55b, 0x0 }, // 1371 48 dunn d
{ 0x55a, 0x0 }, // 1370 49 duns d
{ 0x559, 0x0 }, // 1369 50 unk
{ 0x558, 0x0 }, // 1368 51 iceblood d
{ 0x557, 0x0 }, // 1367 52 towerp d
{ 0x556, 0x0 }, // 1366 53 frostwolfe d
{ 0x555, 0x0 }, // 1365 54 frostwolfw d
{ 0x554, 0x1 }, // 1364 55 stoneh tower c
{ 0x553, 0x1 }, // 1363 56 icewing tower c
{ 0x552, 0x1 }, // 1362 57 dunn c
{ 0x551, 0x1 }, // 1361 58 duns c
{ 0x54f, 0x0 }, // 1359 59 irondeep (N) horde
{ 0x54e, 0x0 }, // 1358 60 irondeep (N) ally
{ 0x54d, 0x1 }, // 1357 61 mine (S) neutral
{ 0x54c, 0x0 }, // 1356 62 mine (S) horde
{ 0x54b, 0x0 }, // 1355 63 mine (S) ally
{ 0x545, 0x0 }, // 1349 64 iceblood h_a
{ 0x543, 0x1 }, // 1347 65 iceblod h_c
{ 0x542, 0x0 }, // 1346 66 iceblood a_c
{ 0x540, 0x0 }, // 1344 67 snowfall h_a
{ 0x53f, 0x0 }, // 1343 68 snowfall a_a
{ 0x53e, 0x0 }, // 1342 69 snowfall h_c
{ 0x53d, 0x0 }, // 1341 70 snowfall a_c
{ 0x53c, 0x0 }, // 1340 71 frostwolf g h_a
{ 0x53b, 0x0 }, // 1339 72 frostwolf g a_a
{ 0x53a, 0x1 }, // 1338 73 frostwolf g h_c
{ 0x539, 0x0 }, // l33t 74 frostwolf g a_c
{ 0x538, 0x0 }, // 1336 75 stormpike grave h_a
{ 0x537, 0x0 }, // 1335 76 stormpike grave a_a
{ 0x534, 0x0 }, // 1332 77 frostwolf hut h_a
{ 0x533, 0x0 }, // 1331 78 frostwolf hut a_a
{ 0x530, 0x0 }, // 1328 79 stormpike first aid h_a
{ 0x52f, 0x0 }, // 1327 80 stormpike first aid h_c
{ 0x52d, 0x1 }, // 1325 81 stormpike first aid a_c
{ 0x0, 0x0 }
};
static WorldStatePair WS_world_states[] =
{
{ 0x62d, 0x0 }, // 1581 7 alliance flag captures
{ 0x62e, 0x0 }, // 1582 8 horde flag captures
{ 0x609, 0x0 }, // 1545 9 unk, set to 1 on alliance flag pickup...
{ 0x60a, 0x0 }, // 1546 10 unk, set to 1 on horde flag pickup, after drop it's -1
{ 0x60b, 0x2 }, // 1547 11 unk
{ 0x641, 0x3 }, // 1601 12 unk (max flag captures?)
{ 0x922, 0x1 }, // 2338 13 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
{ 0x923, 0x1 }, // 2339 14 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
{ 0x1097,0x1 }, // 4247 15 show time limit?
{ 0x1098,0x19 }, // 4248 16 time remaining in minutes
{ 0x0, 0x0 }
};
static WorldStatePair AB_world_states[] =
{
{ 0x6e7, 0x0 }, // 1767 7 stables alliance
{ 0x6e8, 0x0 }, // 1768 8 stables horde
{ 0x6e9, 0x0 }, // 1769 9 unk, ST?
{ 0x6ea, 0x0 }, // 1770 10 stables (show/hide)
{ 0x6ec, 0x0 }, // 1772 11 farm (0 - horde controlled, 1 - alliance controlled)
{ 0x6ed, 0x0 }, // 1773 12 farm (show/hide)
{ 0x6ee, 0x0 }, // 1774 13 farm color
{ 0x6ef, 0x0 }, // 1775 14 gold mine color, may be FM?
{ 0x6f0, 0x0 }, // 1776 15 alliance resources
{ 0x6f1, 0x0 }, // 1777 16 horde resources
{ 0x6f2, 0x0 }, // 1778 17 horde bases
{ 0x6f3, 0x0 }, // 1779 18 alliance bases
{ 0x6f4, 0x7d0 }, // 1780 19 max resources (2000)
{ 0x6f6, 0x0 }, // 1782 20 blacksmith color
{ 0x6f7, 0x0 }, // 1783 21 blacksmith (show/hide)
{ 0x6f8, 0x0 }, // 1784 22 unk, bs?
{ 0x6f9, 0x0 }, // 1785 23 unk, bs?
{ 0x6fb, 0x0 }, // 1787 24 gold mine (0 - horde contr, 1 - alliance contr)
{ 0x6fc, 0x0 }, // 1788 25 gold mine (0 - conflict, 1 - horde)
{ 0x6fd, 0x0 }, // 1789 26 gold mine (1 - show/0 - hide)
{ 0x6fe, 0x0 }, // 1790 27 gold mine color
{ 0x700, 0x0 }, // 1792 28 gold mine color, wtf?, may be LM?
{ 0x701, 0x0 }, // 1793 29 lumber mill color (0 - conflict, 1 - horde contr)
{ 0x702, 0x0 }, // 1794 30 lumber mill (show/hide)
{ 0x703, 0x0 }, // 1795 31 lumber mill color color
{ 0x732, 0x1 }, // 1842 32 stables (1 - uncontrolled)
{ 0x733, 0x1 }, // 1843 33 gold mine (1 - uncontrolled)
{ 0x734, 0x1 }, // 1844 34 lumber mill (1 - uncontrolled)
{ 0x735, 0x1 }, // 1845 35 farm (1 - uncontrolled)
{ 0x736, 0x1 }, // 1846 36 blacksmith (1 - uncontrolled)
{ 0x745, 0x2 }, // 1861 37 unk
{ 0x7a3, 0x708 }, // 1955 38 warning limit (1800)
{ 0x0, 0x0 }
};
static WorldStatePair EY_world_states[] =
{
{ 0xac1, 0x0 }, // 2753 7 Horde Bases
{ 0xac0, 0x0 }, // 2752 8 Alliance Bases
{ 0xab6, 0x0 }, // 2742 9 Mage Tower - Horde conflict
{ 0xab5, 0x0 }, // 2741 10 Mage Tower - Alliance conflict
{ 0xab4, 0x0 }, // 2740 11 Fel Reaver - Horde conflict
{ 0xab3, 0x0 }, // 2739 12 Fel Reaver - Alliance conflict
{ 0xab2, 0x0 }, // 2738 13 Draenei - Alliance conflict
{ 0xab1, 0x0 }, // 2737 14 Draenei - Horde conflict
{ 0xab0, 0x0 }, // 2736 15 unk // 0 at start
{ 0xaaf, 0x0 }, // 2735 16 unk // 0 at start
{ 0xaad, 0x0 }, // 2733 17 Draenei - Horde control
{ 0xaac, 0x0 }, // 2732 18 Draenei - Alliance control
{ 0xaab, 0x1 }, // 2731 19 Draenei uncontrolled (1 - yes, 0 - no)
{ 0xaaa, 0x0 }, // 2730 20 Mage Tower - Alliance control
{ 0xaa9, 0x0 }, // 2729 21 Mage Tower - Horde control
{ 0xaa8, 0x1 }, // 2728 22 Mage Tower uncontrolled (1 - yes, 0 - no)
{ 0xaa7, 0x0 }, // 2727 23 Fel Reaver - Horde control
{ 0xaa6, 0x0 }, // 2726 24 Fel Reaver - Alliance control
{ 0xaa5, 0x1 }, // 2725 25 Fel Reaver uncontrolled (1 - yes, 0 - no)
{ 0xaa4, 0x0 }, // 2724 26 Boold Elf - Horde control
{ 0xaa3, 0x0 }, // 2723 27 Boold Elf - Alliance control
{ 0xaa2, 0x1 }, // 2722 28 Boold Elf uncontrolled (1 - yes, 0 - no)
{ 0xac5, 0x1 }, // 2757 29 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
{ 0xad2, 0x1 }, // 2770 30 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
{ 0xad1, 0x1 }, // 2769 31 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
{ 0xabe, 0x0 }, // 2750 32 Horde resources
{ 0xabd, 0x0 }, // 2749 33 Alliance resources
{ 0xa05, 0x8e }, // 2565 34 unk, constant?
{ 0xaa0, 0x0 }, // 2720 35 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
{ 0xa9f, 0x0 }, // 2719 36 Capturing progress-bar (0 - left, 100 - right)
{ 0xa9e, 0x0 }, // 2718 37 Capturing progress-bar (1 - show, 0 - hide)
{ 0xc0d, 0x17b }, // 3085 38 unk
// and some more ... unknown
{ 0x0, 0x0 }
};
static WorldStatePair SI_world_states[] = // Silithus
{
{ 2313, 0x0 }, // 1 ally silityst gathered
{ 2314, 0x0 }, // 2 horde silityst gathered
{ 2317, 0x0 } // 3 max silithyst
};
static WorldStatePair EP_world_states[] =
{
{ 0x97a, 0x0 }, // 10 2426
{ 0x917, 0x0 }, // 11 2327
{ 0x918, 0x0 }, // 12 2328
{ 0x97b, 0x32 }, // 13 2427
{ 0x97c, 0x32 }, // 14 2428
{ 0x933, 0x1 }, // 15 2355
{ 0x946, 0x0 }, // 16 2374
{ 0x947, 0x0 }, // 17 2375
{ 0x948, 0x0 }, // 18 2376
{ 0x949, 0x0 }, // 19 2377
{ 0x94a, 0x0 }, // 20 2378
{ 0x94b, 0x0 }, // 21 2379
{ 0x932, 0x0 }, // 22 2354
{ 0x934, 0x0 }, // 23 2356
{ 0x935, 0x0 }, // 24 2357
{ 0x936, 0x0 }, // 25 2358
{ 0x937, 0x0 }, // 26 2359
{ 0x938, 0x0 }, // 27 2360
{ 0x939, 0x1 }, // 28 2361
{ 0x930, 0x1 }, // 29 2352
{ 0x93a, 0x0 }, // 30 2362
{ 0x93b, 0x0 }, // 31 2363
{ 0x93c, 0x0 }, // 32 2364
{ 0x93d, 0x0 }, // 33 2365
{ 0x944, 0x0 }, // 34 2372
{ 0x945, 0x0 }, // 35 2373
{ 0x931, 0x1 }, // 36 2353
{ 0x93e, 0x0 }, // 37 2366
{ 0x931, 0x1 }, // 38 2367 ?? grey horde not in dbc! send for consistency's sake, and to match field count
{ 0x940, 0x0 }, // 39 2368
{ 0x941, 0x0 }, // 7 2369
{ 0x942, 0x0 }, // 8 2370
{ 0x943, 0x0 } // 9 2371
};
static WorldStatePair HP_world_states[] = // Hellfire Peninsula
{
{ 0x9ba, 0x1 }, // 2490 10
{ 0x9b9, 0x1 }, // 2489 11
{ 0x9b5, 0x0 }, // 2485 12
{ 0x9b4, 0x1 }, // 2484 13
{ 0x9b3, 0x0 }, // 2483 14
{ 0x9b2, 0x0 }, // 2482 15
{ 0x9b1, 0x1 }, // 2481 16
{ 0x9b0, 0x0 }, // 2480 17
{ 0x9ae, 0x0 }, // 2478 18 horde pvp objectives captured
{ 0x9ac, 0x0 }, // 2476 19
{ 0x9a8, 0x0 }, // 2472 20
{ 0x9a7, 0x0 }, // 2471 21
{ 0x9a6, 0x1 }, // 2470 22
{ 0x0, 0x0 }
};
static WorldStatePair TF_world_states[] = // Terokkar Forest
{
{ 0xa41, 0x0 }, // 2625 10
{ 0xa40, 0x14 }, // 2624 11
{ 0xa3f, 0x0 }, // 2623 12
{ 0xa3e, 0x0 }, // 2622 13
{ 0xa3d, 0x5 }, // 2621 14
{ 0xa3c, 0x0 }, // 2620 15
{ 0xa87, 0x0 }, // 2695 16
{ 0xa86, 0x0 }, // 2694 17
{ 0xa85, 0x0 }, // 2693 18
{ 0xa84, 0x0 }, // 2692 19
{ 0xa83, 0x0 }, // 2691 20
{ 0xa82, 0x0 }, // 2690 21
{ 0xa81, 0x0 }, // 2689 22
{ 0xa80, 0x0 }, // 2688 23
{ 0xa7e, 0x0 }, // 2686 24
{ 0xa7d, 0x0 }, // 2685 25
{ 0xa7c, 0x0 }, // 2684 26
{ 0xa7b, 0x0 }, // 2683 27
{ 0xa7a, 0x0 }, // 2682 28
{ 0xa79, 0x0 }, // 2681 29
{ 0x9d0, 0x5 }, // 2512 30
{ 0x9ce, 0x0 }, // 2510 31
{ 0x9cd, 0x0 }, // 2509 32
{ 0x9cc, 0x0 }, // 2508 33
{ 0xa88, 0x0 }, // 2696 34
{ 0xad0, 0x0 }, // 2768 35
{ 0xacf, 0x1 }, // 2767 36
{ 0x0, 0x0 }
};
static WorldStatePair ZM_world_states[] = // Zangarmarsh
{
{ 0x9e1, 0x0 }, // 2529 10
{ 0x9e0, 0x0 }, // 2528 11
{ 0x9df, 0x0 }, // 2527 12
{ 0xa5d, 0x1 }, // 2526 13
{ 0xa5c, 0x0 }, // 2525 14
{ 0xa5b, 0x1 }, // 2524 15
{ 0xa5a, 0x0 }, // 2523 16
{ 0xa59, 0x1 }, // 2649 17
{ 0xa58, 0x0 }, // 2648 18
{ 0xa57, 0x0 }, // 2647 19
{ 0xa56, 0x0 }, // 2646 20
{ 0xa55, 0x1 }, // 2645 21
{ 0xa54, 0x0 }, // 2644 22
{ 0x9e7, 0x0 }, // 2535 23
{ 0x9e6, 0x0 }, // 2534 24
{ 0x9e5, 0x0 }, // 2533 25
{ 0xa00, 0x0 }, // 2560 26
{ 0x9ff, 0x1 }, // 2559 27
{ 0x9fe, 0x0 }, // 2558 28
{ 0x9fd, 0x0 }, // 2557 29
{ 0x9fc, 0x1 }, // 2556 30
{ 0x9fb, 0x0 }, // 2555 31
{ 0xa62, 0x0 }, // 2658 32
{ 0xa61, 0x1 }, // 2657 33
{ 0xa60, 0x1 }, // 2656 34
{ 0xa5f, 0x0 }, // 2655 35
{ 0x0, 0x0 }
};
static WorldStatePair NA_world_states[] =
{
{ 2503, 0x0 }, // 10
{ 2502, 0x0 }, // 11
{ 2493, 0x0 }, // 12
{ 2491, 0x0 }, // 13
{ 2495, 0x0 }, // 14
{ 2494, 0x0 }, // 15
{ 2497, 0x0 }, // 16
{ 2762, 0x0 }, // 17
{ 2662, 0x0 }, // 18
{ 2663, 0x0 }, // 19
{ 2664, 0x0 }, // 20
{ 2760, 0x0 }, // 21
{ 2670, 0x0 }, // 22
{ 2668, 0x0 }, // 23
{ 2669, 0x0 }, // 24
{ 2761, 0x0 }, // 25
{ 2667, 0x0 }, // 26
{ 2665, 0x0 }, // 27
{ 2666, 0x0 }, // 28
{ 2763, 0x0 }, // 29
{ 2659, 0x0 }, // 30
{ 2660, 0x0 }, // 31
{ 2661, 0x0 }, // 32
{ 2671, 0x0 }, // 33
{ 2676, 0x0 }, // 34
{ 2677, 0x0 }, // 35
{ 2672, 0x0 }, // 36
{ 2673, 0x0 } // 37
};
void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
{
// data depends on zoneid/mapid...
BattleGround* bg = GetBattleGround();
uint32 mapid = GetMapId();
WorldPvP* outdoorBg = sWorldPvPMgr.GetWorldPvPToZoneId(zoneid);
DEBUG_LOG("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
uint32 count = 0; // count of world states in packet
WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+8*8));// guess
data << uint32(mapid); // mapid
data << uint32(zoneid); // zone id
data << uint32(areaid); // area id, new 2.1.0
size_t count_pos = data.wpos();
data << uint16(0); // count of uint64 blocks, placeholder
// common fields
FillInitialWorldState(data, count, 0x8d8, 0x0); // 2264 1
FillInitialWorldState(data, count, 0x8d7, 0x0); // 2263 2
FillInitialWorldState(data, count, 0x8d6, 0x0); // 2262 3
FillInitialWorldState(data, count, 0x8d5, 0x0); // 2261 4
FillInitialWorldState(data, count, 0x8d4, 0x0); // 2260 5
FillInitialWorldState(data, count, 0x8d3, 0x0); // 2259 6
// 3191 7 Current arena season
FillInitialWorldState(data, count, 0xC77, sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_ID));
// 3901 8 Previous arena season
FillInitialWorldState(data, count, 0xF3D, sWorld.getConfig(CONFIG_UINT32_ARENA_SEASON_PREVIOUS_ID));
FillInitialWorldState(data, count, 0xED9, 1); // 3801 9 0 - Battle for Wintergrasp in progress, 1 - otherwise
// 4354 10 Time when next Battle for Wintergrasp starts
FillInitialWorldState(data, count, 0x1102, uint32(time(NULL) + 9000));
if (mapid == 530) // Outland
{
FillInitialWorldState(data, count, 0x9bf, 0x0); // 2495
FillInitialWorldState(data, count, 0x9bd, 0xF); // 2493
FillInitialWorldState(data, count, 0x9bb, 0xF); // 2491
}
switch(zoneid)
{
case 1:
case 11:
case 12:
case 38:
case 40:
case 51:
break;
case 139: // Eastern plaguelands
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_EP)
outdoorBg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data, count, EP_world_states);
break;
case 1377: // Silithus
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_SI)
outdoorBg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data, count, SI_world_states);
break;
case 1519:
case 1537:
case 2257:
break;
case 2597: // AV
if (bg && bg->GetTypeID(true) == BATTLEGROUND_AV)
bg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data,count, AV_world_states);
break;
case 3277: // WS
if (bg && bg->GetTypeID(true) == BATTLEGROUND_WS)
bg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data,count, WS_world_states);
break;
case 3358: // AB
if (bg && bg->GetTypeID(true) == BATTLEGROUND_AB)
bg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data,count, AB_world_states);
break;
case 3820: // EY
if (bg && bg->GetTypeID(true) == BATTLEGROUND_EY)
bg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data,count, EY_world_states);
break;
case 3483: // Hellfire Peninsula
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_HP)
outdoorBg->FillInitialWorldStates(data,count);
else
FillInitialWorldState(data,count, HP_world_states);
break;
case 3518: // Nargrand - Halaa
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_NA)
outdoorBg->FillInitialWorldStates(data, count);
else
FillInitialWorldState(data, count, NA_world_states);
break;
case 3519: // Terokkar Forest
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_TF)
outdoorBg->FillInitialWorldStates(data,count);
else
FillInitialWorldState(data,count, TF_world_states);
break;
case 3521: // Zangarmarsh
if (outdoorBg && outdoorBg->GetTypeId() == WORLD_PVP_TYPE_ZM)
outdoorBg->FillInitialWorldStates(data,count);
else
FillInitialWorldState(data,count, ZM_world_states);
break;
case 3698: // Nagrand Arena
if (bg && bg->GetTypeID(true) == BATTLEGROUND_NA)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0xa0f,0x0);// 2575 7
FillInitialWorldState(data,count,0xa10,0x0);// 2576 8
FillInitialWorldState(data,count,0xa11,0x0);// 2577 9 show
}
break;
case 3702: // Blade's Edge Arena
if (bg && bg->GetTypeID(true) == BATTLEGROUND_BE)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0x9f0,0x0);// 2544 7 gold
FillInitialWorldState(data,count,0x9f1,0x0);// 2545 8 green
FillInitialWorldState(data,count,0x9f3,0x0);// 2547 9 show
}
break;
case 3968: // Ruins of Lordaeron
if (bg && bg->GetTypeID(true) == BATTLEGROUND_RL)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0xbb8,0x0);// 3000 7 gold
FillInitialWorldState(data,count,0xbb9,0x0);// 3001 8 green
FillInitialWorldState(data,count,0xbba,0x0);// 3002 9 show
}
break;
case 4378: // Dalaran Severs
if (bg && bg->GetTypeID() == BATTLEGROUND_DS)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0xe11,0x0);// 7 gold
FillInitialWorldState(data,count,0xe10,0x0);// 8 green
FillInitialWorldState(data,count,0xe1a,0x0);// 9 show
}
break;
case 4406: // Ring of Valor
if (bg && bg->GetTypeID() == BATTLEGROUND_RV)
bg->FillInitialWorldStates(data, count);
else
{
FillInitialWorldState(data,count,0xe11,0x0);// 7 gold
FillInitialWorldState(data,count,0xe10,0x0);// 8 green
FillInitialWorldState(data,count,0xe1a,0x0);// 9 show
}
break;
case 3703: // Shattrath City
break;
case 4384: // SA
if (bg && bg->GetTypeID(true) == BATTLEGROUND_SA)
bg->FillInitialWorldStates(data, count);
else
{
// 1-3 A defend, 4-6 H defend, 7-9 unk defend, 1 - ok, 2 - half destroyed, 3 - destroyed
data << uint32(0xf09) << uint32(0x4); // 7 3849 Gate of Temple
data << uint32(0xe36) << uint32(0x4); // 8 3638 Gate of Yellow Moon
data << uint32(0xe27) << uint32(0x4); // 9 3623 Gate of Green Emerald
data << uint32(0xe24) << uint32(0x4); // 10 3620 Gate of Blue Sapphire
data << uint32(0xe21) << uint32(0x4); // 11 3617 Gate of Red Sun
data << uint32(0xe1e) << uint32(0x4); // 12 3614 Gate of Purple Ametyst
data << uint32(0xdf3) << uint32(0x0); // 13 3571 bonus timer (1 - on, 0 - off)
data << uint32(0xded) << uint32(0x0); // 14 3565 Horde Attacker
data << uint32(0xdec) << uint32(0x1); // 15 3564 Alliance Attacker
// End Round (timer), better explain this by example, eg. ends in 19:59 -> A:BC
data << uint32(0xde9) << uint32(0x9); // 16 3561 C
data << uint32(0xde8) << uint32(0x5); // 17 3560 B
data << uint32(0xde7) << uint32(0x19); // 18 3559 A
data << uint32(0xe35) << uint32(0x1); // 19 3637 East g - Horde control
data << uint32(0xe34) << uint32(0x1); // 20 3636 West g - Horde control
data << uint32(0xe33) << uint32(0x1); // 21 3635 South g - Horde control
data << uint32(0xe32) << uint32(0x0); // 22 3634 East g - Alliance control
data << uint32(0xe31) << uint32(0x0); // 23 3633 West g - Alliance control
data << uint32(0xe30) << uint32(0x0); // 24 3632 South g - Alliance control
data << uint32(0xe2f) << uint32(0x1); // 25 3631 Chamber of Ancients - Horde control
data << uint32(0xe2e) << uint32(0x0); // 26 3630 Chamber of Ancients - Alliance control
data << uint32(0xe2d) << uint32(0x0); // 27 3629 Beach1 - Horde control
data << uint32(0xe2c) << uint32(0x0); // 28 3628 Beach2 - Horde control
data << uint32(0xe2b) << uint32(0x1); // 29 3627 Beach1 - Alliance control
data << uint32(0xe2a) << uint32(0x1); // 30 3626 Beach2 - Alliance control
// and many unks...
}
break;
case 4710:
if (bg && bg->GetTypeID(true) == BATTLEGROUND_IC)
bg->FillInitialWorldStates(data, count);
else
{
data << uint32(4221) << uint32(1); // 7
data << uint32(4222) << uint32(1); // 8
data << uint32(4226) << uint32(300); // 9
data << uint32(4227) << uint32(300); // 10
data << uint32(4322) << uint32(1); // 11
data << uint32(4321) << uint32(1); // 12
data << uint32(4320) << uint32(1); // 13
data << uint32(4323) << uint32(1); // 14
data << uint32(4324) << uint32(1); // 15
data << uint32(4325) << uint32(1); // 16
data << uint32(4317) << uint32(1); // 17
data << uint32(4301) << uint32(1); // 18
data << uint32(4296) << uint32(1); // 19
data << uint32(4306) << uint32(1); // 20
data << uint32(4311) << uint32(1); // 21
data << uint32(4294) << uint32(1); // 22
data << uint32(4243) << uint32(1); // 23
data << uint32(4345) << uint32(1); // 24
}
break;
default:
FillInitialWorldState(data,count, 0x914, 0x0); // 2324 7
FillInitialWorldState(data,count, 0x913, 0x0); // 2323 8
FillInitialWorldState(data,count, 0x912, 0x0); // 2322 9
FillInitialWorldState(data,count, 0x915, 0x0); // 2325 10
break;
}
FillBGWeekendWorldStates(data,count);
data.put<uint16>(count_pos,count); // set actual world state amount
GetSession()->SendPacket(&data);
}
void Player::FillBGWeekendWorldStates(WorldPacket& data, uint32& count)
{
for(uint32 i = 1; i < sBattlemasterListStore.GetNumRows(); ++i)
{
BattlemasterListEntry const * bl = sBattlemasterListStore.LookupEntry(i);
if (bl && bl->HolidayWorldStateId)
{
if (BattleGroundMgr::IsBGWeekend(BattleGroundTypeId(bl->id)))
FillInitialWorldState(data, count, bl->HolidayWorldStateId, 1);
else
FillInitialWorldState(data, count, bl->HolidayWorldStateId, 0);
}
}
}
uint32 Player::GetXPRestBonus(uint32 xp)
{
uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
if (rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
rested_bonus = xp;
SetRestBonus( GetRestBonus() - rested_bonus);
DETAIL_LOG("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
return rested_bonus;
}
void Player::SetBindPoint(ObjectGuid guid)
{
WorldPacket data(SMSG_BINDER_CONFIRM, 8);
data << ObjectGuid(guid);
GetSession()->SendPacket( &data );
}
void Player::SendTalentWipeConfirm(ObjectGuid guid)
{
WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
data << ObjectGuid(guid);
data << uint32(resetTalentsCost());
GetSession()->SendPacket( &data );
}
void Player::SendPetSkillWipeConfirm()
{
Pet* pet = GetPet();
if(!pet)
return;
if (pet->getPetType() != HUNTER_PET || pet->m_usedTalentCount == 0)
return;
CharmInfo* charmInfo = pet->GetCharmInfo();
if (!charmInfo)
{
sLog.outError("WorldSession::HandlePetUnlearnOpcode: %s is considered pet-like but doesn't have a charminfo!", pet->GetGuidStr().c_str());
return;
}
pet->resetTalents();
SendTalentsInfoData(true);
}
/*********************************************************/
/*** STORAGE SYSTEM ***/
/*********************************************************/
void Player::SetVirtualItemSlot( uint8 i, Item* item)
{
MANGOS_ASSERT(i < 3);
if (i < 2 && item)
{
if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
return;
uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
if (charges == 0)
return;
if (charges > 1)
item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
else if (charges <= 1)
{
ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
}
}
}
void Player::SetSheath( SheathState sheathed )
{
switch (sheathed)
{
case SHEATH_STATE_UNARMED: // no prepared weapon
SetVirtualItemSlot(0,NULL);
SetVirtualItemSlot(1,NULL);
SetVirtualItemSlot(2,NULL);
break;
case SHEATH_STATE_MELEE: // prepared melee weapon
{
SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true));
SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true));
SetVirtualItemSlot(2,NULL);
}; break;
case SHEATH_STATE_RANGED: // prepared ranged weapon
SetVirtualItemSlot(0,NULL);
SetVirtualItemSlot(1,NULL);
SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true));
break;
default:
SetVirtualItemSlot(0,NULL);
SetVirtualItemSlot(1,NULL);
SetVirtualItemSlot(2,NULL);
break;
}
Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
}
uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
{
uint8 pClass = getClass();
uint8 slots[4];
slots[0] = NULL_SLOT;
slots[1] = NULL_SLOT;
slots[2] = NULL_SLOT;
slots[3] = NULL_SLOT;
switch( proto->InventoryType )
{
case INVTYPE_HEAD:
slots[0] = EQUIPMENT_SLOT_HEAD;
break;
case INVTYPE_NECK:
slots[0] = EQUIPMENT_SLOT_NECK;
break;
case INVTYPE_SHOULDERS:
slots[0] = EQUIPMENT_SLOT_SHOULDERS;
break;
case INVTYPE_BODY:
slots[0] = EQUIPMENT_SLOT_BODY;
break;
case INVTYPE_CHEST:
slots[0] = EQUIPMENT_SLOT_CHEST;
break;
case INVTYPE_ROBE:
slots[0] = EQUIPMENT_SLOT_CHEST;
break;
case INVTYPE_WAIST:
slots[0] = EQUIPMENT_SLOT_WAIST;
break;
case INVTYPE_LEGS:
slots[0] = EQUIPMENT_SLOT_LEGS;
break;
case INVTYPE_FEET:
slots[0] = EQUIPMENT_SLOT_FEET;
break;
case INVTYPE_WRISTS:
slots[0] = EQUIPMENT_SLOT_WRISTS;
break;
case INVTYPE_HANDS:
slots[0] = EQUIPMENT_SLOT_HANDS;
break;
case INVTYPE_FINGER:
slots[0] = EQUIPMENT_SLOT_FINGER1;
slots[1] = EQUIPMENT_SLOT_FINGER2;
break;
case INVTYPE_TRINKET:
slots[0] = EQUIPMENT_SLOT_TRINKET1;
slots[1] = EQUIPMENT_SLOT_TRINKET2;
break;
case INVTYPE_CLOAK:
slots[0] = EQUIPMENT_SLOT_BACK;
break;
case INVTYPE_WEAPON:
{
slots[0] = EQUIPMENT_SLOT_MAINHAND;
// suggest offhand slot only if know dual wielding
// (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
if (CanDualWield())
slots[1] = EQUIPMENT_SLOT_OFFHAND;
break;
};
case INVTYPE_SHIELD:
slots[0] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_RANGED:
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case INVTYPE_2HWEAPON:
slots[0] = EQUIPMENT_SLOT_MAINHAND;
if (CanDualWield() && CanTitanGrip())
slots[1] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_TABARD:
slots[0] = EQUIPMENT_SLOT_TABARD;
break;
case INVTYPE_WEAPONMAINHAND:
slots[0] = EQUIPMENT_SLOT_MAINHAND;
break;
case INVTYPE_WEAPONOFFHAND:
slots[0] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_HOLDABLE:
slots[0] = EQUIPMENT_SLOT_OFFHAND;
break;
case INVTYPE_THROWN:
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case INVTYPE_RANGEDRIGHT:
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case INVTYPE_BAG:
slots[0] = INVENTORY_SLOT_BAG_START + 0;
slots[1] = INVENTORY_SLOT_BAG_START + 1;
slots[2] = INVENTORY_SLOT_BAG_START + 2;
slots[3] = INVENTORY_SLOT_BAG_START + 3;
break;
case INVTYPE_RELIC:
{
switch(proto->SubClass)
{
case ITEM_SUBCLASS_ARMOR_LIBRAM:
if (pClass == CLASS_PALADIN)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_IDOL:
if (pClass == CLASS_DRUID)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_TOTEM:
if (pClass == CLASS_SHAMAN)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_MISC:
if (pClass == CLASS_WARLOCK)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
case ITEM_SUBCLASS_ARMOR_SIGIL:
if (pClass == CLASS_DEATH_KNIGHT)
slots[0] = EQUIPMENT_SLOT_RANGED;
break;
}
break;
}
default :
return NULL_SLOT;
}
if ( slot != NULL_SLOT )
{
if ( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
{
for (int i = 0; i < 4; ++i)
{
if ( slots[i] == slot )
return slot;
}
}
}
else
{
// search free slot at first
for (int i = 0; i < 4; ++i)
{
if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
{
// in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
if (slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
return slots[i];
}
}
// if not found free and can swap return first appropriate from used
for (int i = 0; i < 4; ++i)
{
if ( slots[i] != NULL_SLOT && swap )
return slots[i];
}
}
// no free position
return NULL_SLOT;
}
InventoryResult Player::CanUnequipItems( uint32 item, uint32 count ) const
{
Item *pItem;
uint32 tempcount = 0;
InventoryResult res = EQUIP_ERR_OK;
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem->GetEntry() == item )
{
InventoryResult ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
if (ires == EQUIP_ERR_OK)
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return EQUIP_ERR_OK;
}
else
res = ires;
}
}
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem->GetEntry() == item )
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return EQUIP_ERR_OK;
}
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem->GetEntry() == item )
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return EQUIP_ERR_OK;
}
}
Bag *pBag;
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pBag )
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
pItem = GetItemByPos( i, j );
if ( pItem && pItem->GetEntry() == item )
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return EQUIP_ERR_OK;
}
}
}
}
// not found req. item count and have unequippable items
return res;
}
uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const
{
uint32 count = 0;
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetEntry() == item )
count += pItem->GetCount();
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetEntry() == item )
count += pItem->GetCount();
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pBag )
count += pBag->GetItemCount(item,skipItem);
}
if (skipItem && skipItem->GetProto()->GemProperties)
{
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
count += pItem->GetGemCountWithID(item);
}
}
if (inBankAlso)
{
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
{
Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetEntry() == item )
count += pItem->GetCount();
}
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pBag )
count += pBag->GetItemCount(item,skipItem);
}
if (skipItem && skipItem->GetProto()->GemProperties)
{
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
{
Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
count += pItem->GetGemCountWithID(item);
}
}
}
return count;
}
uint32 Player::GetItemCountWithLimitCategory( uint32 limitCategory, Item* skipItem) const
{
uint32 count = 0;
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem)
count += pItem->GetCount();
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem)
count += pItem->GetCount();
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem);
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitCategory && pItem != skipItem)
count += pItem->GetCount();
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem);
return count;
}
Item* Player::GetItemByEntry( uint32 item ) const
{
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == item)
return pItem;
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEntry() == item)
return pItem;
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
if (Item* itemPtr = pBag->GetItemByEntry(item))
return itemPtr;
return NULL;
}
Item* Player::GetItemByLimitedCategory(uint32 limitedCategory) const
{
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
return pItem;
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetProto()->ItemLimitCategory == limitedCategory)
return pItem;
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i))
if (Item* itemPtr = pBag->GetItemByLimitedCategory(limitedCategory))
return itemPtr;
return NULL;
}
Item* Player::GetItemByGuid(ObjectGuid guid) const
{
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetObjectGuid() == guid)
return pItem;
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetObjectGuid() == guid)
return pItem;
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetObjectGuid() == guid)
return pItem;
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
if (Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetObjectGuid() == guid)
return pItem;
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
if (Bag *pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetObjectGuid() == guid)
return pItem;
return NULL;
}
Item* Player::GetItemByPos( uint16 pos ) const
{
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
return GetItemByPos( bag, slot );
}
Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
{
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
return m_items[slot];
else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
|| (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
{
Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
if ( pBag )
return pBag->GetItemByPos(slot);
}
return NULL;
}
uint32 Player::GetItemDisplayIdInSlot(uint8 bag, uint8 slot) const
{
const Item* pItem = GetItemByPos(bag, slot);
if (!pItem)
return 0;
return pItem->GetProto()->DisplayInfoID;
}
Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const
{
uint8 slot;
switch (attackType)
{
case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
default: return NULL;
}
Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
return NULL;
if (useable && !CanUseEquippedWeapon(attackType))
return NULL;
if (nonbroken && item->IsBroken())
return NULL;
return item;
}
Item* Player::GetShield(bool useable) const
{
Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
return NULL;
if (!useable)
return item;
if (item->IsBroken() || !CanUseEquippedWeapon(OFF_ATTACK))
return NULL;
return item;
}
uint32 Player::GetAttackBySlot( uint8 slot )
{
switch(slot)
{
case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
default: return MAX_ATTACK;
}
}
bool Player::IsInventoryPos( uint8 bag, uint8 slot )
{
if ( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
return true;
if ( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
return true;
return false;
}
bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
{
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
return true;
return false;
}
bool Player::IsBankPos( uint8 bag, uint8 slot )
{
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
return true;
if ( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
return true;
return false;
}
bool Player::IsBagPos( uint16 pos )
{
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
return true;
if ( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
return true;
return false;
}
bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos ) const
{
// post selected
if (bag == NULL_BAG && !explicit_pos)
return true;
if (bag == INVENTORY_SLOT_BAG_0)
{
// any post selected
if (slot == NULL_SLOT && !explicit_pos)
return true;
// equipment
if (slot < EQUIPMENT_SLOT_END)
return true;
// bag equip slots
if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
return true;
// backpack slots
if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
return true;
// keyring slots
if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
return true;
// bank main slots
if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
return true;
// bank bag slots
if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
return true;
return false;
}
// bag content slots
if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
{
Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
if(!pBag)
return false;
// any post selected
if (slot == NULL_SLOT && !explicit_pos)
return true;
return slot < pBag->GetBagSize();
}
// bank bag content slots
if ( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
{
Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
if(!pBag)
return false;
// any post selected
if (slot == NULL_SLOT && !explicit_pos)
return true;
return slot < pBag->GetBagSize();
}
// where this?
return false;
}
bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
{
uint32 tempcount = 0;
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
Item* pItem = GetItemByPos( i, j );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
}
}
if (inBankAlso)
{
for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
{
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
Item* pItem = GetItemByPos( i, j );
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
tempcount += pItem->GetCount();
if (tempcount >= count)
return true;
}
}
}
}
}
return false;
}
bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
{
uint32 tempcount = 0;
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i==int(except_slot))
continue;
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && pItem->GetEntry() == item)
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return true;
}
}
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
if (pProto && pProto->GemProperties)
{
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i==int(except_slot))
continue;
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem && (pItem->GetProto()->Socket[0].Color || pItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)))
{
tempcount += pItem->GetGemCountWithID(item);
if ( tempcount >= count )
return true;
}
}
}
return false;
}
bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
{
uint32 tempcount = 0;
for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i==int(except_slot))
continue;
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (!pItem)
continue;
ItemPrototype const *pProto = pItem->GetProto();
if (!pProto)
continue;
if (pProto->ItemLimitCategory == limitCategory)
{
tempcount += pItem->GetCount();
if ( tempcount >= count )
return true;
}
if ( pProto->Socket[0].Color)
{
tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
if ( tempcount >= count )
return true;
}
}
return false;
}
InventoryResult Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count) const
{
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
if (!pProto)
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
// no maximum
if (pProto->MaxCount > 0)
{
uint32 curcount = GetItemCount(pProto->ItemId, true, pItem);
if (curcount + count > uint32(pProto->MaxCount))
{
if (no_space_count)
*no_space_count = count +curcount - pProto->MaxCount;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
// check unique-equipped limit
if (pProto->ItemLimitCategory)
{
ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory);
if (!limitEntry)
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
}
if (limitEntry->mode == ITEM_LIMIT_CATEGORY_MODE_HAVE)
{
uint32 curcount = GetItemCountWithLimitCategory(pProto->ItemLimitCategory, pItem);
if (curcount + count > uint32(limitEntry->maxCount))
{
if (no_space_count)
*no_space_count = count + curcount - limitEntry->maxCount;
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS;
}
}
}
return EQUIP_ERR_OK;
}
bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
{
Item *pItem;
for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
return true;
}
for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if ( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
return true;
}
for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
pItem = GetItemByPos( i, j );
if ( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
return true;
}
}
}
return false;
}
InventoryResult Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
{
Item* pItem2 = GetItemByPos( bag, slot );
// ignore move item (this slot will be empty at move)
if (pItem2==pSrcItem)
pItem2 = NULL;
uint32 need_space;
// empty specific slot - check item fit to slot
if (!pItem2 || swap)
{
if (bag == INVENTORY_SLOT_BAG_0)
{
// keyring case
if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// currencytoken case
if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// prevent cheating
if ((slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) || slot >= PLAYER_SLOT_END)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
}
else
{
Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
if (!pBag)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
ItemPrototype const* pBagProto = pBag->GetProto();
if (!pBagProto)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (slot >= pBagProto->ContainerSlots)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (!ItemCanGoIntoBag(pProto,pBagProto))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
}
// non empty stack with space
need_space = pProto->GetMaxStackSize();
}
// non empty slot, check item type
else
{
// can be merged at least partly
InventoryResult res = pItem2->CanBeMergedPartlyWith(pProto);
if (res != EQUIP_ERR_OK)
return res;
// free stack space or infinity
need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
}
if (need_space > count)
need_space = count;
ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
if (!newPosition.isContainedIn(dest))
{
dest.push_back(newPosition);
count -= need_space;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
{
// skip specific bag already processed in first called _CanStoreItem_InBag
if (bag == skip_bag)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// skip nonexistent bag or self targeted bag
Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
if (!pBag || pBag==pSrcItem)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
ItemPrototype const* pBagProto = pBag->GetProto();
if (!pBagProto)
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
// specialized bag mode or non-specilized
if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
if (!ItemCanGoIntoBag(pProto,pBagProto))
return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
// skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
if (j==skip_slot)
continue;
Item* pItem2 = GetItemByPos( bag, j );
// ignore move item (this slot will be empty at move)
if (pItem2 == pSrcItem)
pItem2 = NULL;
// if merge skip empty, if !merge skip non-empty
if ((pItem2 != NULL) != merge)
continue;
uint32 need_space = pProto->GetMaxStackSize();
if (pItem2)
{
// can be merged at least partly
uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
if (res != EQUIP_ERR_OK)
continue;
// descrease at current stacksize
need_space -= pItem2->GetCount();
}
if (need_space > count)
need_space = count;
ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
if (!newPosition.isContainedIn(dest))
{
dest.push_back(newPosition);
count -= need_space;
if (count==0)
return EQUIP_ERR_OK;
}
}
return EQUIP_ERR_OK;
}
InventoryResult Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
{
for(uint32 j = slot_begin; j < slot_end; ++j)
{
// skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
continue;
Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
// ignore move item (this slot will be empty at move)
if (pItem2 == pSrcItem)
pItem2 = NULL;
// if merge skip empty, if !merge skip non-empty
if ((pItem2 != NULL) != merge)
continue;
uint32 need_space = pProto->GetMaxStackSize();
if (pItem2)
{
// can be merged at least partly
uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
if (res != EQUIP_ERR_OK)
continue;
// descrease at current stacksize
need_space -= pItem2->GetCount();
}
if (need_space > count)
need_space = count;
ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
if (!newPosition.isContainedIn(dest))
{
dest.push_back(newPosition);
count -= need_space;
if (count==0)
return EQUIP_ERR_OK;
}
}
return EQUIP_ERR_OK;
}
InventoryResult Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
{
DEBUG_LOG( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
if (!pProto)
{
if (no_space_count)
*no_space_count = count;
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
}
if (pItem)
{
// item used
if (pItem->HasTemporaryLoot())
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_ALREADY_LOOTED;
}
if (pItem->IsBindedNotWith(this))
{
if (no_space_count)
*no_space_count = count;
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
}
}
// check count of items (skip for auto move for same player from bank)
uint32 no_similar_count = 0; // can't store this amount similar items
InventoryResult res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
if (res != EQUIP_ERR_OK)
{
if (count == no_similar_count)
{
if (no_space_count)
*no_space_count = no_similar_count;
return res;
}
count -= no_similar_count;
}
// in specific slot
if (bag != NULL_BAG && slot != NULL_SLOT)
{
res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
// not specific slot or have space for partly store only in specific slot
// in specific bag
if (bag != NULL_BAG)
{
// search stack in bag for merge to
if (pProto->Stackable != 1)
{
if (bag == INVENTORY_SLOT_BAG_0) // inventory
{
res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
else // equipped bag
{
// we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
if (res != EQUIP_ERR_OK)
res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
// search free slot in bag for place to
if (bag == INVENTORY_SLOT_BAG_0) // inventory
{
// search free slot - keyring case
if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
{
uint32 keyringSize = GetMaxKeyringSize();
res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count==0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
{
res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
else // equipped bag
{
res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
if (res != EQUIP_ERR_OK)
res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
// not specific bag or have space for partly store only in specific bag
// search stack for merge to
if (pProto->Stackable != 1)
{
res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
if (pProto->BagFamily)
{
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count==0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
// search free slot - special bag case
if (pProto->BagFamily)
{
if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
{
uint32 keyringSize = GetMaxKeyringSize();
res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
{
res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count==0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
}
// Normally it would be impossible to autostore not empty bags
if (pItem && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
// search free slot
res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
{
if (no_space_count)
*no_space_count = count + no_similar_count;
return res;
}
if (count == 0)
{
if (no_similar_count==0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
continue;
if (count == 0)
{
if (no_similar_count == 0)
return EQUIP_ERR_OK;
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
if (no_space_count)
*no_space_count = count + no_similar_count;
return EQUIP_ERR_INVENTORY_FULL;
}
//////////////////////////////////////////////////////////////////////////
InventoryResult Player::CanStoreItems( Item **pItems,int count) const
{
Item *pItem2;
// fill space table
int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem2 && !pItem2->IsInTrade())
{
inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
}
}
for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem2 && !pItem2->IsInTrade())
{
inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
}
}
for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem2 && !pItem2->IsInTrade())
{
inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
}
}
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
pItem2 = GetItemByPos( i, j );
if (pItem2 && !pItem2->IsInTrade())
{
inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
}
}
}
}
// check free space for all items
for (int k = 0; k < count; ++k)
{
Item *pItem = pItems[k];
// no item
if (!pItem) continue;
DEBUG_LOG( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
ItemPrototype const *pProto = pItem->GetProto();
// strange item
if (!pProto)
return EQUIP_ERR_ITEM_NOT_FOUND;
// item used
if (pItem->HasTemporaryLoot())
return EQUIP_ERR_ALREADY_LOOTED;
// item it 'bind'
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
Bag *pBag;
ItemPrototype const *pBagProto;
// item is 'one item only'
InventoryResult res = CanTakeMoreSimilarItems(pItem);
if (res != EQUIP_ERR_OK)
return res;
// search stack for merge to
if (pProto->Stackable != 1)
{
bool b_found = false;
for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
b_found = true;
break;
}
}
if (b_found) continue;
for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
b_found = true;
break;
}
}
if (b_found) continue;
for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
{
pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
b_found = true;
break;
}
}
if (b_found) continue;
for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
{
pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pBag)
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
pItem2 = GetItemByPos( t, j );
if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
{
inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
b_found = true;
break;
}
}
}
}
if (b_found) continue;
}
// special bag case
if (pProto->BagFamily)
{
bool b_found = false;
if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
{
uint32 keyringSize = GetMaxKeyringSize();
for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
{
if (inv_keys[t-KEYRING_SLOT_START] == 0)
{
inv_keys[t-KEYRING_SLOT_START] = 1;
b_found = true;
break;
}
}
}
if (b_found) continue;
if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
{
for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
{
if (inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0)
{
inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
b_found = true;
break;
}
}
}
if (b_found) continue;
for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
{
pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pBag)
{
pBagProto = pBag->GetProto();
// not plain container check
if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
ItemCanGoIntoBag(pProto,pBagProto) )
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0)
{
inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
b_found = true;
break;
}
}
}
}
}
if (b_found) continue;
}
// search free slot
bool b_found = false;
for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
{
if (inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0)
{
inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
b_found = true;
break;
}
}
if (b_found) continue;
// search free slot in bags
for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
{
pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
if (pBag)
{
pBagProto = pBag->GetProto();
// special bag already checked
if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
continue;
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0)
{
inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
b_found = true;
break;
}
}
}
}
// no free slot found?
if (!b_found)
return EQUIP_ERR_INVENTORY_FULL;
}
return EQUIP_ERR_OK;
}
//////////////////////////////////////////////////////////////////////////
InventoryResult Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
{
dest = 0;
Item *pItem = Item::CreateItem( item, 1, this );
if (pItem)
{
InventoryResult result = CanEquipItem(slot, dest, pItem, swap );
delete pItem;
return result;
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
InventoryResult Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool direct_action ) const
{
dest = 0;
if (pItem)
{
DEBUG_LOG( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
ItemPrototype const *pProto = pItem->GetProto();
if (pProto)
{
// item used
if (pItem->HasTemporaryLoot())
return EQUIP_ERR_ALREADY_LOOTED;
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
// check count of items (skip for auto move for same player from bank)
InventoryResult res = CanTakeMoreSimilarItems(pItem);
if (res != EQUIP_ERR_OK)
return res;
// check this only in game
if (direct_action)
{
// May be here should be more stronger checks; STUNNED checked
// ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
if (hasUnitState(UNIT_STAT_STUNNED))
return EQUIP_ERR_YOU_ARE_STUNNED;
// do not allow equipping gear except weapons, offhands, projectiles, relics in
// - combat
// - in-progress arenas
if (!pProto->CanChangeEquipStateInCombat())
{
if (isInCombat())
return EQUIP_ERR_NOT_IN_COMBAT;
if (BattleGround* bg = GetBattleGround())
if (bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS)
return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
}
// prevent equip item in process logout
if (GetSession()->isLogingOut())
return EQUIP_ERR_YOU_ARE_STUNNED;
if (isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
if (IsNonMeleeSpellCasted(false))
return EQUIP_ERR_CANT_DO_RIGHT_NOW;
}
ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
// check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items)
if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
uint8 eslot = FindEquipSlot( pProto, slot, swap );
if (eslot == NULL_SLOT)
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
// jewelcrafting gem check
if (InventoryResult res2 = CanEquipMoreJewelcraftingGems(pItem->GetJewelcraftingGemCount(), swap ? eslot : NULL_SLOT))
return res2;
InventoryResult msg = CanUseItem(pItem , direct_action);
if (msg != EQUIP_ERR_OK)
return msg;
if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
// if swap ignore item (equipped also)
if (InventoryResult res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
return res2;
// check unique-equipped special item classes
if (pProto->Class == ITEM_CLASS_QUIVER)
{
for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
if (pBag != pItem)
{
if (ItemPrototype const* pBagProto = pBag->GetProto())
{
if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
: EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
}
}
}
}
}
uint32 type = pProto->InventoryType;
if (eslot == EQUIPMENT_SLOT_OFFHAND)
{
if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
{
if (!CanDualWield())
return EQUIP_ERR_CANT_DUAL_WIELD;
}
else if (type == INVTYPE_2HWEAPON)
{
if (!CanDualWield() || !CanTitanGrip())
return EQUIP_ERR_CANT_DUAL_WIELD;
}
if (IsTwoHandUsed())
return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
}
// equip two-hand weapon case (with possible unequip 2 items)
if (type == INVTYPE_2HWEAPON)
{
if (eslot == EQUIPMENT_SLOT_OFFHAND)
{
if (!CanTitanGrip())
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
}
else if (eslot != EQUIPMENT_SLOT_MAINHAND)
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
if (!CanTitanGrip())
{
// offhand item must can be stored in inventory for offhand item and it also must be unequipped
Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
ItemPosCountVec off_dest;
if (offItem && (!direct_action ||
CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
}
}
dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
return EQUIP_ERR_OK;
}
}
return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
}
InventoryResult Player::CanUnequipItem( uint16 pos, bool swap ) const
{
// Applied only to equipped items and bank bags
if (!IsEquipmentPos(pos) && !IsBagPos(pos))
return EQUIP_ERR_OK;
Item* pItem = GetItemByPos(pos);
// Applied only to existing equipped item
if (!pItem)
return EQUIP_ERR_OK;
DEBUG_LOG( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
ItemPrototype const *pProto = pItem->GetProto();
if (!pProto)
return EQUIP_ERR_ITEM_NOT_FOUND;
// item used
if (pItem->HasTemporaryLoot())
return EQUIP_ERR_ALREADY_LOOTED;
// do not allow unequipping gear except weapons, offhands, projectiles, relics in
// - combat
// - in-progress arenas
if ( !pProto->CanChangeEquipStateInCombat() )
{
if ( isInCombat() )
return EQUIP_ERR_NOT_IN_COMBAT;
if (BattleGround* bg = GetBattleGround())
if ( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
}
// prevent unequip item in process logout
if (GetSession()->isLogingOut())
return EQUIP_ERR_YOU_ARE_STUNNED;
if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
return EQUIP_ERR_OK;
}
InventoryResult Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
{
if (!pItem)
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
uint32 count = pItem->GetCount();
DEBUG_LOG( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
ItemPrototype const *pProto = pItem->GetProto();
if (!pProto)
return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
// item used
if (pItem->HasTemporaryLoot())
return EQUIP_ERR_ALREADY_LOOTED;
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
// check count of items (skip for auto move for same player from bank)
InventoryResult res = CanTakeMoreSimilarItems(pItem);
if (res != EQUIP_ERR_OK)
return res;
// in specific slot
if (bag != NULL_BAG && slot != NULL_SLOT)
{
if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
{
if (!pItem->IsBag())
return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
res = CanUseItem( pItem, not_loading );
if (res != EQUIP_ERR_OK)
return res;
}
res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
}
// not specific slot or have space for partly store only in specific slot
// in specific bag
if ( bag != NULL_BAG )
{
if ( pProto->InventoryType == INVTYPE_BAG )
{
Bag *pBag = (Bag*)pItem;
if ( pBag && !pBag->IsEmpty() )
return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
}
// search stack in bag for merge to
if ( pProto->Stackable != 1 )
{
if ( bag == INVENTORY_SLOT_BAG_0 )
{
res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
}
else
{
res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
if (res!=EQUIP_ERR_OK)
res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
}
}
// search free slot in bag
if ( bag == INVENTORY_SLOT_BAG_0 )
{
res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
}
else
{
res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
}
}
// not specific bag or have space for partly store only in specific bag
// search stack for merge to
if ( pProto->Stackable != 1 )
{
// in slots
res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
if (res != EQUIP_ERR_OK)
return res;
if (count == 0)
return EQUIP_ERR_OK;
// in special bags
if ( pProto->BagFamily )
{
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
continue;
if (count==0)
return EQUIP_ERR_OK;
}
}
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
continue;
if (count==0)
return EQUIP_ERR_OK;
}
}
// search free place in special bag
if ( pProto->BagFamily )
{
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
continue;
if (count==0)
return EQUIP_ERR_OK;
}
}
// search free space
res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
return res;
if (count==0)
return EQUIP_ERR_OK;
for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
if (res!=EQUIP_ERR_OK)
continue;
if (count==0)
return EQUIP_ERR_OK;
}
return EQUIP_ERR_BANK_FULL;
}
InventoryResult Player::CanUseItem(Item *pItem, bool direct_action) const
{
if (pItem)
{
DEBUG_LOG( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
if (!isAlive() && direct_action)
return EQUIP_ERR_YOU_ARE_DEAD;
//if (isStunned())
// return EQUIP_ERR_YOU_ARE_STUNNED;
ItemPrototype const *pProto = pItem->GetProto();
if (pProto)
{
if (pItem->IsBindedNotWith(this))
return EQUIP_ERR_DONT_OWN_THAT_ITEM;
InventoryResult msg = CanUseItem(pProto);
if (msg != EQUIP_ERR_OK)
return msg;
if (uint32 item_use_skill = pItem->GetSkill())
{
if (GetSkillValue(item_use_skill) == 0)
{
// armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
if (pProto->Class != ITEM_CLASS_ARMOR)
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
if (!ssd)
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
bool allowScaleSkill = false;
for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
{
SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
if (!skillInfo)
continue;
if (skillInfo->skillId != item_use_skill)
continue;
// can't learn
if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
continue;
if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
continue;
allowScaleSkill = true;
break;
}
if (!allowScaleSkill)
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
}
}
if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
return EQUIP_ERR_CANT_EQUIP_REPUTATION;
return EQUIP_ERR_OK;
}
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
InventoryResult Player::CanUseItem( ItemPrototype const *pProto ) const
{
// Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
if ( pProto )
{
if(!sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP))
{
if ((pProto->Flags2 & ITEM_FLAG2_HORDE_ONLY) && GetTeam() != HORDE)
return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
if ((pProto->Flags2 & ITEM_FLAG2_ALLIANCE_ONLY) && GetTeam() != ALLIANCE)
return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
}
if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
if ( pProto->RequiredSkill != 0 )
{
if ( GetSkillValue( pProto->RequiredSkill ) == 0 )
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
else if ( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
return EQUIP_ERR_CANT_EQUIP_SKILL;
}
if ( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
if ( getLevel() < pProto->RequiredLevel )
return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
return EQUIP_ERR_OK;
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
InventoryResult Player::CanUseAmmo( uint32 item ) const
{
DEBUG_LOG( "STORAGE: CanUseAmmo item = %u", item);
if ( !isAlive() )
return EQUIP_ERR_YOU_ARE_DEAD;
//if ( isStunned() )
// return EQUIP_ERR_YOU_ARE_STUNNED;
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
if ( pProto )
{
if ( pProto->InventoryType!= INVTYPE_AMMO )
return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
InventoryResult msg = CanUseItem(pProto);
if (msg != EQUIP_ERR_OK)
return msg;
/*if ( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
return EQUIP_ERR_CANT_EQUIP_REPUTATION;
*/
// Requires No Ammo
if (GetDummyAura(46699))
return EQUIP_ERR_BAG_FULL6;
return EQUIP_ERR_OK;
}
return EQUIP_ERR_ITEM_NOT_FOUND;
}
void Player::SetAmmo( uint32 item )
{
if(!item)
return;
// already set
if ( GetUInt32Value(PLAYER_AMMO_ID) == item )
return;
// check ammo
if (item)
{
InventoryResult msg = CanUseAmmo( item );
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, NULL, NULL, item);
return;
}
}
SetUInt32Value(PLAYER_AMMO_ID, item);
_ApplyAmmoBonuses();
}
void Player::RemoveAmmo()
{
SetUInt32Value(PLAYER_AMMO_ID, 0);
m_ammoDPS = 0.0f;
if (CanModifyStats())
UpdateDamagePhysical(RANGED_ATTACK);
}
// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId , AllowedLooterSet* allowedLooters)
{
uint32 count = 0;
for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
count += itr->count;
Item *pItem = Item::CreateItem(item, count, this, randomPropertyId);
if (pItem)
{
ResetCachedGearScore();
ItemAddedQuestCheck( item, count );
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, count);
pItem = StoreItem( dest, pItem, update );
if (allowedLooters && pItem->GetProto()->GetMaxStackSize() == 1 && pItem->IsSoulBound())
{
pItem->SetSoulboundTradeable(allowedLooters, this, true);
pItem->SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, GetTotalPlayedTime());
m_itemSoulboundTradeable.push_back(pItem);
// save data
std::ostringstream ss;
ss << "REPLACE INTO `item_soulbound_trade_data` VALUES (";
ss << pItem->GetGUIDLow();
ss << ", '";
for (AllowedLooterSet::iterator itr = allowedLooters->begin(); itr != allowedLooters->end(); ++itr)
ss << *itr << " ";
ss << "');";
CharacterDatabase.Execute(ss.str().c_str());
}
}
return pItem;
}
Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
{
if ( !pItem )
return NULL;
Item* lastItem = pItem;
uint32 entry = pItem->GetEntry();
for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
{
uint16 pos = itr->pos;
uint32 count = itr->count;
++itr;
if (itr == dest.end())
{
lastItem = _StoreItem(pos,pItem,count,false,update);
break;
}
lastItem = _StoreItem(pos,pItem,count,true,update);
}
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
return lastItem;
}
// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
{
if ( !pItem )
return NULL;
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
DEBUG_LOG( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
Item *pItem2 = GetItemByPos( bag, slot );
if (!pItem2)
{
if (clone)
pItem = pItem->CloneItem(count, this);
else
pItem->SetCount(count);
if (!pItem)
return NULL;
if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
(pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos)))
pItem->SetBinding( true );
if (bag == INVENTORY_SLOT_BAG_0)
{
m_items[slot] = pItem;
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetObjectGuid());
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, GetObjectGuid());
pItem->SetGuidValue(ITEM_FIELD_OWNER, GetObjectGuid());
pItem->SetSlot( slot );
pItem->SetContainer( NULL );
// need update known currency
if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
UpdateKnownCurrencies(pItem->GetEntry(), true);
if (IsInWorld() && update)
{
pItem->AddToWorld();
pItem->SendCreateUpdateToPlayer( this );
}
pItem->SetState(ITEM_CHANGED, this);
}
else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
{
pBag->StoreItem( slot, pItem, update );
if ( IsInWorld() && update )
{
pItem->AddToWorld();
pItem->SendCreateUpdateToPlayer( this );
}
pItem->SetState(ITEM_CHANGED, this);
pBag->SetState(ITEM_CHANGED, this);
}
AddEnchantmentDurations(pItem);
AddItemDurations(pItem);
// at place into not appropriate slot (bank, for example) remove aura
ApplyItemOnStoreSpell(pItem, IsEquipmentPos(pItem->GetBagSlot(), pItem->GetSlot()) || IsInventoryPos(pItem->GetBagSlot(), pItem->GetSlot()));
return pItem;
}
else
{
if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
(pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPPED && IsBagPos(pos)))
pItem2->SetBinding(true);
pItem2->SetCount( pItem2->GetCount() + count );
if (IsInWorld() && update)
pItem2->SendCreateUpdateToPlayer( this );
if (!clone)
{
// delete item (it not in any slot currently)
if (IsInWorld() && update)
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer( this );
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetOwnerGuid(GetObjectGuid()); // prevent error at next SetState in case trade/mail/buy from vendor
pItem->SetSoulboundTradeable(NULL, this, false);
RemoveTradeableItem(pItem);
pItem->SetState(ITEM_REMOVED, this);
}
// AddItemDurations(pItem2); - pItem2 already have duration listed for player
AddEnchantmentDurations(pItem2);
pItem2->SetState(ITEM_CHANGED, this);
return pItem2;
}
}
Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
{
if (Item *pItem = Item::CreateItem(item, 1, this))
{
ResetCachedGearScore();
ItemAddedQuestCheck( item, 1 );
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, 1);
return EquipItem( pos, pItem, update );
}
return NULL;
}
Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
{
AddEnchantmentDurations(pItem);
AddItemDurations(pItem);
uint8 bag = pos >> 8;
uint8 slot = pos & 255;
Item *pItem2 = GetItemByPos(bag, slot);
if (!pItem2)
{
VisualizeItem( slot, pItem);
if (isAlive())
{
ItemPrototype const *pProto = pItem->GetProto();
// item set bonuses applied only at equip and removed at unequip, and still active for broken items
if (pProto && pProto->ItemSet)
AddItemsSetItem(this, pItem);
_ApplyItemMods(pItem, slot, true);
ApplyItemOnStoreSpell(pItem, true);
// Weapons and also Totem/Relic/Sigil/etc
if (pProto && isInCombat() && (pProto->Class == ITEM_CLASS_WEAPON || pProto->InventoryType == INVTYPE_RELIC) && m_weaponChangeTimer == 0)
{
uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
if (getClass() == CLASS_ROGUE)
cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
if (!spellProto)
sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
else
{
m_weaponChangeTimer = spellProto->StartRecoveryTime;
WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
data << GetObjectGuid();
data << uint8(1);
data << uint32(cooldownSpell);
data << uint32(0);
GetSession()->SendPacket(&data);
}
}
}
if ( IsInWorld() && update )
{
pItem->AddToWorld();
pItem->SendCreateUpdateToPlayer( this );
}
ApplyEquipCooldown(pItem);
if ( slot == EQUIPMENT_SLOT_MAINHAND )
{
UpdateExpertise(BASE_ATTACK);
UpdateArmorPenetration();
}
else if ( slot == EQUIPMENT_SLOT_OFFHAND )
{
UpdateExpertise(OFF_ATTACK);
UpdateArmorPenetration();
}
}
else
{
pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
if ( IsInWorld() && update )
pItem2->SendCreateUpdateToPlayer( this );
// delete item (it not in any slot currently)
//pItem->DeleteFromDB();
if ( IsInWorld() && update )
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer( this );
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetOwnerGuid(GetObjectGuid()); // prevent error at next SetState in case trade/mail/buy from vendor
pItem->SetSoulboundTradeable(NULL, this, false);
RemoveTradeableItem(pItem);
pItem->SetState(ITEM_REMOVED, this);
pItem2->SetState(ITEM_CHANGED, this);
ApplyEquipCooldown(pItem2);
return pItem2;
}
// Apply Titan's Grip damage penalty if necessary
if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && HasTwoHandWeaponInOneHand() && !HasAura(49152))
CastSpell(this, 49152, true);
// only for full equip instead adding to stack
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
return pItem;
}
void Player::QuickEquipItem( uint16 pos, Item *pItem)
{
if ( pItem )
{
AddEnchantmentDurations(pItem);
AddItemDurations(pItem);
ApplyItemOnStoreSpell(pItem, true);
uint8 slot = pos & 255;
VisualizeItem( slot, pItem);
if ( IsInWorld() )
{
pItem->AddToWorld();
pItem->SendCreateUpdateToPlayer( this );
}
// Apply Titan's Grip damage penalty if necessary
if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && HasTwoHandWeaponInOneHand() && !HasAura(49152))
CastSpell(this, 49152, true);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, slot+1);
}
}
void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
{
if (pItem)
{
SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
}
else
{
SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
}
}
void Player::VisualizeItem( uint8 slot, Item *pItem)
{
if(!pItem)
return;
// check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
if ( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
pItem->SetBinding( true );
DEBUG_LOG( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
m_items[slot] = pItem;
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetObjectGuid());
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, GetObjectGuid());
pItem->SetGuidValue(ITEM_FIELD_OWNER, GetObjectGuid());
pItem->SetSlot( slot );
pItem->SetContainer( NULL );
if ( slot < EQUIPMENT_SLOT_END )
SetVisibleItemSlot(slot, pItem);
pItem->SetState(ITEM_CHANGED, this);
}
void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
{
// note: removeitem does not actually change the item
// it only takes the item out of storage temporarily
// note2: if removeitem is to be used for delinking
// the item must be removed from the player's updatequeue
if (Item *pItem = GetItemByPos(bag, slot))
{
DEBUG_LOG( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
if ( bag == INVENTORY_SLOT_BAG_0 )
{
if ( slot < INVENTORY_SLOT_BAG_END )
{
ItemPrototype const *pProto = pItem->GetProto();
// item set bonuses applied only at equip and removed at unequip, and still active for broken items
if (pProto && pProto->ItemSet)
RemoveItemsSetItem(this, pProto);
_ApplyItemMods(pItem, slot, false);
// remove item dependent auras and casts (only weapon and armor slots)
if (slot < EQUIPMENT_SLOT_END)
{
RemoveItemDependentAurasAndCasts(pItem);
// remove held enchantments, update expertise
if ( slot == EQUIPMENT_SLOT_MAINHAND )
{
if (pItem->GetItemSuffixFactor())
{
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
}
else
{
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
}
UpdateExpertise(BASE_ATTACK);
UpdateArmorPenetration();
}
else if ( slot == EQUIPMENT_SLOT_OFFHAND )
{
UpdateExpertise(OFF_ATTACK);
UpdateArmorPenetration();
}
}
}
// need update known currency
else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
UpdateKnownCurrencies(pItem->GetEntry(), false);
m_items[slot] = NULL;
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid());
if ( slot < EQUIPMENT_SLOT_END )
{
SetVisibleItemSlot(slot, NULL);
// Remove Titan's Grip damage penalty if necessary
if ((slot == EQUIPMENT_SLOT_MAINHAND || slot == EQUIPMENT_SLOT_OFFHAND) && CanTitanGrip() && !HasTwoHandWeaponInOneHand())
RemoveAurasDueToSpell(49152);
}
}
else
{
Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
if ( pBag )
pBag->RemoveItem(slot, update);
}
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid());
// pItem->SetGuidValue(ITEM_FIELD_OWNER, ObjectGuid()); not clear owner at remove (it will be set at store). This used in mail and auction code
pItem->SetSlot( NULL_SLOT );
//ApplyItemOnStoreSpell, for avoid re-apply will remove at _adding_ to not appropriate slot
if (IsInWorld() && update)
pItem->SendCreateUpdateToPlayer( this );
}
}
// Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
{
if (Item* it = GetItemByPos(bag,slot))
{
ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
RemoveItem(bag, slot, update);
// item atStore spell not removed in RemoveItem (for avoid reappaly in slots changes), so do it directly
if (IsEquipmentPos(bag, slot) || IsInventoryPos(bag, slot))
ApplyItemOnStoreSpell(it, false);
it->RemoveFromUpdateQueueOf(this);
if (it->IsInWorld())
{
it->RemoveFromWorld();
it->DestroyForPlayer( this );
}
}
}
// Common operation need to add item from inventory without delete in trade, guild bank, mail....
void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
{
// update quest counters
ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount());
// store item
Item* pLastItem = StoreItem(dest, pItem, update);
// only set if not merged to existing stack (pItem can be deleted already but we can compare pointers any way)
if (pLastItem == pItem)
{
// update owner for last item (this can be original item with wrong owner
if (pLastItem->GetOwnerGuid() != GetObjectGuid())
pLastItem->SetOwnerGuid(GetObjectGuid());
// if this original item then it need create record in inventory
// in case trade we already have item in other player inventory
pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
}
if (pLastItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BOP_TRADEABLE))
m_itemSoulboundTradeable.push_back(pLastItem);
}
void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
{
Item *pItem = GetItemByPos( bag, slot );
if ( pItem )
{
DEBUG_LOG( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
// start from destroy contained items (only equipped bag can have its)
if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
{
for (int i = 0; i < MAX_BAG_SIZE; ++i)
DestroyItem(slot, i, update);
}
if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED))
{
static SqlStatementID delGifts ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delGifts, "DELETE FROM character_gifts WHERE item_guid = ?");
stmt.PExecute(pItem->GetGUIDLow());
}
RemoveEnchantmentDurations(pItem);
RemoveItemDurations(pItem);
pItem->SetSoulboundTradeable(NULL, this, false);
RemoveTradeableItem(pItem);
if (IsEquipmentPos(bag, slot) || IsInventoryPos(bag, slot))
ApplyItemOnStoreSpell(pItem, false);
ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
if ( bag == INVENTORY_SLOT_BAG_0 )
{
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid());
// equipment and equipped bags can have applied bonuses
if ( slot < INVENTORY_SLOT_BAG_END )
{
ItemPrototype const *pProto = pItem->GetProto();
// item set bonuses applied only at equip and removed at unequip, and still active for broken items
if (pProto && pProto->ItemSet)
RemoveItemsSetItem(this, pProto);
_ApplyItemMods(pItem, slot, false);
}
if ( slot < EQUIPMENT_SLOT_END )
{
// remove item dependent auras and casts (only weapon and armor slots)
RemoveItemDependentAurasAndCasts(pItem);
// update expertise
if ( slot == EQUIPMENT_SLOT_MAINHAND )
{
UpdateExpertise(BASE_ATTACK);
UpdateArmorPenetration();
}
else if ( slot == EQUIPMENT_SLOT_OFFHAND )
{
UpdateExpertise(OFF_ATTACK);
UpdateArmorPenetration();
}
// equipment visual show
SetVisibleItemSlot(slot, NULL);
}
// need update known currency
else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
UpdateKnownCurrencies(pItem->GetEntry(), false);
m_items[slot] = NULL;
}
else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
pBag->RemoveItem(slot, update);
if ( IsInWorld() && update )
{
pItem->RemoveFromWorld();
pItem->DestroyForPlayer(this);
}
//pItem->SetOwnerGUID(0);
pItem->SetGuidValue(ITEM_FIELD_CONTAINED, ObjectGuid());
pItem->SetSlot( NULL_SLOT );
pItem->SetState(ITEM_REMOVED, this);
}
}
void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
{
DEBUG_LOG( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
uint32 remcount = 0;
// in inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
if (pItem->GetEntry() == item && !pItem->IsInTrade())
{
if (pItem->GetCount() + remcount <= count)
{
// all items in inventory can unequipped
remcount += pItem->GetCount();
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return;
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
pItem->SetCount( pItem->GetCount() - count + remcount );
if (IsInWorld() & update)
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
{
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
if (pItem->GetEntry() == item && !pItem->IsInTrade())
{
if (pItem->GetCount() + remcount <= count)
{
// all keys can be unequipped
remcount += pItem->GetCount();
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return;
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
pItem->SetCount( pItem->GetCount() - count + remcount );
if (IsInWorld() & update)
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
// in inventory bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
if (Item* pItem = pBag->GetItemByPos(j))
{
if (pItem->GetEntry() == item && !pItem->IsInTrade())
{
// all items in bags can be unequipped
if (pItem->GetCount() + remcount <= count)
{
remcount += pItem->GetCount();
DestroyItem( i, j, update );
if (remcount >= count)
return;
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
pItem->SetCount( pItem->GetCount() - count + remcount );
if (IsInWorld() && update)
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
}
}
// in equipment and bag list
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
{
if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
{
if (pItem->GetCount() + remcount <= count)
{
if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
{
remcount += pItem->GetCount();
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
if (remcount >= count)
return;
}
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
pItem->SetCount( pItem->GetCount() - count + remcount );
if (IsInWorld() & update)
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
return;
}
}
}
}
}
void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
{
DEBUG_LOG( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
// in inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
// in inventory bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem(i, j, update);
// in equipment and bag list
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
}
void Player::DestroyConjuredItems( bool update )
{
// used when entering arena
// destroys all conjured items
DEBUG_LOG( "STORAGE: DestroyConjuredItems" );
// in inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsConjuredConsumable())
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
// in inventory bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->IsConjuredConsumable())
DestroyItem( i, j, update);
// in equipment and bag list
for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (pItem->IsConjuredConsumable())
DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
}
void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
{
if(!pItem)
return;
DEBUG_LOG( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
if ( pItem->GetCount() <= count )
{
count -= pItem->GetCount();
DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
}
else
{
ItemRemovedQuestCheck( pItem->GetEntry(), count);
pItem->SetCount( pItem->GetCount() - count );
count = 0;
if ( IsInWorld() & update )
pItem->SendCreateUpdateToPlayer( this );
pItem->SetState(ITEM_CHANGED, this);
}
}
void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
{
uint8 srcbag = src >> 8;
uint8 srcslot = src & 255;
uint8 dstbag = dst >> 8;
uint8 dstslot = dst & 255;
Item *pSrcItem = GetItemByPos( srcbag, srcslot );
if (!pSrcItem)
{
SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
return;
}
if (pSrcItem->HasGeneratedLoot()) // prevent split looting item (stackable items can has only temporary loot and this meaning that loot window open)
{
//best error message found for attempting to split while looting
SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
return;
}
// not let split all items (can be only at cheating)
if (pSrcItem->GetCount() == count)
{
SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
return;
}
// not let split more existing items (can be only at cheating)
if (pSrcItem->GetCount() < count)
{
SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
return;
}
DEBUG_LOG( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
Item *pNewItem = pSrcItem->CloneItem( count, this );
if (!pNewItem)
{
SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
return;
}
if (IsInventoryPos(dst))
{
// change item amount before check (for unique max count check)
pSrcItem->SetCount( pSrcItem->GetCount() - count );
ItemPosCountVec dest;
InventoryResult msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
if (msg != EQUIP_ERR_OK)
{
delete pNewItem;
pSrcItem->SetCount( pSrcItem->GetCount() + count );
SendEquipError( msg, pSrcItem, NULL );
return;
}
if (IsInWorld())
pSrcItem->SendCreateUpdateToPlayer( this );
pSrcItem->SetState(ITEM_CHANGED, this);
StoreItem( dest, pNewItem, true);
}
else if (IsBankPos (dst))
{
// change item amount before check (for unique max count check)
pSrcItem->SetCount( pSrcItem->GetCount() - count );
ItemPosCountVec dest;
InventoryResult msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
if ( msg != EQUIP_ERR_OK )
{
delete pNewItem;
pSrcItem->SetCount( pSrcItem->GetCount() + count );
SendEquipError( msg, pSrcItem, NULL );
return;
}
if (IsInWorld())
pSrcItem->SendCreateUpdateToPlayer( this );
pSrcItem->SetState(ITEM_CHANGED, this);
BankItem( dest, pNewItem, true);
}
else if (IsEquipmentPos (dst))
{
// change item amount before check (for unique max count check), provide space for splitted items
pSrcItem->SetCount( pSrcItem->GetCount() - count );
uint16 dest;
InventoryResult msg = CanEquipItem( dstslot, dest, pNewItem, false );
if (msg != EQUIP_ERR_OK)
{
delete pNewItem;
pSrcItem->SetCount( pSrcItem->GetCount() + count );
SendEquipError( msg, pSrcItem, NULL );
return;
}
if (IsInWorld())
pSrcItem->SendCreateUpdateToPlayer( this );
pSrcItem->SetState(ITEM_CHANGED, this);
EquipItem( dest, pNewItem, true);
AutoUnequipOffhandIfNeed();
}
}
void Player::SwapItem( uint16 src, uint16 dst )
{
uint8 srcbag = src >> 8;
uint8 srcslot = src & 255;
uint8 dstbag = dst >> 8;
uint8 dstslot = dst & 255;
Item *pSrcItem = GetItemByPos( srcbag, srcslot );
Item *pDstItem = GetItemByPos( dstbag, dstslot );
if (!pSrcItem)
return;
DEBUG_LOG( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
if (!isAlive())
{
SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
return;
}
// SRC checks
// check unequip potability for equipped items and bank bags
if (IsEquipmentPos(src) || IsBagPos(src))
{
// bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
InventoryResult msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
if (msg != EQUIP_ERR_OK)
{
SendEquipError( msg, pSrcItem, pDstItem );
return;
}
}
// prevent put equipped/bank bag in self
if (IsBagPos(src) && srcslot == dstbag)
{
SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
return;
}
// prevent put equipped/bank bag in self
if (IsBagPos(dst) && dstslot == srcbag)
{
SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pDstItem, pSrcItem );
return;
}
// DST checks
if (pDstItem)
{
// check unequip potability for equipped items and bank bags
if (IsEquipmentPos ( dst ) || IsBagPos ( dst ))
{
// bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
InventoryResult msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
if (msg != EQUIP_ERR_OK)
{
SendEquipError( msg, pSrcItem, pDstItem );
return;
}
}
}
// NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
// or swap empty bag with another empty or not empty bag (with items exchange)
// Move case
if ( !pDstItem )
{
if ( IsInventoryPos( dst ) )
{
ItemPosCountVec dest;
InventoryResult msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pSrcItem, NULL );
return;
}
RemoveItem(srcbag, srcslot, true);
StoreItem( dest, pSrcItem, true);
}
else if ( IsBankPos ( dst ) )
{
ItemPosCountVec dest;
InventoryResult msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pSrcItem, NULL );
return;
}
RemoveItem(srcbag, srcslot, true);
BankItem( dest, pSrcItem, true);
}
else if ( IsEquipmentPos ( dst ) )
{
uint16 dest;
InventoryResult msg = CanEquipItem( dstslot, dest, pSrcItem, false );
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pSrcItem, NULL );
return;
}
RemoveItem(srcbag, srcslot, true);
EquipItem(dest, pSrcItem, true);
AutoUnequipOffhandIfNeed();
}
return;
}
// attempt merge to / fill target item
if(!pSrcItem->IsBag() && !pDstItem->IsBag())
{
InventoryResult msg;
ItemPosCountVec sDest;
uint16 eDest;
if ( IsInventoryPos( dst ) )
msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
else if ( IsBankPos ( dst ) )
msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
else if ( IsEquipmentPos ( dst ) )
msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
else
return;
// can be merge/fill
if (msg == EQUIP_ERR_OK)
{
if ( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
{
RemoveItem(srcbag, srcslot, true);
if ( IsInventoryPos( dst ) )
StoreItem( sDest, pSrcItem, true);
else if ( IsBankPos ( dst ) )
BankItem( sDest, pSrcItem, true);
else if ( IsEquipmentPos ( dst ) )
{
EquipItem( eDest, pSrcItem, true);
AutoUnequipOffhandIfNeed();
}
}
else
{
pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
pSrcItem->SetState(ITEM_CHANGED, this);
pDstItem->SetState(ITEM_CHANGED, this);
if ( IsInWorld() )
{
pSrcItem->SendCreateUpdateToPlayer( this );
pDstItem->SendCreateUpdateToPlayer( this );
}
}
return;
}
}
// impossible merge/fill, do real swap
InventoryResult msg;
// check src->dest move possibility
ItemPosCountVec sDest;
uint16 eDest = 0;
if ( IsInventoryPos( dst ) )
msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
else if ( IsBankPos( dst ) )
msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
else if ( IsEquipmentPos( dst ) )
{
msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
if ( msg == EQUIP_ERR_OK )
msg = CanUnequipItem( eDest, true );
}
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pSrcItem, pDstItem );
return;
}
// check dest->src move possibility
ItemPosCountVec sDest2;
uint16 eDest2 = 0;
if ( IsInventoryPos( src ) )
msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
else if ( IsBankPos( src ) )
msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
else if ( IsEquipmentPos( src ) )
{
msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
if ( msg == EQUIP_ERR_OK )
msg = CanUnequipItem( eDest2, true);
}
if ( msg != EQUIP_ERR_OK )
{
SendEquipError( msg, pDstItem, pSrcItem );
return;
}
// Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
if (pSrcItem->IsBag() && pDstItem->IsBag())
{
Bag* emptyBag = NULL;
Bag* fullBag = NULL;
if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
{
emptyBag = (Bag*)pSrcItem;
fullBag = (Bag*)pDstItem;
}
else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
{
emptyBag = (Bag*)pDstItem;
fullBag = (Bag*)pSrcItem;
}
// bag swap (with items exchange) case
if (emptyBag && fullBag)
{
ItemPrototype const* emotyProto = emptyBag->GetProto();
uint32 count = 0;
for(uint32 i=0; i < fullBag->GetBagSize(); ++i)
{
Item *bagItem = fullBag->GetItemByPos(i);
if (!bagItem)
continue;
ItemPrototype const* bagItemProto = bagItem->GetProto();
if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
{
// one from items not go to empty target bag
SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
return;
}
++count;
}
if (count > emptyBag->GetBagSize())
{
// too small targeted bag
SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
return;
}
// Items swap
count = 0; // will pos in new bag
for(uint32 i = 0; i< fullBag->GetBagSize(); ++i)
{
Item *bagItem = fullBag->GetItemByPos(i);
if (!bagItem)
continue;
fullBag->RemoveItem(i, true);
emptyBag->StoreItem(count, bagItem, true);
bagItem->SetState(ITEM_CHANGED, this);
++count;
}
}
}
// now do moves, remove...
RemoveItem(dstbag, dstslot, false);
RemoveItem(srcbag, srcslot, false);
// add to dest
if (IsInventoryPos(dst))
StoreItem(sDest, pSrcItem, true);
else if (IsBankPos(dst))
BankItem(sDest, pSrcItem, true);
else if (IsEquipmentPos(dst))
EquipItem(eDest, pSrcItem, true);
// add to src
if (IsInventoryPos(src))
StoreItem(sDest2, pDstItem, true);
else if (IsBankPos(src))
BankItem(sDest2, pDstItem, true);
else if (IsEquipmentPos(src))
EquipItem(eDest2, pDstItem, true);
AutoUnequipOffhandIfNeed();
}
void Player::AddItemToBuyBackSlot( Item *pItem )
{
if (pItem)
{
uint32 slot = m_currentBuybackSlot;
// if current back slot non-empty search oldest or free
if (m_items[slot])
{
uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
uint32 oldest_slot = BUYBACK_SLOT_START;
for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
{
// found empty
if (!m_items[i])
{
slot = i;
break;
}
uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
if (oldest_time > i_time)
{
oldest_time = i_time;
oldest_slot = i;
}
}
// find oldest
slot = oldest_slot;
}
RemoveItemFromBuyBackSlot( slot, true );
DEBUG_LOG( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
m_items[slot] = pItem;
time_t base = time(NULL);
uint32 etime = uint32(base - m_logintime + (30 * 3600));
uint32 eslot = slot - BUYBACK_SLOT_START;
SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetObjectGuid());
if (ItemPrototype const *pProto = pItem->GetProto())
SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
else
SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
// move to next (for non filled list is move most optimized choice)
if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
++m_currentBuybackSlot;
}
}
Item* Player::GetItemFromBuyBackSlot( uint32 slot )
{
DEBUG_LOG( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
return m_items[slot];
return NULL;
}
void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
{
DEBUG_LOG( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
{
Item *pItem = m_items[slot];
if (pItem)
{
pItem->RemoveFromWorld();
if (del) pItem->SetState(ITEM_REMOVED, this);
}
m_items[slot] = NULL;
uint32 eslot = slot - BUYBACK_SLOT_START;
SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), ObjectGuid());
SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
// if current backslot is filled set to now free slot
if (m_items[m_currentBuybackSlot])
m_currentBuybackSlot = slot;
}
}
void Player::SendEquipError( InventoryResult msg, Item* pItem, Item *pItem2, uint32 itemid /*= 0*/ ) const
{
DEBUG_LOG( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, 1+8+8+1);
data << uint8(msg);
if (msg != EQUIP_ERR_OK)
{
data << (pItem ? pItem->GetObjectGuid() : ObjectGuid());
data << (pItem2 ? pItem2->GetObjectGuid() : ObjectGuid());
data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
switch(msg)
{
case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
{
ItemPrototype const* proto = pItem ? pItem->GetProto() : ObjectMgr::GetItemPrototype(itemid);
data << uint32(proto ? proto->RequiredLevel : 0);
break;
}
case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
{
data << uint64(0);
data << uint32(0);
data << uint64(0);
break;
}
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS:
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS:
case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS:
{
ItemPrototype const* proto = pItem ? pItem->GetProto() : ObjectMgr::GetItemPrototype(itemid);
uint32 LimitCategory=proto ? proto->ItemLimitCategory : 0;
if (pItem)
// check unique-equipped on gems
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
if(!pGem)
continue;
// include for check equip another gems with same limit category for not equipped item (and then not counted)
uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
if ( msg == CanEquipUniqueItem(pGem, pItem->GetSlot(),gem_limit_count))
{
LimitCategory=pGem->ItemLimitCategory;
break;
}
}
data << uint32(LimitCategory);
break;
}
default:
break;
}
}
GetSession()->SendPacket(&data);
}
void Player::SendBuyError( BuyResult msg, Creature* pCreature, uint32 item, uint32 param )
{
DEBUG_LOG( "WORLD: Sent SMSG_BUY_FAILED" );
WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
data << (pCreature ? pCreature->GetObjectGuid() : ObjectGuid());
data << uint32(item);
if (param > 0)
data << uint32(param);
data << uint8(msg);
GetSession()->SendPacket(&data);
}
void Player::SendSellError( SellResult msg, Creature* pCreature, ObjectGuid itemGuid, uint32 param )
{
DEBUG_LOG( "WORLD: Sent SMSG_SELL_ITEM" );
WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
data << (pCreature ? pCreature->GetObjectGuid() : ObjectGuid());
data << ObjectGuid(itemGuid);
if (param > 0)
data << uint32(param);
data << uint8(msg);
GetSession()->SendPacket(&data);
}
void Player::TradeCancel(bool sendback)
{
if (m_trade)
{
Player* trader = m_trade->GetTrader();
// send yellow "Trade canceled" message to both traders
if (sendback)
GetSession()->SendCancelTrade();
trader->GetSession()->SendCancelTrade();
// cleanup
delete m_trade;
m_trade = NULL;
delete trader->m_trade;
trader->m_trade = NULL;
}
}
void Player::UpdateSoulboundTradeItems()
{
if (m_itemSoulboundTradeable.empty())
return;
// also checks for garbage data
for (ItemDurationList::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end();)
{
if (!*itr)
{
itr = m_itemSoulboundTradeable.erase(itr++);
continue;
}
if ((*itr)->GetOwnerGuid() != GetObjectGuid())
{
itr = m_itemSoulboundTradeable.erase(itr++);
continue;
}
if ((*itr)->CheckSoulboundTradeExpire())
{
itr = m_itemSoulboundTradeable.erase(itr++);
continue;
}
++itr;
}
}
void Player::RemoveTradeableItem(Item* item)
{
for (ItemDurationList::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end(); ++itr)
{
if ((*itr) == item)
{
m_itemSoulboundTradeable.erase(itr);
break;
}
}
}
void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
{
if (m_itemDuration.empty())
return;
DEBUG_LOG("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
{
Item* item = *itr;
++itr; // current element can be erased in UpdateDuration
if ((realtimeonly && (item->GetProto()->ExtraFlags & ITEM_EXTRA_REAL_TIME_DURATION)) || !realtimeonly)
item->UpdateDuration(this,time);
}
}
void Player::UpdateEnchantTime(uint32 time)
{
for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
{
MANGOS_ASSERT(itr->item);
next = itr;
if (!itr->item->GetEnchantmentId(itr->slot))
{
next = m_enchantDuration.erase(itr);
}
else if (itr->leftduration <= time)
{
ApplyEnchantment(itr->item, itr->slot, false, false);
itr->item->ClearEnchantment(itr->slot);
next = m_enchantDuration.erase(itr);
}
else if (itr->leftduration > time)
{
itr->leftduration -= time;
++next;
}
}
}
void Player::AddEnchantmentDurations(Item *item)
{
for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
{
if (!item->GetEnchantmentId(EnchantmentSlot(x)))
continue;
uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
if (duration > 0)
AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
}
}
void Player::RemoveEnchantmentDurations(Item *item)
{
for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
{
if (itr->item == item)
{
// save duration in item
item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
itr = m_enchantDuration.erase(itr);
}
else
++itr;
}
}
void Player::RemoveAllEnchantments(EnchantmentSlot slot)
{
// remove enchantments from equipped items first to clean up the m_enchantDuration list
for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
{
next = itr;
if (itr->slot == slot)
{
if (itr->item && itr->item->GetEnchantmentId(slot))
{
// remove from stats
ApplyEnchantment(itr->item, slot, false, false);
// remove visual
itr->item->ClearEnchantment(slot);
}
// remove from update list
next = m_enchantDuration.erase(itr);
}
else
++next;
}
// remove enchants from inventory items
// NOTE: no need to remove these from stats, since these aren't equipped
// in inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
if (pItem->GetEnchantmentId(slot))
pItem->ClearEnchantment(slot);
// in inventory bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
if (Item* pItem = pBag->GetItemByPos(j))
if (pItem->GetEnchantmentId(slot))
pItem->ClearEnchantment(slot);
}
// duration == 0 will remove item enchant
void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
{
if (!item)
return;
if (slot >= MAX_ENCHANTMENT_SLOT)
return;
for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
{
if (itr->item == item && itr->slot == slot)
{
itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
m_enchantDuration.erase(itr);
break;
}
}
if (item && duration > 0 )
{
GetSession()->SendItemEnchantTimeUpdate(GetObjectGuid(), item->GetObjectGuid(), slot, uint32(duration/1000));
m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
}
}
void Player::ApplyEnchantment(Item *item,bool apply)
{
for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
ApplyEnchantment(item, EnchantmentSlot(slot), apply);
}
void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
{
if (!item)
return;
if (!item->IsEquipped())
return;
// Don't apply ANY enchantment if item is broken! It's offlike and avoid many exploits with broken items.
// Not removing enchantments from broken items - not need.
if (item->IsBroken())
return;
if (slot >= MAX_ENCHANTMENT_SLOT)
return;
uint32 enchant_id = item->GetEnchantmentId(slot);
if (!enchant_id)
return;
SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if (!pEnchant)
return;
if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
return;
if ((pEnchant->requiredLevel) > ((Player*)this)->getLevel())
return;
if ((pEnchant->requiredSkill) > 0)
{
if ((pEnchant->requiredSkillValue) > (((Player*)this)->GetSkillValue(pEnchant->requiredSkill)))
return;
}
if (!item->IsBroken())
{
for (int s = 0; s < 3; ++s)
{
uint32 enchant_display_type = pEnchant->type[s];
uint32 enchant_amount = pEnchant->amount[s];
uint32 enchant_spell_id = pEnchant->spellid[s];
switch(enchant_display_type)
{
case ITEM_ENCHANTMENT_TYPE_NONE:
break;
case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
// processed in Player::CastItemCombatSpell
break;
case ITEM_ENCHANTMENT_TYPE_DAMAGE:
if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
break;
case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
if (enchant_spell_id)
{
if (apply)
{
int32 basepoints = 0;
// Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
if (item->GetItemRandomPropertyId())
{
ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
if (item_rand)
{
// Search enchant_amount
for (int k = 0; k < 3; ++k)
{
if (item_rand->enchant_id[k] == enchant_id)
{
basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
break;
}
}
}
}
// Cast custom spell vs all equal basepoints getted from enchant_amount
if (basepoints)
CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
else
CastSpell(this, enchant_spell_id, true, item);
}
else
RemoveAurasDueToItemSpell(item, enchant_spell_id);
}
break;
case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
if (!enchant_amount)
{
ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
if (item_rand)
{
for (int k = 0; k < 3; ++k)
{
if (item_rand->enchant_id[k] == enchant_id)
{
enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
break;
}
}
}
}
HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
break;
case ITEM_ENCHANTMENT_TYPE_STAT:
{
if (!enchant_amount)
{
ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
if (item_rand_suffix)
{
for (int k = 0; k < 3; ++k)
{
if (item_rand_suffix->enchant_id[k] == enchant_id)
{
enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
break;
}
}
}
}
DEBUG_LOG("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
switch (enchant_spell_id)
{
case ITEM_MOD_MANA:
DEBUG_LOG("+ %u MANA",enchant_amount);
HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
break;
case ITEM_MOD_HEALTH:
DEBUG_LOG("+ %u HEALTH",enchant_amount);
HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
break;
case ITEM_MOD_AGILITY:
DEBUG_LOG("+ %u AGILITY",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_AGILITY, float(enchant_amount), apply);
break;
case ITEM_MOD_STRENGTH:
DEBUG_LOG("+ %u STRENGTH",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_STRENGTH, float(enchant_amount), apply);
break;
case ITEM_MOD_INTELLECT:
DEBUG_LOG("+ %u INTELLECT",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_INTELLECT, float(enchant_amount), apply);
break;
case ITEM_MOD_SPIRIT:
DEBUG_LOG("+ %u SPIRIT",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_SPIRIT, float(enchant_amount), apply);
break;
case ITEM_MOD_STAMINA:
DEBUG_LOG("+ %u STAMINA",enchant_amount);
HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
ApplyStatBuffMod(STAT_STAMINA, float(enchant_amount), apply);
break;
case ITEM_MOD_DEFENSE_SKILL_RATING:
((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
DEBUG_LOG("+ %u DEFENCE", enchant_amount);
break;
case ITEM_MOD_DODGE_RATING:
((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
DEBUG_LOG("+ %u DODGE", enchant_amount);
break;
case ITEM_MOD_PARRY_RATING:
((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
DEBUG_LOG("+ %u PARRY", enchant_amount);
break;
case ITEM_MOD_BLOCK_RATING:
((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
DEBUG_LOG("+ %u SHIELD_BLOCK", enchant_amount);
break;
case ITEM_MOD_HIT_MELEE_RATING:
((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
DEBUG_LOG("+ %u MELEE_HIT", enchant_amount);
break;
case ITEM_MOD_HIT_RANGED_RATING:
((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
DEBUG_LOG("+ %u RANGED_HIT", enchant_amount);
break;
case ITEM_MOD_HIT_SPELL_RATING:
((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u SPELL_HIT", enchant_amount);
break;
case ITEM_MOD_CRIT_MELEE_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
DEBUG_LOG("+ %u MELEE_CRIT", enchant_amount);
break;
case ITEM_MOD_CRIT_RANGED_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
DEBUG_LOG("+ %u RANGED_CRIT", enchant_amount);
break;
case ITEM_MOD_CRIT_SPELL_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u SPELL_CRIT", enchant_amount);
break;
// Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
// in Enchantments
// case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
// break;
// case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
// break;
// case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
// break;
// case ITEM_MOD_HASTE_MELEE_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
// break;
// case ITEM_MOD_HASTE_RANGED_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
// break;
case ITEM_MOD_HASTE_SPELL_RATING:
((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
break;
case ITEM_MOD_HIT_RATING:
((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u HIT", enchant_amount);
break;
case ITEM_MOD_CRIT_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u CRITICAL", enchant_amount);
break;
// Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
// case ITEM_MOD_HIT_TAKEN_RATING:
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
// ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
// break;
// case ITEM_MOD_CRIT_TAKEN_RATING:
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
// ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
// break;
case ITEM_MOD_RESILIENCE_RATING:
((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u RESILIENCE", enchant_amount);
break;
case ITEM_MOD_HASTE_RATING:
((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
DEBUG_LOG("+ %u HASTE", enchant_amount);
break;
case ITEM_MOD_EXPERTISE_RATING:
((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
DEBUG_LOG("+ %u EXPERTISE", enchant_amount);
break;
case ITEM_MOD_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
DEBUG_LOG("+ %u ATTACK_POWER", enchant_amount);
break;
case ITEM_MOD_RANGED_ATTACK_POWER:
HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
DEBUG_LOG("+ %u RANGED_ATTACK_POWER", enchant_amount);
break;
case ITEM_MOD_MANA_REGENERATION:
((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
DEBUG_LOG("+ %u MANA_REGENERATION", enchant_amount);
break;
case ITEM_MOD_ARMOR_PENETRATION_RATING:
((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
DEBUG_LOG("+ %u ARMOR PENETRATION", enchant_amount);
break;
case ITEM_MOD_SPELL_POWER:
((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
DEBUG_LOG("+ %u SPELL_POWER", enchant_amount);
break;
case ITEM_MOD_HEALTH_REGEN:
((Player*)this)->ApplyHealthRegenBonus(enchant_amount, apply);
DEBUG_LOG("+ %u HEALTH_REGENERATION", enchant_amount);
break;
case ITEM_MOD_BLOCK_VALUE:
HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(enchant_amount), apply);
break;
case ITEM_MOD_FERAL_ATTACK_POWER:
case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
default:
break;
}
break;
}
case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
{
if (getClass() == CLASS_SHAMAN)
{
float addValue = 0.0f;
if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
{
addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
}
else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
{
addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
}
}
break;
}
case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
// processed in Player::CastItemUseSpell
break;
case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
// nothing do..
break;
default:
sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
break;
} /*switch(enchant_display_type)*/
} /*for*/
}
// visualize enchantment at player and equipped items
if (slot == PERM_ENCHANTMENT_SLOT)
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
if (slot == TEMP_ENCHANTMENT_SLOT)
SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
if (apply_dur)
{
if (apply)
{
// set duration
uint32 duration = item->GetEnchantmentDuration(slot);
if (duration > 0)
AddEnchantmentDuration(item, slot, duration);
}
else
{
// duration == 0 will remove EnchantDuration
AddEnchantmentDuration(item, slot, 0);
}
}
}
void Player::SendEnchantmentDurations()
{
for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
{
GetSession()->SendItemEnchantTimeUpdate(GetObjectGuid(), itr->item->GetObjectGuid(), itr->slot, uint32(itr->leftduration) / 1000);
}
}
void Player::SendItemDurations()
{
for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
{
(*itr)->SendTimeUpdate(this);
}
}
void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
{
if(!item) // prevent crash
return;
// last check 2.0.10
WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
data << GetObjectGuid(); // player GUID
data << uint32(received); // 0=looted, 1=from npc
data << uint32(created); // 0=received, 1=created
data << uint32(1); // IsShowChatMessage
data << uint8(item->GetBagSlot()); // bagslot
// item slot, but when added to stack: 0xFFFFFFFF
data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
data << uint32(item->GetEntry()); // item id
data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
data << uint32(item->GetItemRandomPropertyId()); // random item property id
data << uint32(count); // count of items
data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
if (broadcast && GetGroup())
GetGroup()->BroadcastPacket(&data, true);
else
GetSession()->SendPacket(&data);
}
/*********************************************************/
/*** GOSSIP SYSTEM ***/
/*********************************************************/
void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
{
PlayerMenu* pMenu = PlayerTalkClass;
pMenu->ClearMenus();
pMenu->GetGossipMenu().SetMenuId(menuId);
GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId);
// prepares quest menu when true
bool canSeeQuests = menuId == GetDefaultGossipMenuForSource(pSource);
// if canSeeQuests (the default, top level menu) and no menu options exist for this, use options from default options
if (pMenuItemBounds.first == pMenuItemBounds.second && canSeeQuests)
pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0);
bool canTalkToCredit = pSource->GetTypeId() == TYPEID_UNIT;
for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
{
bool hasMenuItem = true;
if (!isGameMaster()) // Let GM always see menu items regardless of conditions
{
if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
{
if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER)
canSeeQuests = false;
continue;
}
if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
{
if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER)
canSeeQuests = false;
continue;
}
if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
{
if (itr->second.option_id == GOSSIP_OPTION_QUESTGIVER)
canSeeQuests = false;
continue;
}
}
if (pSource->GetTypeId() == TYPEID_UNIT)
{
Creature *pCreature = (Creature*)pSource;
uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
if (!(itr->second.npc_option_npcflag & npcflags))
continue;
switch(itr->second.option_id)
{
case GOSSIP_OPTION_GOSSIP:
if (itr->second.action_menu_id != 0) // has sub menu (or close gossip), so do not "talk" with this NPC yet
canTalkToCredit = false;
break;
case GOSSIP_OPTION_QUESTGIVER:
hasMenuItem = false;
break;
case GOSSIP_OPTION_ARMORER:
hasMenuItem = false; // added in special mode
break;
case GOSSIP_OPTION_SPIRITHEALER:
if (!isDead())
hasMenuItem = false;
break;
case GOSSIP_OPTION_VENDOR:
{
VendorItemData const* vItems = pCreature->GetVendorItems();
VendorItemData const* tItems = pCreature->GetVendorTemplateItems();
if ((!vItems || vItems->Empty()) && (!tItems || tItems->Empty()))
{
sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
hasMenuItem = false;
}
break;
}
case GOSSIP_OPTION_TRAINER:
// pet trainers not have spells in fact now
/* FIXME: gossip menu with single unlearn pet talents option not show by some reason
if (pCreature->GetCreatureInfo()->trainer_type == TRAINER_TYPE_PETS)
hasMenuItem = false;
else */
if (!pCreature->IsTrainerOf(this, false))
hasMenuItem = false;
break;
case GOSSIP_OPTION_UNLEARNTALENTS:
if (!pCreature->CanTrainAndResetTalentsOf(this))
hasMenuItem = false;
break;
case GOSSIP_OPTION_UNLEARNPETSKILLS:
if (pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
hasMenuItem = false;
else if (Pet * pet = GetPet())
{
if (pet->getPetType() != HUNTER_PET || pet->m_spells.size() <= 1)
hasMenuItem = false;
}
else
hasMenuItem = false;
break;
case GOSSIP_OPTION_TAXIVENDOR:
if (GetSession()->SendLearnNewTaxiNode(pCreature))
return;
break;
case GOSSIP_OPTION_BATTLEFIELD:
if (!pCreature->CanInteractWithBattleMaster(this, false))
hasMenuItem = false;
break;
case GOSSIP_OPTION_STABLEPET:
if (getClass() != CLASS_HUNTER)
hasMenuItem = false;
break;
case GOSSIP_OPTION_SPIRITGUIDE:
case GOSSIP_OPTION_INNKEEPER:
case GOSSIP_OPTION_BANKER:
case GOSSIP_OPTION_PETITIONER:
case GOSSIP_OPTION_TABARDDESIGNER:
case GOSSIP_OPTION_AUCTIONEER:
case GOSSIP_OPTION_MAILBOX:
break; // no checks
default:
sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
hasMenuItem = false;
break;
}
}
else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
{
GameObject *pGo = (GameObject*)pSource;
switch(itr->second.option_id)
{
case GOSSIP_OPTION_QUESTGIVER:
hasMenuItem = false;
break;
case GOSSIP_OPTION_GOSSIP:
if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
hasMenuItem = false;
break;
default:
hasMenuItem = false;
break;
}
}
if (hasMenuItem)
{
std::string strOptionText = itr->second.option_text;
std::string strBoxText = itr->second.box_text;
int loc_idx = GetSession()->GetSessionDbLocaleIndex();
if (loc_idx >= 0)
{
uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry))
{
if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
strOptionText = no->OptionText[loc_idx];
if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
strBoxText = no->BoxText[loc_idx];
}
}
pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
}
}
if (canSeeQuests)
PrepareQuestMenu(pSource->GetObjectGuid());
if (canTalkToCredit)
{
if (pSource->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP) && !(((Creature*)pSource)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_TALKTO_CREDIT))
TalkedToCreature(pSource->GetEntry(), pSource->GetObjectGuid());
}
// some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
/*if (pMenu->Empty())
{
if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
{
// output error message if need
pCreature->IsTrainerOf(this, true);
}
if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
{
// output error message if need
pCreature->CanInteractWithBattleMaster(this, true);
}
}*/
}
void Player::SendPreparedGossip(WorldObject *pSource)
{
if (!pSource)
return;
if (pSource->GetTypeId() == TYPEID_UNIT)
{
// in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
{
SendPreparedQuest(pSource->GetObjectGuid());
return;
}
}
else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
{
// probably need to find a better way here
if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
{
SendPreparedQuest(pSource->GetObjectGuid());
return;
}
}
// in case non empty gossip menu (that not included quests list size) show it
// (quest entries from quest menu will be included in list)
uint32 textId = GetGossipTextId(pSource);
if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
textId = GetGossipTextId(menuId, pSource);
PlayerTalkClass->SendGossipMenu(textId, pSource->GetObjectGuid());
}
void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
{
GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
if (gossipListId >= gossipmenu.MenuItemCount())
return;
// if not same, then something funky is going on
if (menuId != gossipmenu.GetMenuId())
return;
GossipMenuItem const& menu_item = gossipmenu.GetItem(gossipListId);
uint32 gossipOptionId = menu_item.m_gOptionId;
ObjectGuid guid = pSource->GetObjectGuid();
uint32 moneyTake = menu_item.m_gBoxMoney;
// if this function called and player have money for pay MoneyTake or cheating, proccess both cases
if (moneyTake > 0)
{
if (GetMoney() >= moneyTake)
ModifyMoney(-int32(moneyTake));
else
return; // cheating
}
if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
{
if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
{
sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
return;
}
}
GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
switch (gossipOptionId)
{
case GOSSIP_OPTION_GOSSIP:
{
if (pMenuData.m_gAction_poi)
PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
// send new menu || close gossip || stay at current menu
if (pMenuData.m_gAction_menu > 0)
{
PrepareGossipMenu(pSource, uint32(pMenuData.m_gAction_menu));
SendPreparedGossip(pSource);
}
else if (pMenuData.m_gAction_menu < 0)
{
PlayerTalkClass->CloseGossip();
TalkedToCreature(pSource->GetEntry(), pSource->GetObjectGuid());
}
break;
}
case GOSSIP_OPTION_SPIRITHEALER:
if (isDead())
((Creature*)pSource)->CastSpell(((Creature*)pSource), 17251, true, NULL, NULL, GetObjectGuid());
break;
case GOSSIP_OPTION_QUESTGIVER:
PrepareQuestMenu(guid);
SendPreparedQuest(guid);
break;
case GOSSIP_OPTION_VENDOR:
case GOSSIP_OPTION_ARMORER:
GetSession()->SendListInventory(guid);
break;
case GOSSIP_OPTION_STABLEPET:
GetSession()->SendStablePet(guid);
break;
case GOSSIP_OPTION_TRAINER:
GetSession()->SendTrainerList(guid);
break;
case GOSSIP_OPTION_UNLEARNTALENTS:
PlayerTalkClass->CloseGossip();
SendTalentWipeConfirm(guid);
break;
case GOSSIP_OPTION_UNLEARNPETSKILLS:
PlayerTalkClass->CloseGossip();
SendPetSkillWipeConfirm();
break;
case GOSSIP_OPTION_TAXIVENDOR:
GetSession()->SendTaxiMenu(((Creature*)pSource));
break;
case GOSSIP_OPTION_INNKEEPER:
PlayerTalkClass->CloseGossip();
SetBindPoint(guid);
break;
case GOSSIP_OPTION_BANKER:
GetSession()->SendShowBank(guid);
break;
case GOSSIP_OPTION_PETITIONER:
PlayerTalkClass->CloseGossip();
GetSession()->SendPetitionShowList(guid);
break;
case GOSSIP_OPTION_TABARDDESIGNER:
PlayerTalkClass->CloseGossip();
GetSession()->SendTabardVendorActivate(guid);
break;
case GOSSIP_OPTION_AUCTIONEER:
GetSession()->SendAuctionHello(((Creature*)pSource));
break;
case GOSSIP_OPTION_MAILBOX:
PlayerTalkClass->CloseGossip();
GetSession()->SendShowMailBox(guid);
break;
case GOSSIP_OPTION_SPIRITGUIDE:
PrepareGossipMenu(pSource);
SendPreparedGossip(pSource);
break;
case GOSSIP_OPTION_BATTLEFIELD:
{
BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
if (bgTypeId == BATTLEGROUND_TYPE_NONE)
{
sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
return;
}
GetSession()->SendBattlegGroundList(guid, bgTypeId);
break;
}
}
if (pMenuData.m_gAction_script)
{
if (pSource->GetTypeId() == TYPEID_UNIT)
GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
}
}
uint32 Player::GetGossipTextId(WorldObject *pSource)
{
if (!pSource || pSource->GetTypeId() != TYPEID_UNIT)
return DEFAULT_GOSSIP_MESSAGE;
if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetGUIDLow()))
return pos;
return DEFAULT_GOSSIP_MESSAGE;
}
uint32 Player::GetGossipTextId(uint32 menuId, WorldObject* pSource)
{
uint32 textId = DEFAULT_GOSSIP_MESSAGE;
if (!menuId)
return textId;
GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId);
for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
{
if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
{
textId = itr->second.text_id;
// Start related script
if (itr->second.script_id)
GetMap()->ScriptsStart(sGossipScripts, itr->second.script_id, this, pSource);
break;
}
}
return textId;
}
uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
{
if (pSource->GetTypeId() == TYPEID_UNIT)
return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
return 0;
}
/*********************************************************/
/*** QUEST SYSTEM ***/
/*********************************************************/
void Player::PrepareQuestMenu(ObjectGuid guid)
{
QuestRelationsMapBounds rbounds;
QuestRelationsMapBounds irbounds;
// pets also can have quests
if (Creature *pCreature = GetMap()->GetAnyTypeCreature(guid))
{
rbounds = sObjectMgr.GetCreatureQuestRelationsMapBounds(pCreature->GetEntry());
irbounds = sObjectMgr.GetCreatureQuestInvolvedRelationsMapBounds(pCreature->GetEntry());
}
else
{
//we should obtain map pointer from GetMap() in 99% of cases. Special case
//only for quests which cast teleport spells on player
Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
MANGOS_ASSERT(_map);
if (GameObject *pGameObject = _map->GetGameObject(guid))
{
rbounds = sObjectMgr.GetGOQuestRelationsMapBounds(pGameObject->GetEntry());
irbounds = sObjectMgr.GetGOQuestInvolvedRelationsMapBounds(pGameObject->GetEntry());
}
else
return;
}
QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
qm.ClearMenu();
for(QuestRelationsMap::const_iterator itr = irbounds.first; itr != irbounds.second; ++itr)
{
uint32 quest_id = itr->second;
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (!pQuest || !pQuest->IsActive())
continue;
QuestStatus status = GetQuestStatus(quest_id);
if (status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(quest_id))
qm.AddMenuItem(quest_id, 4);
else if (status == QUEST_STATUS_INCOMPLETE)
qm.AddMenuItem(quest_id, 4);
else if (status == QUEST_STATUS_AVAILABLE)
qm.AddMenuItem(quest_id, 2);
}
for(QuestRelationsMap::const_iterator itr = rbounds.first; itr != rbounds.second; ++itr)
{
uint32 quest_id = itr->second;
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (!pQuest || !pQuest->IsActive())
continue;
QuestStatus status = GetQuestStatus(quest_id);
if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
qm.AddMenuItem(quest_id, 4);
else if (status == QUEST_STATUS_NONE && CanTakeQuest(pQuest, false))
qm.AddMenuItem(quest_id, 2);
}
}
void Player::SendPreparedQuest(ObjectGuid guid)
{
QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
if (questMenu.Empty())
return;
QuestMenuItem const& qmi0 = questMenu.GetItem(0);
uint32 icon = qmi0.m_qIcon;
// single element case
if (questMenu.MenuItemCount() == 1)
{
// Auto open -- maybe also should verify there is no greeting
uint32 quest_id = qmi0.m_qId;
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (pQuest)
{
if (icon == 4 && !GetQuestRewardStatus(quest_id))
PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
else if (icon == 4)
PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
// Send completable on repeatable and autoCompletable quest if player don't have quest
// TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDailyOrWeekly())
PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
else
PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
}
}
// multiply entries
else
{
QEmote qe;
qe._Delay = 0;
qe._Emote = 0;
std::string title = "";
// need pet case for some quests
if (Creature *pCreature = GetMap()->GetAnyTypeCreature(guid))
{
uint32 textid = GetGossipTextId(pCreature);
GossipText const* gossiptext = sObjectMgr.GetGossipText(textid);
if (!gossiptext)
{
qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
title = "";
}
else
{
qe = gossiptext->Options[0].Emotes[0];
int loc_idx = GetSession()->GetSessionDbLocaleIndex();
std::string title0 = gossiptext->Options[0].Text_0;
std::string title1 = gossiptext->Options[0].Text_1;
sObjectMgr.GetNpcTextLocaleStrings0(textid, loc_idx, &title0, &title1);
title = !title0.empty() ? title0 : title1;
}
}
PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
}
}
bool Player::IsActiveQuest( uint32 quest_id ) const
{
QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
}
bool Player::IsCurrentQuest(uint32 quest_id, uint8 completed_or_not) const
{
QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
if (itr == mQuestStatus.end())
return false;
switch (completed_or_not)
{
case 1:
return itr->second.m_status == QUEST_STATUS_INCOMPLETE;
case 2:
return itr->second.m_status == QUEST_STATUS_COMPLETE && !itr->second.m_rewarded;
default:
return itr->second.m_status == QUEST_STATUS_INCOMPLETE || (itr->second.m_status == QUEST_STATUS_COMPLETE && !itr->second.m_rewarded);
}
}
Quest const* Player::GetNextQuest(ObjectGuid guid, Quest const *pQuest)
{
QuestRelationsMapBounds rbounds;
if (Creature *pCreature = GetMap()->GetAnyTypeCreature(guid))
{
rbounds = sObjectMgr.GetCreatureQuestRelationsMapBounds(pCreature->GetEntry());
}
else
{
//we should obtain map pointer from GetMap() in 99% of cases. Special case
//only for quests which cast teleport spells on player
Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
MANGOS_ASSERT(_map);
if (GameObject *pGameObject = _map->GetGameObject(guid))
{
rbounds = sObjectMgr.GetGOQuestRelationsMapBounds(pGameObject->GetEntry());
}
else
return NULL;
}
uint32 nextQuestID = pQuest->GetNextQuestInChain();
for(QuestRelationsMap::const_iterator itr = rbounds.first; itr != rbounds.second; ++itr)
{
if (itr->second == nextQuestID)
return sObjectMgr.GetQuestTemplate(nextQuestID);
}
return NULL;
}
bool Player::CanSeeStartQuest(Quest const *pQuest) const
{
if (SatisfyQuestClass(pQuest, false) && SatisfyQuestRace(pQuest, false) && SatisfyQuestSkill(pQuest, false) &&
SatisfyQuestExclusiveGroup(pQuest, false) && SatisfyQuestReputation(pQuest, false) &&
SatisfyQuestPreviousQuest(pQuest, false) && SatisfyQuestNextChain(pQuest, false) &&
SatisfyQuestPrevChain(pQuest, false) && SatisfyQuestDay(pQuest, false) && SatisfyQuestWeek(pQuest, false) &&
SatisfyQuestMonth(pQuest, false) &&
pQuest->IsActive())
{
return int32(getLevel()) + sWorld.getConfig(CONFIG_INT32_QUEST_HIGH_LEVEL_HIDE_DIFF) >= int32(pQuest->GetMinLevel());
}
return false;
}
bool Player::CanTakeQuest(Quest const *pQuest, bool msg) const
{
return SatisfyQuestStatus(pQuest, msg) && SatisfyQuestExclusiveGroup(pQuest, msg) &&
SatisfyQuestClass(pQuest, msg) && SatisfyQuestRace(pQuest, msg) && SatisfyQuestLevel(pQuest, msg) &&
SatisfyQuestSkill(pQuest, msg) && SatisfyQuestReputation(pQuest, msg) &&
SatisfyQuestPreviousQuest(pQuest, msg) && SatisfyQuestTimed(pQuest, msg) &&
SatisfyQuestNextChain(pQuest, msg) && SatisfyQuestPrevChain(pQuest, msg) &&
SatisfyQuestDay(pQuest, msg) && SatisfyQuestWeek(pQuest, msg) && SatisfyQuestMonth(pQuest, msg) &&
pQuest->IsActive();
}
bool Player::CanAddQuest(Quest const *pQuest, bool msg) const
{
if (!SatisfyQuestLog(msg))
return false;
if (!CanGiveQuestSourceItemIfNeed(pQuest))
return false;
return true;
}
bool Player::CanCompleteQuest(uint32 quest_id) const
{
if (!quest_id)
return false;
QuestStatusMap::const_iterator q_itr = mQuestStatus.find(quest_id);
// some quests can be auto taken and auto completed in one step
QuestStatus status = q_itr != mQuestStatus.end() ? q_itr->second.m_status : QUEST_STATUS_NONE;
if (status == QUEST_STATUS_COMPLETE)
return false; // not allow re-complete quest
Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
if (!qInfo)
return false;
// only used for "flag" quests and not real in-game quests
if (qInfo->HasQuestFlag(QUEST_FLAGS_AUTO_REWARDED))
{
// a few checks, not all "satisfy" is needed
if (SatisfyQuestPreviousQuest(qInfo, false) && SatisfyQuestLevel(qInfo, false) &&
SatisfyQuestSkill(qInfo, false) && SatisfyQuestRace(qInfo, false) && SatisfyQuestClass(qInfo, false))
return true;
return false;
}
// Anti WPE for client command /script CompleteQuest() on quests with AutoComplete flag
if (status == QUEST_STATUS_NONE)
{
for (uint32 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (qInfo->ReqItemCount[i] != 0 &&
GetItemCount(qInfo->ReqItemId[i]) < qInfo->ReqItemCount[i])
{
return false;
}
}
}
// auto complete quest
if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
return true;
if (status != QUEST_STATUS_INCOMPLETE)
return false;
// incomplete quest have status data
QuestStatusData const& q_status = q_itr->second;
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
{
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i])
return false;
}
}
if (qInfo->HasSpecialFlag(QuestSpecialFlags(QUEST_SPECIAL_FLAG_KILL_OR_CAST | QUEST_SPECIAL_FLAG_SPEAKTO)))
{
for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
{
if (qInfo->ReqCreatureOrGOId[i] == 0)
continue;
if (qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i])
return false;
}
}
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_EXPLORATION_OR_EVENT) && !q_status.m_explored)
return false;
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED) && q_status.m_timer == 0)
return false;
if (qInfo->GetRewOrReqMoney() < 0)
{
if (GetMoney() < uint32(-qInfo->GetRewOrReqMoney()))
return false;
}
uint32 repFacId = qInfo->GetRepObjectiveFaction();
if (repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue())
return false;
return true;
}
bool Player::CanCompleteRepeatableQuest(Quest const *pQuest) const
{
// Solve problem that player don't have the quest and try complete it.
// if repeatable she must be able to complete event if player don't have it.
// Seem that all repeatable quest are DELIVER Flag so, no need to add more.
if (!CanTakeQuest(pQuest, false))
return false;
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
if (pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]))
return false;
if (!CanRewardQuest(pQuest, false))
return false;
return true;
}
bool Player::CanRewardQuest(Quest const *pQuest, bool msg) const
{
// not auto complete quest and not completed quest (only cheating case, then ignore without message)
if (!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
return false;
// daily quest can't be rewarded (25 daily quest already completed)
if (!SatisfyQuestDay(pQuest, true) || !SatisfyQuestWeek(pQuest, true) || !SatisfyQuestMonth(pQuest, true))
return false;
// rewarded and not repeatable quest (only cheating case, then ignore without message)
if (GetQuestRewardStatus(pQuest->GetQuestId()))
return false;
// prevent receive reward with quest items in bank
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
{
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (pQuest->ReqItemCount[i] != 0 &&
GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i])
{
if (msg)
SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, pQuest->ReqItemId[i]);
return false;
}
}
}
// prevent receive reward with low money and GetRewOrReqMoney() < 0
if (pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()))
return false;
return true;
}
bool Player::CanRewardQuest(Quest const *pQuest, uint32 reward, bool msg) const
{
// prevent receive reward with quest items in bank or for not completed quest
if (!CanRewardQuest(pQuest,msg))
return false;
if (pQuest->GetRewChoiceItemsCount() > 0)
{
if (pQuest->RewChoiceItemId[reward])
{
ItemPosCountVec dest;
InventoryResult res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
if (res != EQUIP_ERR_OK)
{
SendEquipError(res, NULL, NULL, pQuest->RewChoiceItemId[reward]);
return false;
}
}
}
if (pQuest->GetRewItemsCount() > 0)
{
for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
{
if (pQuest->RewItemId[i])
{
ItemPosCountVec dest;
InventoryResult res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
if (res != EQUIP_ERR_OK)
{
SendEquipError(res, NULL, NULL);
return false;
}
}
}
}
return true;
}
void Player::SendPetTameFailure(PetTameFailureReason reason)
{
WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
data << uint8(reason);
GetSession()->SendPacket(&data);
}
void Player::AddQuest( Quest const *pQuest, Object *questGiver )
{
uint16 log_slot = FindQuestSlot( 0 );
MANGOS_ASSERT(log_slot < MAX_QUEST_LOG_SIZE);
uint32 quest_id = pQuest->GetQuestId();
// if not exist then created with set uState==NEW and rewarded=false
QuestStatusData& questStatusData = mQuestStatus[quest_id];
// check for repeatable quests status reset
questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
questStatusData.m_explored = false;
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
{
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
questStatusData.m_itemcount[i] = 0;
}
if (pQuest->HasSpecialFlag(QuestSpecialFlags(QUEST_SPECIAL_FLAG_KILL_OR_CAST | QUEST_SPECIAL_FLAG_SPEAKTO)))
{
for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
questStatusData.m_creatureOrGOcount[i] = 0;
}
if ( pQuest->GetRepObjectiveFaction() )
if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
GetReputationMgr().SetVisible(factionEntry);
uint32 qtime = 0;
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED))
{
uint32 limittime = pQuest->GetLimitTime();
// shared timed quest
if (questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILLISECONDS;
AddTimedQuest( quest_id );
questStatusData.m_timer = limittime * IN_MILLISECONDS;
qtime = static_cast<uint32>(time(NULL)) + limittime;
}
else
questStatusData.m_timer = 0;
SetQuestSlot(log_slot, quest_id, qtime);
if (questStatusData.uState != QUEST_NEW)
questStatusData.uState = QUEST_CHANGED;
// quest accept scripts
if (questGiver)
{
switch (questGiver->GetTypeId())
{
case TYPEID_UNIT:
sScriptMgr.OnQuestAccept(this, (Creature*)questGiver, pQuest);
break;
case TYPEID_ITEM:
case TYPEID_CONTAINER:
sScriptMgr.OnQuestAccept(this, (Item*)questGiver, pQuest);
break;
case TYPEID_GAMEOBJECT:
sScriptMgr.OnQuestAccept(this, (GameObject*)questGiver, pQuest);
break;
}
// starting initial DB quest script
if (pQuest->GetQuestStartScript() != 0)
GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
}
// remove start item if not need
if (questGiver && questGiver->isType(TYPEMASK_ITEM))
{
// destroy not required for quest finish quest starting item
bool notRequiredItem = true;
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
if (pQuest->ReqItemId[i] == questGiver->GetEntry())
{
notRequiredItem = false;
break;
}
}
if (pQuest->GetSrcItemId() == questGiver->GetEntry())
notRequiredItem = false;
if (notRequiredItem)
DestroyItem(((Item*)questGiver)->GetBagSlot(), ((Item*)questGiver)->GetSlot(), true);
}
GiveQuestSourceItemIfNeed(pQuest);
AdjustQuestReqItemCount( pQuest, questStatusData );
// Some spells applied at quest activation
SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true);
if (saBounds.first != saBounds.second)
{
uint32 zone, area;
GetZoneAndAreaId(zone,area);
for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
if (!HasAura(itr->second->spellId, EFFECT_INDEX_0) )
CastSpell(this,itr->second->spellId,true);
}
UpdateForQuestWorldObjects();
}
void Player::CompleteQuest(uint32 quest_id)
{
if (quest_id)
{
SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
uint16 log_slot = FindQuestSlot(quest_id);
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
{
if (qInfo->HasQuestFlag(QUEST_FLAGS_AUTO_REWARDED))
RewardQuest(qInfo, 0, this, false);
}
}
}
void Player::IncompleteQuest(uint32 quest_id)
{
if (quest_id)
{
SetQuestStatus(quest_id, QUEST_STATUS_INCOMPLETE);
uint16 log_slot = FindQuestSlot( quest_id );
if (log_slot < MAX_QUEST_LOG_SIZE)
RemoveQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
}
}
void Player::RewardQuest(Quest const *pQuest, uint32 reward, Object* questGiver, bool announce)
{
uint32 quest_id = pQuest->GetQuestId();
// Destroy quest items
uint32 srcItemId = pQuest->GetSrcItemId();
uint32 srcItemCount = 0;
if (srcItemId)
{
srcItemCount = pQuest->GetSrcItemCount();
if (!srcItemCount)
srcItemCount = 1;
DestroyItemCount(srcItemId, srcItemCount, true, true);
}
// Destroy requered items
for (uint32 i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
uint32 reqItemId = pQuest->ReqItemId[i];
uint32 reqItemCount = pQuest->ReqItemCount[i];
if (reqItemId)
{
if (reqItemId == srcItemId)
reqItemCount -= srcItemCount;
if (reqItemCount)
DestroyItemCount(reqItemId, reqItemCount, true);
}
}
RemoveTimedQuest(quest_id);
if (BattleGround* bg = GetBattleGround())
if (bg->GetTypeID(true) == BATTLEGROUND_AV)
((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
if (pQuest->GetRewChoiceItemsCount() > 0)
{
if (uint32 itemId = pQuest->RewChoiceItemId[reward])
{
ItemPosCountVec dest;
if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward]) == EQUIP_ERR_OK)
{
Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
}
}
}
if (pQuest->GetRewItemsCount() > 0)
{
for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
{
if (uint32 itemId = pQuest->RewItemId[i])
{
ItemPosCountVec dest;
if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i]) == EQUIP_ERR_OK)
{
Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
SendNewItem(item, pQuest->RewItemCount[i], true, false);
}
}
}
}
RewardReputation(pQuest);
uint16 log_slot = FindQuestSlot(quest_id);
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlot(log_slot,0);
QuestStatusData& q_status = mQuestStatus[quest_id];
// Used for client inform but rewarded only in case not max level
uint32 xp = uint32(pQuest->XPValue(this) * sWorld.getConfig(CONFIG_FLOAT_RATE_XP_QUEST)*(GetSession()->IsPremium()+1));
if (getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
{
GiveXP(xp , NULL);
// Give player extra money (for max level already included in pQuest->GetRewMoneyMaxLevel())
if (pQuest->GetRewOrReqMoney() > 0)
{
ModifyMoney(pQuest->GetRewOrReqMoney());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
}
}
else
{
// reward money for max level already included in pQuest->GetRewMoneyMaxLevel()
uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY));
// reward money used if > xp replacement money
if (pQuest->GetRewOrReqMoney() > int32(money))
money = pQuest->GetRewOrReqMoney();
ModifyMoney(money);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
}
// req money case
if (pQuest->GetRewOrReqMoney() < 0)
ModifyMoney(pQuest->GetRewOrReqMoney());
// honor reward
if (uint32 honor = pQuest->CalculateRewardHonor(getLevel()))
RewardHonor(NULL, 0, honor);
// title reward
if (pQuest->GetCharTitleId())
{
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
SetTitle(titleEntry);
}
if (pQuest->GetBonusTalents())
{
m_questRewardTalentCount += pQuest->GetBonusTalents();
InitTalentForLevel();
}
// Send reward mail
if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_HAS_BODY, pQuest->GetRewMailDelaySecs());
if (pQuest->IsDaily())
{
SetDailyQuestStatus(quest_id);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
}
if (pQuest->IsWeekly())
SetWeeklyQuestStatus(quest_id);
if (pQuest->IsMonthly())
SetMonthlyQuestStatus(quest_id);
if (!pQuest->IsRepeatable())
SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
else
SetQuestStatus(quest_id, QUEST_STATUS_NONE);
q_status.m_rewarded = true;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
if (announce)
SendQuestReward(pQuest, xp, questGiver);
bool handled = false;
if (questGiver)
{
switch(questGiver->GetTypeId())
{
case TYPEID_UNIT:
handled = sScriptMgr.OnQuestRewarded(this, (Creature*)questGiver, pQuest);
break;
case TYPEID_GAMEOBJECT:
handled = sScriptMgr.OnQuestRewarded(this, (GameObject*)questGiver, pQuest);
break;
}
}
if (!handled && questGiver && pQuest->GetQuestCompleteScript() != 0)
GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
// cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
if (pQuest->GetRewSpellCast() > 0)
CastSpell(this, pQuest->GetRewSpellCast(), true);
else if (pQuest->GetRewSpell() > 0)
CastSpell(this, pQuest->GetRewSpell(), true);
if (pQuest->GetZoneOrSort() > 0)
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
uint32 zone = 0;
uint32 area = 0;
// remove auras from spells with quest reward state limitations
SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id);
if (saEndBounds.first != saEndBounds.second)
{
GetZoneAndAreaId(zone,area);
for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
if (!itr->second->IsFitToRequirements(this, zone, area))
RemoveAurasDueToSpell(itr->second->spellId);
}
// Some spells applied at quest reward
SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id, false);
if (saBounds.first != saBounds.second)
{
if (!zone || !area)
GetZoneAndAreaId(zone, area);
for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this, zone, area))
if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
CastSpell(this, itr->second->spellId, true);
}
}
void Player::FailQuest(uint32 questId)
{
if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId))
{
SetQuestStatus(questId, QUEST_STATUS_FAILED);
uint16 log_slot = FindQuestSlot(questId);
if (log_slot < MAX_QUEST_LOG_SIZE)
{
SetQuestSlotTimer(log_slot, 1);
SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
}
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED))
{
QuestStatusData& q_status = mQuestStatus[questId];
RemoveTimedQuest(questId);
q_status.m_timer = 0;
SendQuestTimerFailed(questId);
}
else
SendQuestFailed(questId);
}
}
bool Player::SatisfyQuestSkill(Quest const* qInfo, bool msg) const
{
uint32 skill = qInfo->GetRequiredSkill();
// skip 0 case RequiredSkill
if (skill == 0)
return true;
// check skill value
if (GetSkillValue(skill) < qInfo->GetRequiredSkillValue())
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
return true;
}
bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg) const
{
if (getLevel() < qInfo->GetMinLevel())
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
return true;
}
bool Player::SatisfyQuestLog(bool msg) const
{
// exist free slot
if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE)
return true;
if (msg)
{
WorldPacket data(SMSG_QUESTLOG_FULL, 0);
GetSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_QUESTLOG_FULL");
}
return false;
}
bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const
{
// No previous quest (might be first quest in a series)
if (qInfo->prevQuests.empty())
return true;
for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter)
{
uint32 prevId = abs(*iter);
QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find(prevId);
Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId);
if (qPrevInfo && i_prevstatus != mQuestStatus.end())
{
// If any of the positive previous quests completed, return true
if (*iter > 0 && i_prevstatus->second.m_rewarded)
{
// skip one-from-all exclusive group
if (qPrevInfo->GetExclusiveGroup() >= 0)
return true;
// each-from-all exclusive group ( < 0)
// can be start if only all quests in prev quest exclusive group completed and rewarded
ExclusiveQuestGroupsMapBounds bounds = sObjectMgr.GetExclusiveQuestGroupsMapBounds(qPrevInfo->GetExclusiveGroup());
MANGOS_ASSERT(bounds.first != bounds.second); // always must be found if qPrevInfo->ExclusiveGroup != 0
for(ExclusiveQuestGroupsMap::const_iterator iter2 = bounds.first; iter2 != bounds.second; ++iter2)
{
uint32 exclude_Id = iter2->second;
// skip checked quest id, only state of other quests in group is interesting
if (exclude_Id == prevId)
continue;
QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find(exclude_Id);
// alternative quest from group also must be completed and rewarded(reported)
if (i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
}
return true;
}
// If any of the negative previous quests active, return true
if (*iter < 0 && IsCurrentQuest(prevId))
{
// skip one-from-all exclusive group
if (qPrevInfo->GetExclusiveGroup() >= 0)
return true;
// each-from-all exclusive group ( < 0)
// can be start if only all quests in prev quest exclusive group active
ExclusiveQuestGroupsMapBounds bounds = sObjectMgr.GetExclusiveQuestGroupsMapBounds(qPrevInfo->GetExclusiveGroup());
MANGOS_ASSERT(bounds.first != bounds.second); // always must be found if qPrevInfo->ExclusiveGroup != 0
for(ExclusiveQuestGroupsMap::const_iterator iter2 = bounds.first; iter2 != bounds.second; ++iter2)
{
uint32 exclude_Id = iter2->second;
// skip checked quest id, only state of other quests in group is interesting
if (exclude_Id == prevId)
continue;
// alternative quest from group also must be active
if (!IsCurrentQuest(exclude_Id))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
}
return true;
}
}
}
// Has only positive prev. quests in non-rewarded state
// and negative prev. quests in non-active state
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
bool Player::SatisfyQuestClass(Quest const* qInfo, bool msg) const
{
uint32 reqClass = qInfo->GetRequiredClasses();
if (reqClass == 0)
return true;
if ((reqClass & getClassMask()) == 0)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
return true;
}
bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg) const
{
uint32 reqraces = qInfo->GetRequiredRaces();
if (reqraces == 0)
return true;
if ((reqraces & getRaceMask()) == 0)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE);
return false;
}
return true;
}
bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg) const
{
uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
if (fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
return true;
}
bool Player::SatisfyQuestStatus(Quest const* qInfo, bool msg) const
{
QuestStatusMap::const_iterator itr = mQuestStatus.find(qInfo->GetQuestId());
if (itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_ON);
return false;
}
return true;
}
bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg) const
{
if (!m_timedquests.empty() && qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
return false;
}
return true;
}
bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const
{
// non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
if (qInfo->GetExclusiveGroup() <= 0)
return true;
ExclusiveQuestGroupsMapBounds bounds = sObjectMgr.GetExclusiveQuestGroupsMapBounds(qInfo->GetExclusiveGroup());
MANGOS_ASSERT(bounds.first != bounds.second); // must always be found if qInfo->ExclusiveGroup != 0
for(ExclusiveQuestGroupsMap::const_iterator iter = bounds.first; iter != bounds.second; ++iter)
{
uint32 exclude_Id = iter->second;
// skip checked quest id, only state of other quests in group is interesting
if (exclude_Id == qInfo->GetQuestId())
continue;
// not allow have daily quest if daily quest from exclusive group already recently completed
Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id);
if (!SatisfyQuestDay(Nquest, false) || !SatisfyQuestWeek(Nquest, false))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find(exclude_Id);
// alternative quest already started or completed
if (i_exstatus != mQuestStatus.end() &&
(i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
}
return true;
}
bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg) const
{
if (!qInfo->GetNextQuestInChain())
return true;
// next quest in chain already started or completed
QuestStatusMap::const_iterator itr = mQuestStatus.find(qInfo->GetNextQuestInChain());
if (itr != mQuestStatus.end() &&
(itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
// check for all quests further up the chain
// only necessary if there are quest chains with more than one quest that can be skipped
//return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
return true;
}
bool Player::SatisfyQuestPrevChain(Quest const* qInfo, bool msg) const
{
// No previous quest in chain
if (qInfo->prevChainQuests.empty())
return true;
for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter)
{
uint32 prevId = *iter;
// If any of the previous quests in chain active, return false
if (IsCurrentQuest(prevId))
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);
return false;
}
// check for all quests further down the chain
// only necessary if there are quest chains with more than one quest that can be skipped
//if ( !SatisfyQuestPrevChain( prevId, msg ) )
// return false;
}
// No previous quest in chain active
return true;
}
bool Player::SatisfyQuestDay(Quest const* qInfo, bool msg) const
{
if (!qInfo->IsDaily())
return true;
bool have_slot = false;
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
{
uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
if (qInfo->GetQuestId()==id)
return false;
if (!id)
have_slot = true;
}
if (!have_slot)
{
if (msg)
SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_TOO_MANY_DAILY_QUESTS);
return false;
}
return true;
}
bool Player::SatisfyQuestWeek(Quest const* qInfo, bool msg) const
{
if (!qInfo->IsWeekly() || m_weeklyquests.empty())
return true;
// if not found in cooldown list
return m_weeklyquests.find(qInfo->GetQuestId()) == m_weeklyquests.end();
}
bool Player::SatisfyQuestMonth(Quest const* qInfo, bool msg) const
{
if (!qInfo->IsMonthly() || m_monthlyquests.empty())
return true;
// if not found in cooldown list
return m_monthlyquests.find(qInfo->GetQuestId()) == m_monthlyquests.end();
}
bool Player::CanGiveQuestSourceItemIfNeed( Quest const *pQuest, ItemPosCountVec* dest) const
{
if (uint32 srcitem = pQuest->GetSrcItemId())
{
uint32 count = pQuest->GetSrcItemCount();
// player already have max amount required item (including bank), just report success
uint32 has_count = GetItemCount(srcitem, true);
if (has_count >= count)
return true;
count -= has_count; // real need amount
InventoryResult msg;
if (!dest)
{
ItemPosCountVec destTemp;
msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, destTemp, srcitem, count );
}
else
msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, *dest, srcitem, count );
if (msg == EQUIP_ERR_OK)
return true;
else
SendEquipError( msg, NULL, NULL, srcitem );
return false;
}
return true;
}
void Player::GiveQuestSourceItemIfNeed(Quest const *pQuest)
{
ItemPosCountVec dest;
if (CanGiveQuestSourceItemIfNeed(pQuest, &dest) && !dest.empty())
{
uint32 count = 0;
for(ItemPosCountVec::const_iterator c_itr = dest.begin(); c_itr != dest.end(); ++c_itr)
count += c_itr->count;
Item * item = StoreNewItem(dest, pQuest->GetSrcItemId(), true);
SendNewItem(item, count, true, false);
}
}
bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
{
Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
if ( qInfo )
{
uint32 srcitem = qInfo->GetSrcItemId();
if ( srcitem > 0 )
{
uint32 count = qInfo->GetSrcItemCount();
if ( count <= 0 )
count = 1;
// exist one case when destroy source quest item not possible:
// non un-equippable item (equipped non-empty bag, for example)
InventoryResult res = CanUnequipItems(srcitem,count);
if (res != EQUIP_ERR_OK)
{
if (msg)
SendEquipError( res, NULL, NULL, srcitem );
return false;
}
DestroyItemCount(srcitem, count, true, true);
}
}
return true;
}
bool Player::GetQuestRewardStatus( uint32 quest_id ) const
{
Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
if ( qInfo )
{
// for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
&& !qInfo->IsRepeatable() )
return itr->second.m_rewarded;
return false;
}
return false;
}
QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
{
if ( quest_id )
{
QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
if ( itr != mQuestStatus.end() )
return itr->second.m_status;
}
return QUEST_STATUS_NONE;
}
bool Player::CanShareQuest(uint32 quest_id) const
{
if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
if (qInfo->HasQuestFlag(QUEST_FLAGS_SHARABLE))
return IsCurrentQuest(quest_id);
return false;
}
void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
{
if (sObjectMgr.GetQuestTemplate(quest_id))
{
QuestStatusData& q_status = mQuestStatus[quest_id];
q_status.m_status = status;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
}
UpdateForQuestWorldObjects();
}
// not used in MaNGOS, but used in scripting code
uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
{
Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
if ( !qInfo )
return 0;
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
if ( qInfo->ReqCreatureOrGOId[j] == entry )
return mQuestStatus[quest_id].m_creatureOrGOcount[j];
return 0;
}
void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
{
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
{
for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
{
uint32 reqitemcount = pQuest->ReqItemCount[i];
if ( reqitemcount != 0 )
{
uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
}
}
}
}
uint16 Player::FindQuestSlot( uint32 quest_id ) const
{
for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
if ( GetQuestSlotQuestId(i) == quest_id )
return i;
return MAX_QUEST_LOG_SIZE;
}
void Player::AreaExploredOrEventHappens( uint32 questId )
{
if ( questId )
{
uint16 log_slot = FindQuestSlot( questId );
if ( log_slot < MAX_QUEST_LOG_SIZE)
{
QuestStatusData& q_status = mQuestStatus[questId];
if(!q_status.m_explored)
{
SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
SendQuestCompleteEvent(questId);
q_status.m_explored = true;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
}
}
if ( CanCompleteQuest( questId ) )
CompleteQuest( questId );
}
}
//not used in mangosd, function for external script library
void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
{
if ( Group *pGroup = GetGroup() )
{
for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player *pGroupGuy = itr->getSource();
// for any leave or dead (with not released body) group member at appropriate distance
if ( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
pGroupGuy->AreaExploredOrEventHappens(questId);
}
}
else
AreaExploredOrEventHappens(questId);
}
void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if ( questid == 0 )
continue;
QuestStatusData& q_status = mQuestStatus[questid];
if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if (!qInfo || !qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
continue;
for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
{
uint32 reqitem = qInfo->ReqItemId[j];
if ( reqitem == entry )
{
uint32 reqitemcount = qInfo->ReqItemCount[j];
uint32 curitemcount = q_status.m_itemcount[j];
if ( curitemcount < reqitemcount )
{
uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
q_status.m_itemcount[j] += additemcount;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
}
if ( CanCompleteQuest( questid ) )
CompleteQuest( questid );
return;
}
}
}
UpdateForQuestWorldObjects();
}
void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if(!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if ( !qInfo )
continue;
if (!qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_DELIVER))
continue;
for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
{
uint32 reqitem = qInfo->ReqItemId[j];
if ( reqitem == entry )
{
QuestStatusData& q_status = mQuestStatus[questid];
uint32 reqitemcount = qInfo->ReqItemCount[j];
uint32 curitemcount;
if ( q_status.m_status != QUEST_STATUS_COMPLETE )
curitemcount = q_status.m_itemcount[j];
else
curitemcount = GetItemCount(entry, true);
if ( curitemcount < reqitemcount + count )
{
uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
q_status.m_itemcount[j] = curitemcount - remitemcount;
if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
IncompleteQuest( questid );
}
return;
}
}
}
UpdateForQuestWorldObjects();
}
void Player::KilledMonster( CreatureInfo const* cInfo, ObjectGuid guid )
{
if (cInfo->Entry)
KilledMonsterCredit(cInfo->Entry, guid);
for(int i = 0; i < MAX_KILL_CREDIT; ++i)
if (cInfo->KillCredit[i])
KilledMonsterCredit(cInfo->KillCredit[i], guid);
}
void Player::KilledMonsterCredit( uint32 entry, ObjectGuid guid )
{
uint32 addkillcount = 1;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if(!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if (!qInfo)
continue;
// just if !ingroup || !noraidgroup || raidgroup
QuestStatusData& q_status = mQuestStatus[questid];
if (q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid()))
{
if (qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_KILL_OR_CAST))
{
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip GO activate objective or none
if (qInfo->ReqCreatureOrGOId[j] <=0)
continue;
// skip Cast at creature objective
if (qInfo->ReqSpell[j] !=0 )
continue;
uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
if (reqkill == entry)
{
uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
uint32 curkillcount = q_status.m_creatureOrGOcount[j];
if (curkillcount < reqkillcount)
{
q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, q_status.m_creatureOrGOcount[j]);
}
if (CanCompleteQuest( questid ))
CompleteQuest( questid );
// same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
continue;
}
}
}
}
}
}
void Player::CastedCreatureOrGO( uint32 entry, ObjectGuid guid, uint32 spell_id, bool original_caster )
{
bool isCreature = guid.IsCreatureOrVehicle();
uint32 addCastCount = 1;
for(int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if (!qInfo)
continue;
if (!original_caster && !qInfo->HasQuestFlag(QUEST_FLAGS_SHARABLE))
continue;
if (!qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAG_KILL_OR_CAST))
continue;
QuestStatusData& q_status = mQuestStatus[questid];
if (q_status.m_status != QUEST_STATUS_INCOMPLETE)
continue;
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip kill creature objective (0) or wrong spell casts
if (qInfo->ReqSpell[j] != spell_id)
continue;
uint32 reqTarget = 0;
if (isCreature)
{
// creature activate objectives
if (qInfo->ReqCreatureOrGOId[j] > 0)
// checked at quest_template loading
reqTarget = qInfo->ReqCreatureOrGOId[j];
}
else
{
// GO activate objective
if (qInfo->ReqCreatureOrGOId[j] < 0)
// checked at quest_template loading
reqTarget = - qInfo->ReqCreatureOrGOId[j];
}
// other not this creature/GO related objectives
if (reqTarget != entry)
continue;
uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
uint32 curCastCount = q_status.m_creatureOrGOcount[j];
if (curCastCount < reqCastCount)
{
q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
if (q_status.uState != QUEST_NEW)
q_status.uState = QUEST_CHANGED;
SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, q_status.m_creatureOrGOcount[j]);
}
if (CanCompleteQuest(questid))
CompleteQuest(questid);
// same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
break;
}
}
}
void Player::TalkedToCreature( uint32 entry, ObjectGuid guid )
{
uint32 addTalkCount = 1;
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if(!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if ( !qInfo )
continue;
QuestStatusData& q_status = mQuestStatus[questid];
if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
{
if (qInfo->HasSpecialFlag(QuestSpecialFlags(QUEST_SPECIAL_FLAG_KILL_OR_CAST | QUEST_SPECIAL_FLAG_SPEAKTO)))
{
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
// skip spell casts and Gameobject objectives
if (qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
continue;
uint32 reqTarget = 0;
if (qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
// checked at quest_template loading
reqTarget = qInfo->ReqCreatureOrGOId[j];
else
continue;
if ( reqTarget == entry )
{
uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
if ( curTalkCount < reqTalkCount )
{
q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, q_status.m_creatureOrGOcount[j]);
}
if ( CanCompleteQuest( questid ) )
CompleteQuest( questid );
// same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
continue;
}
}
}
}
}
}
void Player::MoneyChanged( uint32 count )
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if (!questid)
continue;
Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
if ( qInfo && qInfo->GetRewOrReqMoney() < 0 )
{
QuestStatusData& q_status = mQuestStatus[questid];
if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
{
if (int32(count) >= -qInfo->GetRewOrReqMoney())
{
if ( CanCompleteQuest( questid ) )
CompleteQuest( questid );
}
}
else if ( q_status.m_status == QUEST_STATUS_COMPLETE )
{
if (int32(count) < -qInfo->GetRewOrReqMoney())
IncompleteQuest( questid );
}
}
}
}
void Player::ReputationChanged(FactionEntry const* factionEntry )
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
if (uint32 questid = GetQuestSlotQuestId(i))
{
if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid))
{
if (qInfo->GetRepObjectiveFaction() == factionEntry->ID )
{
QuestStatusData& q_status = mQuestStatus[questid];
if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
{
if (GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
if ( CanCompleteQuest( questid ) )
CompleteQuest( questid );
}
else if ( q_status.m_status == QUEST_STATUS_COMPLETE )
{
if (GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
IncompleteQuest( questid );
}
}
}
}
}
}
bool Player::HasQuestForItem( uint32 itemid ) const
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if ( questid == 0 )
continue;
QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
if (qs_itr == mQuestStatus.end())
continue;
QuestStatusData const& q_status = qs_itr->second;
if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
{
Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
if(!qinfo)
continue;
// hide quest if player is in raid-group and quest is no raid quest
if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid() && !InBattleGround())
continue;
// There should be no mixed ReqItem/ReqSource drop
// This part for ReqItem drop
for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
{
if (itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
return true;
}
// This part - for ReqSource
for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
{
// examined item is a source item
if (qinfo->ReqSourceId[j] == itemid)
{
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
// 'unique' item
if (pProto->MaxCount && (int32)GetItemCount(itemid,true) < pProto->MaxCount)
return true;
// allows custom amount drop when not 0
if (qinfo->ReqSourceCount[j])
{
if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
return true;
} else if ((int32)GetItemCount(itemid,true) < pProto->Stackable)
return true;
}
}
}
}
return false;
}
// Used for quests having some event (explore, escort, "external event") as quest objective.
void Player::SendQuestCompleteEvent(uint32 quest_id)
{
if (quest_id)
{
WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4);
data << uint32(quest_id);
GetSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id);
}
}
void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
{
uint32 questid = pQuest->GetQuestId();
DEBUG_LOG( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
data << uint32(questid);
if ( getLevel() < sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL) )
{
data << uint32(XP);
data << uint32(pQuest->GetRewOrReqMoney());
}
else
{
data << uint32(0);
data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY)));
}
data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorAddition()));
data << uint32(pQuest->GetBonusTalents()); // bonus talents
data << uint32(0); // arena points
GetSession()->SendPacket( &data );
}
void Player::SendQuestFailed( uint32 quest_id, InventoryResult reason)
{
if ( quest_id )
{
WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
data << uint32(quest_id);
data << uint32(reason); // failed reason (valid reasons: 4, 16, 50, 17, 74, other values show default message)
GetSession()->SendPacket( &data );
DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
}
}
void Player::SendQuestTimerFailed( uint32 quest_id )
{
if ( quest_id )
{
WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
data << uint32(quest_id);
GetSession()->SendPacket( &data );
DEBUG_LOG("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
}
}
void Player::SendCanTakeQuestResponse( uint32 msg ) const
{
WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
data << uint32(msg);
GetSession()->SendPacket( &data );
DEBUG_LOG("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
}
void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
{
if (pReceiver)
{
int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
std::string title = pQuest->GetTitle();
sObjectMgr.GetQuestLocaleStrings(pQuest->GetQuestId(), loc_idx, &title);
WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + title.size() + 8));
data << uint32(pQuest->GetQuestId());
data << title;
data << GetObjectGuid();
pReceiver->GetSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
}
}
void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
{
if ( pPlayer )
{
WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
data << pPlayer->GetObjectGuid();
data << uint8(msg); // valid values: 0-8
GetSession()->SendPacket( &data );
DEBUG_LOG("WORLD: Sent MSG_QUEST_PUSH_RESULT");
}
}
void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, ObjectGuid guid, uint32 creatureOrGO_idx, uint32 count)
{
MANGOS_ASSERT(count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
if (entry < 0)
// client expected gameobject template id in form (id|0x80000000)
entry = (-entry) | 0x80000000;
WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
DEBUG_LOG( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
data << uint32(pQuest->GetQuestId());
data << uint32(entry);
data << uint32(count);
data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
data << guid;
GetSession()->SendPacket(&data);
uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
if (log_slot < MAX_QUEST_LOG_SIZE)
SetQuestSlotCounter(log_slot, creatureOrGO_idx, count);
}
/*********************************************************/
/*** LOAD SYSTEM ***/
/*********************************************************/
void Player::_LoadDeclinedNames(QueryResult* result)
{
if(!result)
return;
if (m_declinedname)
delete m_declinedname;
m_declinedname = new DeclinedName;
Field *fields = result->Fetch();
for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
m_declinedname->name[i] = fields[i].GetCppString();
delete result;
}
void Player::_LoadArenaTeamInfo(QueryResult *result)
{
// arenateamid, played_week, played_season, personal_rating
memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
if (!result)
return;
do
{
Field *fields = result->Fetch();
uint32 arenateamid = fields[0].GetUInt32();
uint32 played_week = fields[1].GetUInt32();
uint32 played_season = fields[2].GetUInt32();
uint32 wons_season = fields[3].GetUInt32();
uint32 personal_rating = fields[4].GetUInt32();
ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid);
if(!aTeam)
{
sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
continue;
}
uint8 arenaSlot = aTeam->GetSlot();
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_ID, arenateamid);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_TYPE, aTeam->GetType());
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_MEMBER, (aTeam->GetCaptainGuid() == GetObjectGuid()) ? 0 : 1);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_WEEK, played_week);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_GAMES_SEASON, played_season);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_WINS_SEASON, wons_season);
SetArenaTeamInfoField(arenaSlot, ARENA_TEAM_PERSONAL_RATING, personal_rating);
} while (result->NextRow());
delete result;
}
void Player::_LoadEquipmentSets(QueryResult *result)
{
// SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, ignore_mask, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
if (!result)
return;
uint32 count = 0;
do
{
Field *fields = result->Fetch();
EquipmentSet eqSet;
eqSet.Guid = fields[0].GetUInt64();
uint32 index = fields[1].GetUInt32();
eqSet.Name = fields[2].GetCppString();
eqSet.IconName = fields[3].GetCppString();
eqSet.IgnoreMask = fields[4].GetUInt32();
eqSet.state = EQUIPMENT_SET_UNCHANGED;
for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
eqSet.Items[i] = fields[5+i].GetUInt32();
m_EquipmentSets[index] = eqSet;
++count;
if (count >= MAX_EQUIPMENT_SET_INDEX) // client limit
break;
} while (result->NextRow());
delete result;
}
void Player::_LoadBGData(QueryResult* result)
{
if (!result)
return;
// Expecting only one row
Field *fields = result->Fetch();
/* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
m_bgData.bgInstanceID = fields[0].GetUInt32();
m_bgData.bgTeam = Team(fields[1].GetUInt32());
m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
fields[2].GetFloat(), // X
fields[3].GetFloat(), // Y
fields[4].GetFloat(), // Z
fields[5].GetFloat()); // Orientation
m_bgData.taxiPath[0] = fields[7].GetUInt32();
m_bgData.taxiPath[1] = fields[8].GetUInt32();
m_bgData.mountSpell = fields[9].GetUInt32();
delete result;
}
bool Player::LoadPositionFromDB(ObjectGuid guid, uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight)
{
QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'", guid.GetCounter());
if(!result)
return false;
Field *fields = result->Fetch();
x = fields[0].GetFloat();
y = fields[1].GetFloat();
z = fields[2].GetFloat();
o = fields[3].GetFloat();
mapid = fields[4].GetUInt32();
in_flight = !fields[5].GetCppString().empty();
delete result;
return true;
}
void Player::_LoadIntoDataField(const char* data, uint32 startOffset, uint32 count)
{
if(!data)
return;
Tokens tokens(data, ' ', count);
if (tokens.size() != count)
return;
for (uint32 index = 0; index < count; ++index)
m_uint32Values[startOffset + index] = atol(tokens[index]);
}
bool Player::LoadFromDB(ObjectGuid guid, SqlQueryHolder *holder )
{
// 0 1 2 3 4 5 6 7 8 9 10 11
//SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
// 12 13 14 15 16 17 18 19 20 21 22 23 24
//"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
// 25 26 27 28 29 30 31 32 33 34 35 36 37 38
//"resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty,"
// 39 40 41 42 43 44 45 46 47 48 49
//"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
// 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
//"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
if(!result)
{
sLog.outError("%s not found in table `characters`, can't load. ", guid.GetString().c_str());
return false;
}
Field *fields = result->Fetch();
uint32 dbAccountId = fields[1].GetUInt32();
// check if the character's account in the db and the logged in account match.
// player should be able to load/delete character only with correct account!
if ( dbAccountId != GetSession()->GetAccountId() )
{
sLog.outError("%s loading from wrong account (is: %u, should be: %u)",
guid.GetString().c_str(), GetSession()->GetAccountId(), dbAccountId);
delete result;
return false;
}
Object::_Create(guid);
m_name = fields[2].GetCppString();
// check name limitations
if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
(GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name)))
{
delete result;
CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'",
uint32(AT_LOGIN_RENAME), guid.GetCounter());
return false;
}
// overwrite possible wrong/corrupted guid
SetGuidValue(OBJECT_FIELD_GUID, guid);
// overwrite some data fields
SetByteValue(UNIT_FIELD_BYTES_0,0,fields[3].GetUInt8());// race
SetByteValue(UNIT_FIELD_BYTES_0,1,fields[4].GetUInt8());// class
uint8 gender = fields[5].GetUInt8() & 0x01; // allowed only 1 bit values male/female cases (for fit drunk gender part)
SetByteValue(UNIT_FIELD_BYTES_0,2,gender); // gender
SetUInt32Value(UNIT_FIELD_LEVEL, fields[6].GetUInt8());
SetUInt32Value(PLAYER_XP, fields[7].GetUInt32());
_LoadIntoDataField(fields[60].GetString(), PLAYER_EXPLORED_ZONES_1, PLAYER_EXPLORED_ZONES_SIZE);
_LoadIntoDataField(fields[63].GetString(), PLAYER__FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE*2);
InitDisplayIds(); // model, scale and model data
SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f);
// just load criteria/achievement data, safe call before any load, and need, because some spell/item/quest loading
// can triggering achievement criteria update that will be lost if this call will later
m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
uint32 money = fields[8].GetUInt32();
if (money > MAX_MONEY_AMOUNT)
money = MAX_MONEY_AMOUNT;
SetMoney(money);
SetUInt32Value(PLAYER_BYTES, fields[9].GetUInt32());
SetUInt32Value(PLAYER_BYTES_2, fields[10].GetUInt32());
m_drunk = fields[49].GetUInt16();
SetUInt16Value(PLAYER_BYTES_3, 0, (m_drunk & 0xFFFE) | gender);
SetUInt32Value(PLAYER_FLAGS, fields[11].GetUInt32());
SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[48].GetInt32());
SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[47].GetUInt64());
SetUInt32Value(PLAYER_AMMO_ID, fields[62].GetUInt32());
// Action bars state
SetByteValue(PLAYER_FIELD_BYTES, 2, fields[64].GetUInt8());
// cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid());
SetVisibleItemSlot(slot, NULL);
if (m_items[slot])
{
delete m_items[slot];
m_items[slot] = NULL;
}
}
DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_STATS, "Load Basic value of player %s is: ", m_name.c_str());
outDebugStatsValues();
//Need to call it to initialize m_team (m_team can be calculated from race)
//Other way is to saves m_team into characters table.
setFactionForRace(getRace());
SetCharm(NULL);
// load home bind and check in same time class/race pair, it used later for restore broken positions
if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
{
delete result;
return false;
}
InitPrimaryProfessions(); // to max set before any spell loaded
// init saved position, and fix it later if problematic
uint32 transGUID = fields[30].GetUInt32();
// Relocate(fields[12].GetFloat(),fields[13].GetFloat(),fields[14].GetFloat(),fields[16].GetFloat());
// SetLocationMapId(fields[15].GetUInt32());
WorldLocation savedLocation = WorldLocation(fields[15].GetUInt32(),fields[12].GetFloat(),fields[13].GetFloat(),fields[14].GetFloat(),fields[16].GetFloat());
m_Difficulty = fields[38].GetUInt32(); // may be changed in _LoadGroup
if (GetDungeonDifficulty() >= MAX_DUNGEON_DIFFICULTY)
SetDungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL);
if (GetRaidDifficulty() >= MAX_RAID_DIFFICULTY)
SetRaidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL);
_LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
_LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
SetArenaPoints(fields[39].GetUInt32());
// check arena teams integrity
for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
{
uint32 arena_team_id = GetArenaTeamId(arena_slot);
if (!arena_team_id)
continue;
if (ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id))
if (at->HaveMember(GetObjectGuid()))
continue;
// arena team not exist or not member, cleanup fields
for(int j = 0; j < ARENA_TEAM_END; ++j)
SetArenaTeamInfoField(arena_slot, ArenaTeamInfoType(j), 0);
}
SetHonorPoints(fields[40].GetUInt32());
SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[41].GetUInt32());
SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[42].GetUInt32());
SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, fields[43].GetUInt32());
SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[44].GetUInt16());
SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[45].GetUInt16());
_LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
MapEntry const* mapEntry = sMapStore.LookupEntry(savedLocation.mapid);
if (!mapEntry || !MapManager::IsValidMapCoord(savedLocation) ||
// client without expansion support
GetSession()->Expansion() < mapEntry->Expansion())
{
sLog.outError("Player::LoadFromDB player %s have invalid coordinates (map: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
guid.GetString().c_str(),
savedLocation.mapid,
savedLocation.coord_x,
savedLocation.coord_y,
savedLocation.coord_z,
savedLocation.orientation);
RelocateToHomebind();
GetPosition(savedLocation); // reset saved position to homebind
transGUID = 0;
m_movementInfo.ClearTransportData();
}
_LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
bool player_at_bg = false;
// player bounded instance saves loaded in _LoadBoundInstances, group versions at group loading
DungeonPersistentState* state = GetBoundInstanceSaveForSelfOrGroup(savedLocation.mapid);
Map* targetMap = sMapMgr.FindMap(savedLocation.mapid, state ? state->GetInstanceId() : 0);
if (m_bgData.bgInstanceID) //saved in BattleGround
{
BattleGround* currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetObjectGuid());
if (player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
{
BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
AddBattleGroundQueueId(bgQueueTypeId);
m_bgData.bgTypeID = currentBg->GetTypeID(); // bg data not marked as modified
//join player to battleground group
currentBg->EventPlayerLoggedIn(this, GetObjectGuid());
currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetObjectGuid(), m_bgData.bgTeam);
SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
}
else
{
// leave bg
if (player_at_bg)
{
currentBg->RemovePlayerAtLeave(GetObjectGuid(), false, true);
player_at_bg = false;
}
// move to bg enter point
const WorldLocation& _loc = GetBattleGroundEntryPoint();
SetLocationMapId(_loc.mapid);
Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
// We are not in BG anymore
SetBattleGroundId(0, BATTLEGROUND_TYPE_NONE);
// remove outdated DB data in DB
_SaveBGData(true);
}
}
else
{
mapEntry = sMapStore.LookupEntry(savedLocation.mapid);
// if server restart after player save in BG or area
// player can have current coordinates in to BG/Arena map, fix this
if(mapEntry->IsBattleGroundOrArena())
{
const WorldLocation& _loc = GetBattleGroundEntryPoint();
if (!MapManager::IsValidMapCoord(_loc))
{
RelocateToHomebind();
transGUID = 0;
m_movementInfo.ClearTransportData();
}
else
{
SetLocationMapId(_loc.mapid);
Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
}
// We are not in BG anymore
SetBattleGroundId(0, BATTLEGROUND_TYPE_NONE);
// remove outdated DB data in DB
_SaveBGData(true);
}
// Cleanup LFG BG data, if char not in dungeon.
else if (!mapEntry->IsDungeon())
{
_SaveBGData(true);
// Saved location checked before
SetLocationMapId(savedLocation.mapid);
Relocate(savedLocation.coord_x, savedLocation.coord_y, savedLocation.coord_z, savedLocation.orientation);
}
else if (mapEntry->IsDungeon())
{
AreaTrigger const* gt = sObjectMgr.GetGoBackTrigger(savedLocation.mapid);
if (gt)
{
// always put player at goback trigger before porting to instance
SetLocationMapId(gt->target_mapId);
Relocate(gt->target_X, gt->target_Y, gt->target_Z, gt->target_Orientation);
AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(savedLocation.mapid);
if (at)
{
if (CheckTransferPossibility(at))
{
if (!state)
{
SetLocationMapId(at->target_mapId);
Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
}
else
{
SetLocationMapId(savedLocation.mapid);
Relocate(savedLocation.coord_x, savedLocation.coord_y, savedLocation.coord_z, savedLocation.orientation);
}
}
else
sLog.outError("Player::LoadFromDB %s try logged to instance (map: %u, difficulty %u), but transfer to map impossible. This _might_ be an exploit attempt.", GetObjectGuid().GetString().c_str(), savedLocation.mapid, GetDifficulty());
}
else
sLog.outError("Player::LoadFromDB %s logged in to a reset instance (map: %u, difficulty %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetObjectGuid().GetString().c_str(), savedLocation.mapid, GetDifficulty());
}
else
{
transGUID = 0;
m_movementInfo.ClearTransportData();
RelocateToHomebind();
}
}
}
if (transGUID != 0)
{
m_movementInfo.SetTransportData(ObjectGuid(HIGHGUID_MO_TRANSPORT,transGUID), fields[26].GetFloat(), fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat(), 0, -1);
if ( !MaNGOS::IsValidMapCoord(
GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o) ||
// transport size limited
m_movementInfo.GetTransportPos()->x > 50 || m_movementInfo.GetTransportPos()->y > 50 || m_movementInfo.GetTransportPos()->z > 50 )
{
sLog.outError("%s have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
guid.GetString().c_str(), GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o);
RelocateToHomebind();
m_movementInfo.ClearTransportData();
transGUID = 0;
}
}
if (transGUID != 0)
{
for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
{
Transport* transport = *iter;
if (transport->GetGUIDLow() == transGUID)
{
MapEntry const* transMapEntry = sMapStore.LookupEntry(transport->GetMapId());
// client without expansion support
if (GetSession()->Expansion() < transMapEntry->Expansion())
{
DEBUG_LOG("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), transport->GetMapId());
break;
}
SetTransport(transport);
transport->AddPassenger(this);
SetLocationMapId(transport->GetMapId());
break;
}
}
if(!m_transport)
{
sLog.outError("%s have problems with transport guid (%u). Teleport to default race/class locations.",
guid.GetString().c_str(), transGUID);
RelocateToHomebind();
m_movementInfo.ClearTransportData();
transGUID = 0;
}
}
// load the player's map here if it's not already loaded
if (!GetMap())
{
if (Map* map = sMapMgr.CreateMap(GetMapId(), this))
SetMap(map);
else
RelocateToHomebind();
}
SaveRecallPosition();
time_t now = time(NULL);
time_t logoutTime = time_t(fields[22].GetUInt64());
// since last logout (in seconds)
uint32 time_diff = uint32(now - logoutTime);
// set value, including drunk invisibility detection
// calculate sobering. after 15 minutes logged out, the player will be sober again
float soberFactor;
if (time_diff > 15*MINUTE)
soberFactor = 0;
else
soberFactor = 1-time_diff/(15.0f*MINUTE);
uint16 newDrunkenValue = uint16(soberFactor* m_drunk);
SetDrunkValue(newDrunkenValue);
m_cinematic = fields[18].GetUInt32();
m_Played_time[PLAYED_TIME_TOTAL]= fields[19].GetUInt32();
m_Played_time[PLAYED_TIME_LEVEL]= fields[20].GetUInt32();
m_resetTalentsCost = fields[24].GetUInt32();
m_resetTalentsTime = time_t(fields[25].GetUInt64());
// reserve some flags
uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
if ( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
m_taxi.LoadTaxiMask( fields[17].GetString() ); // must be before InitTaxiNodesForLevel
uint32 extraflags = fields[31].GetUInt32();
m_stableSlots = fields[32].GetUInt32();
if (m_stableSlots > MAX_PET_STABLES)
{
sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
m_stableSlots = MAX_PET_STABLES;
}
m_atLoginFlags = fields[33].GetUInt32();
// Honor system
// Update Honor kills data
m_lastHonorUpdateTime = logoutTime;
UpdateHonorFields();
m_deathExpireTime = (time_t)fields[36].GetUInt64();
if (m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
std::string taxi_nodes = fields[37].GetCppString();
// clear channel spell data (if saved at channel spell casting)
SetChannelObjectGuid(ObjectGuid());
SetUInt32Value(UNIT_CHANNEL_SPELL,0);
// clear charm/summon related fields
SetCharm(NULL);
SetPet(NULL);
SetTargetGuid(ObjectGuid());
SetCharmerGuid(ObjectGuid());
SetOwnerGuid(ObjectGuid());
SetCreatorGuid(ObjectGuid());
// reset some aura modifiers before aura apply
SetGuidValue(PLAYER_FARSIGHT, ObjectGuid());
SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
// cleanup aura list explicitly before skill load where some spells can be applied
RemoveAllAuras();
// make sure the unit is considered out of combat for proper loading
ClearInCombat();
// make sure the unit is considered not in duel for proper loading
SetGuidValue(PLAYER_DUEL_ARBITER, ObjectGuid());
SetUInt32Value(PLAYER_DUEL_TEAM, 0);
// reset stats before loading any modifiers
InitStatsForLevel();
InitGlyphsForLevel();
InitTaxiNodesForLevel();
InitRunes();
// rest bonus can only be calculated after InitStatsForLevel()
m_rest_bonus = fields[21].GetFloat();
if (time_diff > 0)
{
//speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
float bubble0 = 0.031f;
//speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
float bubble1 = 0.125f;
float bubble = fields[23].GetUInt32() > 0
? bubble1*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
: bubble0*sWorld.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS);
SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
}
// load skills after InitStatsForLevel because it triggering aura apply also
_LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
// apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
// Mail
_LoadMails(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILS));
_LoadMailedItems(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILEDITEMS));
UpdateNextMailTimeAndUnreads();
m_specsCount = fields[58].GetUInt8();
m_activeSpec = fields[59].GetUInt8();
m_GrantableLevelsCount = fields[65].GetUInt32();
// refer-a-friend flag - maybe wrong and hacky
LoadAccountLinkedState();
if (GetAccountLinkedState() != STATE_NOT_LINKED)
SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND);
// set grant flag
if (m_GrantableLevelsCount > 0)
SetByteValue(PLAYER_FIELD_BYTES, 1, 0x01);
_LoadGlyphs(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS));
_LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
ApplyGlyphs(true);
// add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
if ( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
m_deathState = DEAD;
_LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
// after spell load, learn rewarded spell if need also
_LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
_LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
_LoadWeeklyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADWEEKLYQUESTSTATUS));
_LoadMonthlyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMONTHLYQUESTSTATUS));
_LoadRandomBGStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADRANDOMBG));
_LoadTalents(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTALENTS));
// after spell and quest load
InitTalentForLevel();
learnDefaultSpells();
// must be before inventory (some items required reputation check)
m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
_LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
_LoadItemLoot(holder->GetResult(PLAYER_LOGIN_QUERY_LOADITEMLOOT));
// update items with duration and realtime
UpdateItemDuration(time_diff, true);
_LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetObjectGuid());
// check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
// note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
uint32 curTitle = fields[46].GetUInt32();
if (curTitle && !HasTitle(curTitle))
curTitle = 0;
SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle);
// Not finish taxi flight path
if (m_bgData.HasTaxiPath())
{
m_taxi.ClearTaxiDestinations();
for (int i = 0; i < 2; ++i)
m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
}
else if (!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes, GetTeam()))
{
// problems with taxi path loading
TaxiNodesEntry const* nodeEntry = NULL;
if (uint32 node_id = m_taxi.GetTaxiSource())
nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
if (!nodeEntry) // don't know taxi start node, to homebind
{
sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
RelocateToHomebind();
}
else // have start node, to it
{
sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
SetLocationMapId(nodeEntry->map_id);
Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
}
//we can be relocated from taxi and still have an outdated Map pointer!
//so we need to get a new Map pointer!
if (Map* map = sMapMgr.CreateMap(GetMapId(), this))
SetMap(map);
else
RelocateToHomebind();
SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
m_taxi.ClearTaxiDestinations();
}
if (uint32 node_id = m_taxi.GetTaxiSource())
{
// save source node as recall coord to prevent recall and fall from sky
TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
MANGOS_ASSERT(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
m_recallMap = nodeEntry->map_id;
m_recallX = nodeEntry->x;
m_recallY = nodeEntry->y;
m_recallZ = nodeEntry->z;
// flight will started later
}
// has to be called after last Relocate() in Player::LoadFromDB
SetFallInformation(0, GetPositionZ());
_LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
// Spell code allow apply any auras to dead character in load time in aura/spell/item loading
// Do now before stats re-calculation cleanup for ghost state unexpected auras
if(!isAlive())
RemoveAllAurasOnDeath();
//apply all stat bonuses from items and auras
SetCanModifyStats(true);
UpdateAllStats();
// restore remembered power/health values (but not more max values)
uint32 savedhealth = fields[50].GetUInt32();
SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
for(uint32 i = 0; i < MAX_POWERS; ++i)
{
uint32 savedpower = fields[51+i].GetUInt32();
SetPower(Powers(i),savedpower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedpower);
}
DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_STATS, "The value of player %s after load item and aura is: ", m_name.c_str());
outDebugStatsValues();
// all fields read
delete result;
// GM state
if (GetSession()->GetSecurity() > SEC_PLAYER)
{
switch(sWorld.getConfig(CONFIG_UINT32_GM_LOGIN_STATE))
{
default:
case 0: break; // disable
case 1: SetGameMaster(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_ON)
SetGameMaster(true);
break;
}
switch(sWorld.getConfig(CONFIG_UINT32_GM_VISIBLE_STATE))
{
default:
case 0: SetGMVisible(false); break; // invisible
case 1: break; // visible
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_INVISIBLE)
SetGMVisible(false);
break;
}
switch(sWorld.getConfig(CONFIG_UINT32_GM_ACCEPT_TICKETS))
{
default:
case 0: break; // disable
case 1: SetAcceptTicket(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
SetAcceptTicket(true);
break;
}
switch(sWorld.getConfig(CONFIG_UINT32_GM_CHAT))
{
default:
case 0: break; // disable
case 1: SetGMChat(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_GM_CHAT)
SetGMChat(true);
break;
}
switch(sWorld.getConfig(CONFIG_UINT32_GM_WISPERING_TO))
{
default:
case 0: break; // disable
case 1: SetAcceptWhispers(true); break; // enable
case 2: // save state
if (extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
SetAcceptWhispers(true);
break;
}
}
_LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
m_achievementMgr.CheckAllAchievementCriteria();
_LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
if (!GetGroup() || !GetGroup()->isLFDGroup())
{
sLFGMgr.RemoveMemberFromLFDGroup(GetGroup(),GetObjectGuid());
}
return true;
}
bool Player::isAllowedToLoot(Creature* creature)
{
// never tapped by any (mob solo kill)
if (!creature->HasFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_TAPPED))
return false;
if (Player* recipient = creature->GetLootRecipient())
{
if (recipient == this)
return true;
if (Group* otherGroup = recipient->GetGroup())
{
Group* thisGroup = GetGroup();
if (!thisGroup)
return false;
return thisGroup == otherGroup;
}
return false;
}
else
// prevent other players from looting if the recipient got disconnected
return !creature->HasLootRecipient();
}
void Player::_LoadActions(QueryResult *result)
{
for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
m_actionButtons[i].clear();
//QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint8 spec = fields[0].GetUInt8();
uint8 button = fields[1].GetUInt8();
uint32 action = fields[2].GetUInt32();
uint8 type = fields[3].GetUInt8();
if (ActionButton* ab = addActionButton(spec, button, action, type))
ab->uState = ACTIONBUTTON_UNCHANGED;
else
{
sLog.outError( " ...at loading, and will deleted in DB also");
// Will deleted in DB at next save (it can create data until save but marked as deleted)
m_actionButtons[spec][button].uState = ACTIONBUTTON_DELETED;
}
}
while( result->NextRow() );
delete result;
}
}
void Player::_LoadAuras(QueryResult *result, uint32 timediff)
{
//RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explicitly cleaned early
//QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,item_guid,spell,stackcount,remaincharges,basepoints0,basepoints1,basepoints2,periodictime0,periodictime1,periodictime2,maxduration,remaintime,effIndexMask FROM character_aura WHERE guid = '%u'",GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
ObjectGuid caster_guid = ObjectGuid(fields[0].GetUInt64());
uint32 item_lowguid = fields[1].GetUInt32();
uint32 spellid = fields[2].GetUInt32();
uint32 stackcount = fields[3].GetUInt32();
uint32 remaincharges = fields[4].GetUInt32();
int32 damage[MAX_EFFECT_INDEX];
uint32 periodicTime[MAX_EFFECT_INDEX];
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
damage[i] = fields[i+5].GetInt32();
periodicTime[i] = fields[i+8].GetUInt32();
}
int32 maxduration = fields[11].GetInt32();
int32 remaintime = fields[12].GetInt32();
uint32 effIndexMask = fields[13].GetUInt32();
SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
if (!spellproto)
{
sLog.outError("Unknown spell (spellid %u), ignore.",spellid);
continue;
}
if (caster_guid.IsEmpty() || !caster_guid.IsUnit())
{
sLog.outError("Player::LoadAuras Unknown caster %u, ignore.",fields[0].GetUInt64());
continue;
}
if (remaintime != -1 && !IsPositiveSpell(spellproto))
{
if (remaintime/IN_MILLISECONDS <= int32(timediff))
continue;
remaintime -= timediff*IN_MILLISECONDS;
}
// prevent wrong values of remaincharges
if (spellproto->procCharges == 0)
remaincharges = 0;
if (!spellproto->StackAmount)
stackcount = 1;
else if (spellproto->StackAmount < stackcount)
stackcount = spellproto->StackAmount;
else if (!stackcount)
stackcount = 1;
SpellAuraHolderPtr holder = CreateSpellAuraHolder(spellproto, this, NULL);
holder->SetLoadedState(caster_guid, ObjectGuid(HIGHGUID_ITEM, item_lowguid), stackcount, remaincharges, maxduration, remaintime);
for (int32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if ((effIndexMask & (1 << i)) == 0)
continue;
Aura* aura = holder->CreateAura(spellproto, SpellEffectIndex(i), NULL, holder, this, NULL, NULL);
if (!damage[i])
damage[i] = aura->GetModifier()->m_amount;
aura->SetLoadedState(damage[i], periodicTime[i]);
}
if (!holder->IsEmptyHolder())
{
// reset stolen single target auras
if (caster_guid != GetObjectGuid() && holder->IsSingleTarget())
holder->SetIsSingleTarget(false);
AddSpellAuraHolder(holder);
DETAIL_LOG("Added auras from spellid %u", spellproto->Id);
}
}
while( result->NextRow() );
delete result;
}
if (getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
}
void Player::_LoadGlyphs(QueryResult *result)
{
if(!result)
return;
// 0 1 2
// "SELECT spec, slot, glyph FROM character_glyphs WHERE guid='%u'"
do
{
Field *fields = result->Fetch();
uint8 spec = fields[0].GetUInt8();
uint8 slot = fields[1].GetUInt8();
uint32 glyph = fields[2].GetUInt32();
GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph);
if(!gp)
{
sLog.outError("Player %s has not existing glyph entry %u on index %u, spec %u", m_name.c_str(), glyph, slot, spec);
continue;
}
GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(slot));
if (!gs)
{
sLog.outError("Player %s has not existing glyph slot entry %u on index %u, spec %u", m_name.c_str(), GetGlyphSlot(slot), slot, spec);
continue;
}
if (gp->TypeFlags != gs->TypeFlags)
{
sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
continue;
}
m_glyphs[spec][slot].id = glyph;
} while( result->NextRow() );
delete result;
}
void Player::LoadCorpse()
{
if ( isAlive() )
{
sObjectAccessor.ConvertCorpseForPlayer(GetObjectGuid());
}
else
{
if (Corpse *corpse = GetCorpse())
{
ApplyModByteFlag(PLAYER_FIELD_BYTES, 0, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
}
else
{
//Prevent Dead Player login without corpse
ResurrectPlayer(0.5f);
}
}
}
void Player::_LoadInventory(QueryResult *result, uint32 timediff)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT data,text,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow());
std::map<uint32, Bag*> bagMap; // fast guid lookup for bags
//NOTE: the "order by `bag`" is important because it makes sure
//the bagMap is filled before items in the bags are loaded
//NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
//expected to be equipped before offhand items (TODO: fixme)
uint32 zone = GetZoneId();
if (result)
{
std::list<Item*> problematicItems;
// prevent items from being added to the queue when stored
m_itemUpdateQueueBlocked = true;
do
{
Field *fields = result->Fetch();
uint32 bag_guid = fields[2].GetUInt32();
uint8 slot = fields[3].GetUInt8();
uint32 item_lowguid = fields[4].GetUInt32();
uint32 item_id = fields[5].GetUInt32();
ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
if (!proto)
{
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_lowguid);
sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
continue;
}
Item *item = NewItemOrBag(proto);
if (!item->LoadFromDB(item_lowguid, fields, GetObjectGuid()))
{
sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
item->FSetState(ITEM_REMOVED);
item->SaveToDB(); // it also deletes item object !
continue;
}
// not allow have in alive state item limited to another map/zone
if (isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone))
{
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
item->FSetState(ITEM_REMOVED);
item->SaveToDB(); // it also deletes item object !
continue;
}
// "Conjured items disappear if you are logged out for more than 15 minutes"
if (timediff > 15*MINUTE && (item->GetProto()->Flags & ITEM_FLAG_CONJURED))
{
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
item->FSetState(ITEM_REMOVED);
item->SaveToDB(); // it also deletes item object !
continue;
}
if (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BOP_TRADEABLE))
{
QueryResult *result = CharacterDatabase.PQuery("SELECT allowedPlayers FROM item_soulbound_trade_data WHERE itemGuid = '%u'", item->GetGUIDLow());
if (!result)
{
sLog.outError("Item::LoadFromDB, Item GUID: %u has flag ITEM_FLAG_BOP_TRADEABLE but has no data in item_soulbound_trade_data, removing flag.", item->GetGUIDLow());
item->RemoveFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_BOP_TRADEABLE);
}
else
{
Field* fields2 = result->Fetch();
std::string strGUID = fields2[0].GetCppString();
Tokens GUIDlist(strGUID, ' ');
AllowedLooterSet looters;
for (Tokens::iterator itr = GUIDlist.begin(); itr != GUIDlist.end(); ++itr)
looters.insert(atol(*itr));
item->SetSoulboundTradeable(&looters, this, true);
m_itemSoulboundTradeable.push_back(item);
}
}
bool success = true;
// the item/bag is not in a bag
if (!bag_guid)
{
item->SetContainer( NULL );
item->SetSlot(slot);
if (IsInventoryPos( INVENTORY_SLOT_BAG_0, slot))
{
ItemPosCountVec dest;
if (CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false) == EQUIP_ERR_OK)
item = StoreItem(dest, item, true);
else
success = false;
}
else if (IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot))
{
uint16 dest;
if (CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK)
QuickEquipItem(dest, item);
else
success = false;
}
else if (IsBankPos( INVENTORY_SLOT_BAG_0, slot))
{
ItemPosCountVec dest;
if (CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK)
item = BankItem(dest, item, true);
else
success = false;
}
if (success)
{
// store bags that may contain items in them
if (item->IsBag() && IsBagPos(item->GetPos()))
bagMap[item_lowguid] = (Bag*)item;
}
}
// the item/bag in a bag
else
{
item->SetSlot(NULL_SLOT);
// the item is in a bag, find the bag
std::map<uint32, Bag*>::const_iterator itr = bagMap.find(bag_guid);
if (itr != bagMap.end() && slot < itr->second->GetBagSize())
{
ItemPosCountVec dest;
if (CanStoreItem(itr->second->GetSlot(), slot, dest, item, false) == EQUIP_ERR_OK)
item = StoreItem(dest, item, true);
else
success = false;
}
else
success = false;
}
// item's state may have changed after stored
if (success)
{
item->SetState(ITEM_UNCHANGED, this);
// restore container unchanged state also
if (item->GetContainer())
item->GetContainer()->SetState(ITEM_UNCHANGED, this);
// recharged mana gem
if (timediff > 15*MINUTE && proto->ItemLimitCategory ==ITEM_LIMIT_CATEGORY_MANA_GEM)
item->RestoreCharges();
}
else
{
sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by some reason, will send by mail.", GetName(),item_lowguid, item_id, bag_guid, slot);
CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_lowguid);
problematicItems.push_back(item);
}
} while (result->NextRow());
delete result;
m_itemUpdateQueueBlocked = false;
// send by mail problematic items
while(!problematicItems.empty())
{
std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
// fill mail
MailDraft draft(subject, "There's were problems with equipping item(s).");
for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
{
Item* item = problematicItems.front();
problematicItems.pop_front();
draft.AddItem(item);
}
draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);
}
}
//if (isAlive())
_ApplyAllItemMods();
}
void Player::_LoadItemLoot(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT guid,itemid,amount,suffix,property FROM item_loot WHERE guid = '%u'", GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 item_guid = fields[0].GetUInt32();
Item* item = GetItemByGuid(ObjectGuid(HIGHGUID_ITEM, item_guid));
if (!item)
{
CharacterDatabase.PExecute("DELETE FROM item_loot WHERE guid = '%u'", item_guid);
sLog.outError("Player::_LoadItemLoot: Player %s has loot for nonexistent item (GUID: %u) in `item_loot`, deleted.", GetName(), item_guid );
continue;
}
item->LoadLootFromDB(fields);
} while (result->NextRow());
delete result;
}
}
// load mailed item which should receive current player
void Player::_LoadMailedItems(QueryResult *result)
{
// data needs to be at first place for Item::LoadFromDB
// 0 1 2 3 4
// "SELECT data, text, mail_id, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE receiver = '%u'", GUID_LOPART(m_guid)
if(!result)
return;
do
{
Field *fields = result->Fetch();
uint32 mail_id = fields[2].GetUInt32();
uint32 item_guid_low = fields[3].GetUInt32();
uint32 item_template = fields[4].GetUInt32();
Mail* mail = GetMail(mail_id);
if(!mail)
continue;
mail->AddItem(item_guid_low, item_template);
ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
if(!proto)
{
sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
continue;
}
Item *item = NewItemOrBag(proto);
if (!item->LoadFromDB(item_guid_low, fields, GetObjectGuid()))
{
sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
item->FSetState(ITEM_REMOVED);
item->SaveToDB(); // it also deletes item object !
continue;
}
AddMItem(item);
} while (result->NextRow());
delete result;
}
void Player::_LoadMails(QueryResult *result)
{
m_mail.clear();
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13
//"SELECT id,messageType,sender,receiver,subject,body,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId,has_items FROM mail WHERE receiver = '%u' ORDER BY id DESC", GetGUIDLow()
if(!result)
return;
do
{
Field *fields = result->Fetch();
Mail *m = new Mail;
m->messageID = fields[0].GetUInt32();
m->messageType = fields[1].GetUInt8();
m->sender = fields[2].GetUInt32();
m->receiverGuid = ObjectGuid(HIGHGUID_PLAYER, fields[3].GetUInt32());
m->subject = fields[4].GetCppString();
m->body = fields[5].GetCppString();
m->expire_time = (time_t)fields[6].GetUInt64();
m->deliver_time = (time_t)fields[7].GetUInt64();
m->money = fields[8].GetUInt32();
m->COD = fields[9].GetUInt32();
m->checked = fields[10].GetUInt32();
m->stationery = fields[11].GetUInt8();
m->mailTemplateId = fields[12].GetInt16();
m->has_items = fields[13].GetBool(); // true, if mail have items or mail have template and items generated (maybe none)
if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
{
sLog.outError( "Player::_LoadMail - Mail (%u) have nonexistent MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
m->mailTemplateId = 0;
}
m->state = MAIL_STATE_UNCHANGED;
m_mail.push_back(m);
if (m->mailTemplateId && !m->has_items)
m->prepareTemplateItems(this);
} while( result->NextRow() );
delete result;
}
void Player::LoadPet()
{
// fixme: the pet should still be loaded if the player is not in world
// just not added to the map
if (IsInWorld())
{
if (!sWorld.getConfig(CONFIG_BOOL_PET_SAVE_ALL))
{
Pet* pet = new Pet;
pet->SetPetCounter(0);
if(!pet->LoadPetFromDB(this, 0, 0, true))
{
delete pet;
return;
}
}
else
{
QueryResult* result = CharacterDatabase.PQuery("SELECT id, PetType, CreatedBySpell, savetime FROM character_pet WHERE owner = '%u' AND entry = (SELECT entry FROM character_pet WHERE owner = '%u' AND slot = '%u') ORDER BY slot ASC",
GetGUIDLow(), GetGUIDLow(),PET_SAVE_AS_CURRENT);
std::vector<uint32> petnumber;
uint32 _PetType = 0;
uint32 _CreatedBySpell = 0;
uint64 _saveTime = 0;
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 petnum = fields[0].GetUInt32();
if (petnum)
petnumber.push_back(petnum);
if (!_PetType)
_PetType = fields[1].GetUInt32();
if (!_CreatedBySpell)
_CreatedBySpell = fields[2].GetUInt32();
if (!_saveTime)
_saveTime = fields[3].GetUInt64();
}
while (result->NextRow());
delete result;
}
else
return;
if (petnumber.empty())
return;
if (_CreatedBySpell != 13481 && !HasSpell(_CreatedBySpell))
return;
SpellEntry const* spellInfo = sSpellStore.LookupEntry(_CreatedBySpell);
if (!spellInfo)
return;
uint32 count = 1;
if (_CreatedBySpell == 51533 || _CreatedBySpell == 33831)
count = spellInfo->CalculateSimpleValue(EFFECT_INDEX_0);
petnumber.resize(count);
if (GetSpellDuration(spellInfo) > 0)
if (uint64(time(NULL)) - GetSpellDuration(spellInfo)/IN_MILLISECONDS > _saveTime)
return;
if (_CreatedBySpell != 13481 && !HasSpell(_CreatedBySpell))
return;
if (!petnumber.empty())
{
for(uint8 i = 0; i < petnumber.size(); ++i)
{
if (petnumber[i] == 0)
continue;
Pet* _pet = new Pet;
_pet->SetPetCounter(petnumber.size() - i - 1);
if (!_pet->LoadPetFromDB(this, 0, petnumber[i], true))
delete _pet;
}
}
}
}
}
void Player::_LoadQuestStatus(QueryResult *result)
{
mQuestStatus.clear();
uint32 slot = 0;
//// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
//QueryResult *result = CharacterDatabase.PQuery("SELECT quest, status, rewarded, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4, itemcount5, itemcount6 FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
// used to be new, no delete?
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if ( pQuest )
{
// find or create
QuestStatusData& questStatusData = mQuestStatus[quest_id];
uint32 qstatus = fields[1].GetUInt32();
if (qstatus < MAX_QUEST_STATUS)
questStatusData.m_status = QuestStatus(qstatus);
else
{
questStatusData.m_status = QUEST_STATUS_NONE;
sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
}
questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
time_t quest_time = time_t(fields[4].GetUInt64());
if (pQuest->HasSpecialFlag(QUEST_SPECIAL_FLAG_TIMED) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE)
{
AddTimedQuest( quest_id );
if (quest_time <= sWorld.GetGameTime())
questStatusData.m_timer = 1;
else
questStatusData.m_timer = uint32(quest_time - sWorld.GetGameTime()) * IN_MILLISECONDS;
}
else
quest_time = 0;
questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
questStatusData.m_itemcount[0] = fields[9].GetUInt32();
questStatusData.m_itemcount[1] = fields[10].GetUInt32();
questStatusData.m_itemcount[2] = fields[11].GetUInt32();
questStatusData.m_itemcount[3] = fields[12].GetUInt32();
questStatusData.m_itemcount[4] = fields[13].GetUInt32();
questStatusData.m_itemcount[5] = fields[14].GetUInt32();
questStatusData.uState = QUEST_UNCHANGED;
// add to quest log
if (slot < MAX_QUEST_LOG_SIZE &&
((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
questStatusData.m_status == QUEST_STATUS_COMPLETE ||
questStatusData.m_status == QUEST_STATUS_FAILED) &&
(!questStatusData.m_rewarded || pQuest->IsRepeatable())))
{
SetQuestSlot(slot, quest_id, uint32(quest_time));
if (questStatusData.m_explored)
SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
if (questStatusData.m_status == QUEST_STATUS_FAILED)
SetQuestSlotState(slot, QUEST_STATE_FAIL);
for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
if (questStatusData.m_creatureOrGOcount[idx])
SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
++slot;
}
if (questStatusData.m_rewarded)
{
// learn rewarded spell if unknown
learnQuestRewardedSpells(pQuest);
// set rewarded title if any
if (pQuest->GetCharTitleId())
{
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
SetTitle(titleEntry);
}
if (pQuest->GetBonusTalents())
m_questRewardTalentCount += pQuest->GetBonusTalents();
}
DEBUG_LOG("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
}
}
while( result->NextRow() );
delete result;
}
// clear quest log tail
for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
SetQuestSlot(i, 0);
}
void Player::_LoadDailyQuestStatus(QueryResult *result)
{
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
//QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
if (result)
{
uint32 quest_daily_idx = 0;
do
{
if (quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
{
sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
break;
}
Field *fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if ( !pQuest )
continue;
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
++quest_daily_idx;
DEBUG_LOG("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
while( result->NextRow() );
delete result;
}
m_DailyQuestChanged = false;
}
void Player::_LoadWeeklyQuestStatus(QueryResult *result)
{
m_weeklyquests.clear();
//QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_weekly WHERE guid = '%u'", GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (!pQuest)
continue;
m_weeklyquests.insert(quest_id);
DEBUG_LOG("Weekly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
while( result->NextRow() );
delete result;
}
m_WeeklyQuestChanged = false;
}
void Player::_LoadMonthlyQuestStatus(QueryResult *result)
{
m_monthlyquests.clear();
//QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_weekly WHERE guid = '%u'", GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 quest_id = fields[0].GetUInt32();
Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
if (!pQuest)
continue;
m_monthlyquests.insert(quest_id);
DEBUG_LOG("Monthly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
}
while( result->NextRow() );
delete result;
}
m_MonthlyQuestChanged = false;
}
void Player::_LoadSpells(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 spell_id = fields[0].GetUInt32();
// skip talents & drop unneeded data
if (GetTalentSpellPos(spell_id))
{
sLog.outError("Player::_LoadSpells: %s has talent spell %u in character_spell, removing it.",
GetGuidStr().c_str(), spell_id);
CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'", spell_id);
continue;
}
addSpell(spell_id, fields[1].GetBool(), false, false, fields[2].GetBool());
}
while( result->NextRow() );
delete result;
}
}
void Player::_LoadTalents(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT talent_id, current_rank, spec FROM character_talent WHERE guid = '%u'",GetGUIDLow());
if (result)
{
do
{
Field *fields = result->Fetch();
uint32 talent_id = fields[0].GetUInt32();
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talent_id);
if (!talentInfo)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent_id: %u , this talent will be deleted from character_talent",GetGUIDLow(), talent_id );
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id);
continue;
}
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
if (!talentTabInfo)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talentTabInfo: %u for talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentInfo->TalentTab, talentInfo->TalentID );
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id);
continue;
}
// prevent load talent for different class (cheating)
if ((getClassMask() & talentTabInfo->ClassMask) == 0)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has talent with ClassMask: %u , but Player's ClassMask is: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentTabInfo->ClassMask, getClassMask() ,talentInfo->TalentID );
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id);
continue;
}
uint32 currentRank = fields[1].GetUInt32();
if (currentRank > MAX_TALENT_RANK || talentInfo->RankID[currentRank] == 0)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent rank: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), currentRank, talentInfo->TalentID );
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id);
continue;
}
uint32 spec = fields[2].GetUInt32();
if (spec > MAX_TALENT_SPEC_COUNT)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u, spec will be deleted from character_talent", GetGUIDLow(), spec);
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE spec = '%u' ", spec);
continue;
}
if (spec >= m_specsCount)
{
sLog.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u , this spec will be deleted from character_talent.", GetGUIDLow(), spec);
CharacterDatabase.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND spec = '%u' ", GetGUIDLow(), spec);
continue;
}
if (m_activeSpec == spec)
addSpell(talentInfo->RankID[currentRank], true,false,false,false);
else
{
PlayerTalent talent;
talent.currentRank = currentRank;
talent.talentEntry = talentInfo;
talent.state = PLAYERSPELL_UNCHANGED;
m_talents[spec][talentInfo->TalentID] = talent;
}
}
while (result->NextRow());
delete result;
}
}
void Player::_LoadGroup(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
if (result)
{
uint32 groupId = (*result)[0].GetUInt32();
delete result;
if (Group* group = sObjectMgr.GetGroupById(groupId))
{
uint8 subgroup = group->GetMemberGroup(GetObjectGuid());
SetGroup(group, subgroup);
if (getLevel() >= LEVELREQUIREMENT_HEROIC)
{
// the group leader may change the instance difficulty while the player is offline
SetDungeonDifficulty(group->GetDungeonDifficulty());
SetRaidDifficulty(group->GetRaidDifficulty());
}
if (group->isLFDGroup())
sLFGMgr.LoadLFDGroupPropertiesForPlayer(this);
}
}
}
void Player::_LoadBoundInstances(QueryResult *result)
{
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
m_boundInstances[i].clear();
Group *group = GetGroup();
//QueryResult *result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, extend, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
if (result)
{
do
{
Field *fields = result->Fetch();
bool perm = fields[1].GetBool();
uint32 mapId = fields[2].GetUInt32();
uint32 instanceId = fields[0].GetUInt32();
uint8 difficulty = fields[3].GetUInt8();
bool extend = fields[4].GetBool();
time_t resetTime = (time_t)fields[5].GetUInt64();
// the resettime for normal instances is only saved when the InstanceSave is unloaded
// so the value read from the DB may be wrong here but only if the InstanceSave is loaded
// and in that case it is not used
MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
if(!mapEntry || !mapEntry->IsDungeon())
{
sLog.outError("_LoadBoundInstances: player %s(%d) has bind to nonexistent or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId);
continue;
}
if (difficulty >= MAX_DIFFICULTY)
{
sLog.outError("_LoadBoundInstances: player %s(%d) has bind to nonexistent difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId);
continue;
}
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
if(!mapDiff)
{
sLog.outError("_LoadBoundInstances: player %s(%d) has bind to nonexistent difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), instanceId);
continue;
}
if(!perm && group)
{
sLog.outError("_LoadBoundInstances: %s is in group (Id: %d) but has a non-permanent character bind to map %d,%d,%d",
GetGuidStr().c_str(), group->GetId(), mapId, instanceId, difficulty);
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'",
GetGUIDLow(), instanceId);
continue;
}
// since non permanent binds are always solo bind, they can always be reset
DungeonPersistentState *state = (DungeonPersistentState*)sMapPersistentStateMgr.AddPersistentState(mapEntry, instanceId, Difficulty(difficulty), resetTime, !perm, true);
if (state)
BindToInstance(state, perm, true, extend);
} while(result->NextRow());
delete result;
}
}
InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
{
// some instances only have one difficulty
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(mapid,difficulty);
if(!mapDiff)
return NULL;
MAPLOCK_READ(this, MAP_LOCK_TYPE_DEFAULT);
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
if (itr != m_boundInstances[difficulty].end())
return &itr->second;
else
return NULL;
}
void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
{
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
UnbindInstance(itr, difficulty, unload);
}
void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
{
if (itr != m_boundInstances[difficulty].end())
{
if (!unload)
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u' AND extend = 0",
GetGUIDLow(), itr->second.state->GetInstanceId());
itr->second.state->RemovePlayer(this); // state can become invalid
m_boundInstances[difficulty].erase(itr++);
}
}
InstancePlayerBind* Player::BindToInstance(DungeonPersistentState *state, bool permanent, bool load, bool extend)
{
if (state)
{
MAPLOCK_READ(this, MAP_LOCK_TYPE_DEFAULT);
InstancePlayerBind& bind = m_boundInstances[state->GetDifficulty()][state->GetMapId()];
if (bind.state)
{
// update the state when the group kills a boss
if (permanent != bind.perm || state != bind.state || extend != bind.extend)
if (!load)
CharacterDatabase.PExecute("UPDATE character_instance SET instance = '%u', permanent = '%u', extend ='%u' WHERE guid = '%u' AND instance = '%u'",
state->GetInstanceId(), permanent, extend, GetGUIDLow(), bind.state->GetInstanceId());
}
else
{
if (!load)
CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent, extend) VALUES ('%u', '%u', '%u', '%u')",
GetGUIDLow(), state->GetInstanceId(), permanent, extend);
}
if (bind.state != state)
{
if (bind.state)
bind.state->RemovePlayer(this);
state->AddPlayer(this);
}
if (permanent)
state->SetCanReset(false);
bind.state = state;
bind.perm = permanent;
bind.extend = extend;
if (!load)
DEBUG_LOG("Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d",
GetName(), GetGUIDLow(), state->GetMapId(), state->GetInstanceId(), state->GetDifficulty());
return &bind;
}
else
return NULL;
}
DungeonPersistentState* Player::GetBoundInstanceSaveForSelfOrGroup(uint32 mapid)
{
MapEntry const* mapEntry = sMapStore.LookupEntry(mapid);
if (!mapEntry)
return NULL;
InstancePlayerBind *pBind = GetBoundInstance(mapid, GetDifficulty(mapEntry->IsRaid()));
DungeonPersistentState *state = pBind ? pBind->state : NULL;
// the player's permanent player bind is taken into consideration first
// then the player's group bind and finally the solo bind.
if (!pBind || !pBind->perm)
{
InstanceGroupBind *groupBind = NULL;
// use the player's difficulty setting (it may not be the same as the group's)
if (Group *group = GetGroup())
if (groupBind = group->GetBoundInstance(mapid, this))
state = groupBind->state;
}
return state;
}
void Player::BindToInstance()
{
WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
data << uint32(0);
GetSession()->SendPacket(&data);
BindToInstance(_pendingBind, true);
}
void Player::SendRaidInfo()
{
uint32 counter = 0;
WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
size_t p_counter = data.wpos();
data << uint32(counter); // placeholder
time_t now = time(NULL);
for(int i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
{
if (itr->second.perm)
{
DungeonPersistentState* state = itr->second.state;
data << uint32(state->GetMapId()); // map id
data << uint32(state->GetDifficulty()); // difficulty
data << ObjectGuid(state->GetInstanceGuid()); // instance guid
data << uint8((state->GetRealResetTime() > now) ? 1 : 0 ); // expired = 0
data << uint8(itr->second.extend ? 1 : 0); // extended = 1
data << uint32(state->GetRealResetTime() > now ? state->GetRealResetTime() - now
: DungeonResetScheduler::CalculateNextResetTime(GetMapDifficultyData(state->GetMapId(), state->GetDifficulty()))); // reset time
++counter;
}
}
}
data.put<uint32>(p_counter, counter);
GetSession()->SendPacket(&data);
}
/*
- called on every successful teleportation to a map
*/
void Player::SendSavedInstances()
{
bool hasBeenSaved = false;
WorldPacket data;
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
{
if (itr->second.perm) // only permanent binds are sent
{
hasBeenSaved = true;
break;
}
}
}
//Send opcode 811. true or false means, whether you have current raid/heroic instances
data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
data << uint32(hasBeenSaved);
GetSession()->SendPacket(&data);
if(!hasBeenSaved)
return;
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
{
if (itr->second.perm)
{
data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
data << uint32(itr->second.state->GetMapId());
GetSession()->SendPacket(&data);
}
}
}
}
/// convert the player's binds to the group
void Player::ConvertInstancesToGroup(Player *player, Group *group, ObjectGuid player_guid)
{
bool has_binds = false;
bool has_solo = false;
if (player)
{
player_guid = player->GetObjectGuid();
if (!group)
group = player->GetGroup();
}
MANGOS_ASSERT(player_guid);
// copy all binds to the group, when changing leader it's assumed the character
// will not have any solo binds
if (player)
{
for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
{
for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
{
has_binds = true;
if (group)
group->BindToInstance(itr->second.state, itr->second.perm, true);
// permanent binds are not removed
if (!itr->second.perm)
{
// increments itr in call
player->UnbindInstance(itr, Difficulty(i), true);
has_solo = true;
}
else
++itr;
}
}
}
uint32 player_lowguid = player_guid.GetCounter();
// if the player's not online we don't know what binds it has
if (!player || !group || has_binds)
CharacterDatabase.PExecute("REPLACE INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", player_lowguid);
// the following should not get executed when changing leaders
if (!player || has_solo)
CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND permanent = 0 AND extend = 0", player_lowguid);
}
bool Player::_LoadHomeBind(QueryResult *result)
{
PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
if(!info)
{
sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
return false;
}
bool ok = false;
//QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
if (result)
{
Field *fields = result->Fetch();
m_homebindMapId = fields[0].GetUInt32();
m_homebindAreaId = fields[1].GetUInt16();
m_homebindX = fields[2].GetFloat();
m_homebindY = fields[3].GetFloat();
m_homebindZ = fields[4].GetFloat();
delete result;
MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
// accept saved data only for valid position (and non instanceable), and accessable
if ( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
!bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
{
ok = true;
}
else
CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
}
if(!ok)
{
m_homebindMapId = info->mapId;
m_homebindAreaId = info->areaId;
m_homebindX = info->positionX;
m_homebindY = info->positionY;
m_homebindZ = info->positionZ;
CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
}
DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);
return true;
}
/*********************************************************/
/*** SAVE SYSTEM ***/
/*********************************************************/
void Player::SaveToDB()
{
// we should assure this: ASSERT((m_nextSave != sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE)));
// delay auto save at any saves (manual, in code, or autosave)
m_nextSave = sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE);
//lets allow only players in world to be saved
if (IsBeingTeleportedFar())
{
ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
return;
}
// first save/honor gain after midnight will also update the player's honor fields
UpdateHonorFields();
DEBUG_FILTER_LOG(LOG_FILTER_PLAYER_STATS, "The value of player %s at save: ", m_name.c_str());
outDebugStatsValues();
CharacterDatabase.BeginTransaction();
static SqlStatementID delChar ;
static SqlStatementID insChar ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delChar, "DELETE FROM characters WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
SqlStatement uberInsert = CharacterDatabase.CreateStatement(insChar, "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
"map, dungeon_difficulty, position_x, position_y, position_z, orientation, "
"taximask, online, cinematic, "
"totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
"trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
"death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
"todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
"power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars, grantableLevels) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, "
"?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
uberInsert.addUInt32(GetGUIDLow());
uberInsert.addUInt32(GetSession()->GetAccountId());
uberInsert.addString(m_name);
uberInsert.addUInt8(getRace());
uberInsert.addUInt8(getClass());
uberInsert.addUInt8(getGender());
uberInsert.addUInt32(getLevel());
uberInsert.addUInt32(GetUInt32Value(PLAYER_XP));
uberInsert.addUInt32(GetMoney());
uberInsert.addUInt32(GetUInt32Value(PLAYER_BYTES));
uberInsert.addUInt32(GetUInt32Value(PLAYER_BYTES_2));
uberInsert.addUInt32(GetUInt32Value(PLAYER_FLAGS));
if(!IsBeingTeleported())
{
uberInsert.addUInt32(GetMapId());
uberInsert.addUInt32(GetDifficulty());
uberInsert.addFloat(finiteAlways(GetPositionX()));
uberInsert.addFloat(finiteAlways(GetPositionY()));
uberInsert.addFloat(finiteAlways(GetPositionZ()));
uberInsert.addFloat(finiteAlways(GetOrientation()));
}
else
{
uberInsert.addUInt32(GetTeleportDest().mapid);
uberInsert.addUInt32(GetDifficulty());
uberInsert.addFloat(finiteAlways(GetTeleportDest().coord_x));
uberInsert.addFloat(finiteAlways(GetTeleportDest().coord_y));
uberInsert.addFloat(finiteAlways(GetTeleportDest().coord_z));
uberInsert.addFloat(finiteAlways(GetTeleportDest().orientation));
}
std::ostringstream ss;
ss << m_taxi; // string with TaxiMaskSize numbers
uberInsert.addString(ss);
uberInsert.addUInt32(IsInWorld() ? 1 : 0);
uberInsert.addUInt32(m_cinematic);
uberInsert.addUInt32(m_Played_time[PLAYED_TIME_TOTAL]);
uberInsert.addUInt32(m_Played_time[PLAYED_TIME_LEVEL]);
uberInsert.addFloat(finiteAlways(m_rest_bonus));
uberInsert.addUInt64(uint64(time(NULL)));
uberInsert.addUInt32(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0);
//save, far from tavern/city
//save, but in tavern/city
uberInsert.addUInt32(m_resetTalentsCost);
uberInsert.addUInt64(uint64(m_resetTalentsTime));
uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->x));
uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->y));
uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->z));
uberInsert.addFloat(finiteAlways(m_movementInfo.GetTransportPos()->o));
if (m_transport)
uberInsert.addUInt32(m_transport->GetGUIDLow());
else
uberInsert.addUInt32(0);
uberInsert.addUInt32(m_ExtraFlags);
uberInsert.addUInt32(uint32(m_stableSlots)); // to prevent save uint8 as char
uberInsert.addUInt32(uint32(m_atLoginFlags));
uberInsert.addUInt32(IsInWorld() ? GetZoneId() : GetCachedZoneId());
uberInsert.addUInt64(uint64(m_deathExpireTime));
ss << m_taxi.SaveTaxiDestinationsToString(); //string
uberInsert.addString(ss);
uberInsert.addUInt32(GetArenaPoints());
uberInsert.addUInt32(GetHonorPoints());
uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION) );
uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION));
uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS));
uberInsert.addUInt16(GetUInt16Value(PLAYER_FIELD_KILLS, 0));
uberInsert.addUInt16(GetUInt16Value(PLAYER_FIELD_KILLS, 1));
uberInsert.addUInt32(GetUInt32Value(PLAYER_CHOSEN_TITLE));
uberInsert.addUInt64(GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES));
// FIXME: at this moment send to DB as unsigned, including unit32(-1)
uberInsert.addUInt32(GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX));
uberInsert.addUInt16(uint16(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
uberInsert.addUInt32(GetHealth());
for(uint32 i = 0; i < MAX_POWERS; ++i)
uberInsert.addUInt32(GetPower(Powers(i)));
uberInsert.addUInt32(uint32(m_specsCount));
uberInsert.addUInt32(uint32(m_activeSpec));
for(uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i ) //string
{
ss << GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + i) << " ";
}
uberInsert.addString(ss);
for(uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i ) //string
{
ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << " ";
}
uberInsert.addString(ss);
uberInsert.addUInt32(GetUInt32Value(PLAYER_AMMO_ID));
for(uint32 i = 0; i < KNOWN_TITLES_SIZE*2; ++i ) //string
{
ss << GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES + i) << " ";
}
uberInsert.addString(ss);
uberInsert.addUInt32(uint32(GetByteValue(PLAYER_FIELD_BYTES, 2)));
uberInsert.addUInt32(uint32(m_GrantableLevelsCount));
uberInsert.Execute();
if (m_mailsUpdated) //save mails only when needed
_SaveMail();
_SaveBGData();
_SaveInventory();
_SaveQuestStatus();
_SaveDailyQuestStatus();
_SaveWeeklyQuestStatus();
_SaveMonthlyQuestStatus();
_SaveSpells();
_SaveSpellCooldowns();
_SaveActions();
_SaveAuras();
_SaveSkills();
m_achievementMgr.SaveToDB();
m_reputationMgr.SaveToDB();
_SaveEquipmentSets();
GetSession()->SaveTutorialsData(); // changed only while character in game
_SaveGlyphs();
_SaveTalents();
CharacterDatabase.CommitTransaction();
// check if stats should only be saved on logout
// save stats can be out of transaction
if (m_session->isLogingOut() || !sWorld.getConfig(CONFIG_BOOL_STATS_SAVE_ONLY_ON_LOGOUT))
_SaveStats();
// save pet (hunter pet level and experience and all type pets health/mana).
if (Pet* pet = GetPet())
pet->SavePetToDB(PET_SAVE_AS_CURRENT);
}
// fast save function for item/money cheating preventing - save only inventory and money state
void Player::SaveInventoryAndGoldToDB()
{
_SaveInventory();
SaveGoldToDB();
}
void Player::SaveGoldToDB()
{
static SqlStatementID updateGold ;
SqlStatement stmt = CharacterDatabase.CreateStatement(updateGold, "UPDATE characters SET money = ? WHERE guid = ?");
stmt.PExecute(GetMoney(), GetGUIDLow());
}
void Player::_SaveActions()
{
static SqlStatementID insertAction ;
static SqlStatementID updateAction ;
static SqlStatementID deleteAction ;
for(int i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
{
for(ActionButtonList::iterator itr = m_actionButtons[i].begin(); itr != m_actionButtons[i].end(); )
{
switch (itr->second.uState)
{
case ACTIONBUTTON_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insertAction, "INSERT INTO character_action (guid,spec, button,action,type) VALUES (?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(i);
stmt.addUInt32(uint32(itr->first));
stmt.addUInt32(itr->second.GetAction());
stmt.addUInt32(uint32(itr->second.GetType()));
stmt.Execute();
itr->second.uState = ACTIONBUTTON_UNCHANGED;
++itr;
}
break;
case ACTIONBUTTON_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateAction, "UPDATE character_action SET action = ?, type = ? WHERE guid = ? AND button = ? AND spec = ?");
stmt.addUInt32(itr->second.GetAction());
stmt.addUInt32(uint32(itr->second.GetType()));
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(uint32(itr->first));
stmt.addUInt32(i);
stmt.Execute();
itr->second.uState = ACTIONBUTTON_UNCHANGED;
++itr;
}
break;
case ACTIONBUTTON_DELETED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteAction, "DELETE FROM character_action WHERE guid = ? AND button = ? AND spec = ?");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(uint32(itr->first));
stmt.addUInt32(i);
stmt.Execute();
m_actionButtons[i].erase(itr++);
}
break;
default:
++itr;
break;
}
}
}
}
void Player::_SaveAuras()
{
static SqlStatementID deleteAuras ;
static SqlStatementID insertAuras ;
MAPLOCK_READ(this,MAP_LOCK_TYPE_AURAS);
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteAuras, "DELETE FROM character_aura WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
SpellAuraHolderMap const& auraHolders = GetSpellAuraHolderMap();
if (auraHolders.empty())
return;
stmt = CharacterDatabase.CreateStatement(insertAuras, "INSERT INTO character_aura (guid, caster_guid, item_guid, spell, stackcount, remaincharges, "
"basepoints0, basepoints1, basepoints2, periodictime0, periodictime1, periodictime2, maxduration, remaintime, effIndexMask) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
for(SpellAuraHolderMap::const_iterator itr = auraHolders.begin(); itr != auraHolders.end(); ++itr)
{
//skip all holders from spells that are passive or channeled
//do not save single target holders (unless they were cast by the player)
if (itr->second && !itr->second->IsDeleted() && !itr->second->IsPassive() && !IsChanneledSpell(itr->second->GetSpellProto()) && (itr->second->GetCasterGuid() == GetObjectGuid() || !itr->second->IsSingleTarget()) && !IsChanneledSpell(itr->second->GetSpellProto()))
{
int32 damage[MAX_EFFECT_INDEX];
uint32 periodicTime[MAX_EFFECT_INDEX];
uint32 effIndexMask = 0;
for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i)
{
damage[i] = 0;
periodicTime[i] = 0;
if (Aura *aur = itr->second->GetAuraByEffectIndex(SpellEffectIndex(i)))
{
// don't save not own area auras
if (aur->IsAreaAura() && itr->second->GetCasterGuid() != GetObjectGuid())
continue;
damage[i] = aur->GetModifier()->m_amount;
periodicTime[i] = aur->GetModifier()->periodictime;
effIndexMask |= (1 << i);
}
}
if (!effIndexMask)
continue;
stmt.addUInt32(GetGUIDLow());
stmt.addUInt64(itr->second->GetCasterGuid().GetRawValue());
stmt.addUInt32(itr->second->GetCastItemGuid().GetCounter());
stmt.addUInt32(itr->second->GetId());
stmt.addUInt32(itr->second->GetStackAmount());
stmt.addUInt8(itr->second->GetAuraCharges());
for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i)
stmt.addInt32(damage[i]);
for (uint32 i = 0; i < MAX_EFFECT_INDEX; ++i)
stmt.addUInt32(periodicTime[i]);
stmt.addInt32(itr->second->GetAuraMaxDuration());
stmt.addInt32(itr->second->GetAuraDuration());
stmt.addUInt32(effIndexMask);
stmt.Execute();
}
}
}
void Player::_SaveGlyphs()
{
static SqlStatementID insertGlyph ;
static SqlStatementID updateGlyph ;
static SqlStatementID deleteGlyph ;
for (uint8 spec = 0; spec < m_specsCount; ++spec)
{
for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
{
switch(m_glyphs[spec][slot].uState)
{
case GLYPH_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insertGlyph, "INSERT INTO character_glyphs (guid, spec, slot, glyph) VALUES (?, ?, ?, ?)");
stmt.PExecute(GetGUIDLow(), spec, slot, m_glyphs[spec][slot].GetId());
}
break;
case GLYPH_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateGlyph, "UPDATE character_glyphs SET glyph = ? WHERE guid = ? AND spec = ? AND slot = ?");
stmt.PExecute(m_glyphs[spec][slot].GetId(), GetGUIDLow(), spec, slot);
}
break;
case GLYPH_DELETED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteGlyph, "DELETE FROM character_glyphs WHERE guid = ? AND spec = ? AND slot = ?");
stmt.PExecute(GetGUIDLow(), spec, slot);
}
break;
case GLYPH_UNCHANGED:
break;
}
m_glyphs[spec][slot].uState = GLYPH_UNCHANGED;
}
}
}
void Player::_SaveInventory()
{
// force items in buyback slots to new state
// and remove those that aren't already
for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
{
Item *item = m_items[i];
if (!item || item->GetState() == ITEM_NEW) continue;
static SqlStatementID delInv ;
static SqlStatementID delItemInst ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delInv, "DELETE FROM character_inventory WHERE item = ?");
stmt.PExecute(item->GetGUIDLow());
stmt = CharacterDatabase.CreateStatement(delItemInst, "DELETE FROM item_instance WHERE guid = ?");
stmt.PExecute(item->GetGUIDLow());
m_items[i]->FSetState(ITEM_NEW);
}
// update enchantment durations
for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
{
itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
}
// if no changes
if (m_itemUpdateQueue.empty()) return;
// do not save if the update queue is corrupt
bool error = false;
for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
{
Item *item = m_itemUpdateQueue[i];
if(!item || item->GetState() == ITEM_REMOVED) continue;
Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
GetAntiCheat()->DoAntiCheatCheck(CHECK_ITEM_UPDATE,item,test);
if (test == NULL)
{
sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow());
error = true;
}
else if (test != item)
{
sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the item with guid %d is there instead!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
error = true;
}
}
if (error)
{
sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
return;
}
static SqlStatementID insertInventory ;
static SqlStatementID updateInventory ;
static SqlStatementID deleteInventory ;
for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
{
Item *item = m_itemUpdateQueue[i];
if(!item) continue;
Bag *container = item->GetContainer();
uint32 bag_guid = container ? container->GetGUIDLow() : 0;
switch(item->GetState())
{
case ITEM_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insertInventory, "INSERT INTO character_inventory (guid,bag,slot,item,item_template) VALUES (?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(bag_guid);
stmt.addUInt8(item->GetSlot());
stmt.addUInt32(item->GetGUIDLow());
stmt.addUInt32(item->GetEntry());
stmt.Execute();
}
break;
case ITEM_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateInventory, "UPDATE character_inventory SET guid = ?, bag = ?, slot = ?, item_template = ? WHERE item = ?");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(bag_guid);
stmt.addUInt8(item->GetSlot());
stmt.addUInt32(item->GetEntry());
stmt.addUInt32(item->GetGUIDLow());
stmt.Execute();
}
break;
case ITEM_REMOVED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteInventory, "DELETE FROM character_inventory WHERE item = ?");
stmt.PExecute(item->GetGUIDLow());
}
break;
case ITEM_UNCHANGED:
break;
}
item->SaveToDB(); // item have unchanged inventory record and can be save standalone
}
m_itemUpdateQueue.clear();
}
void Player::_SaveMail()
{
static SqlStatementID updateMail ;
static SqlStatementID deleteMailItems ;
static SqlStatementID deleteItem ;
static SqlStatementID deleteMain ;
static SqlStatementID deleteItems ;
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
{
Mail *m = (*itr);
if (m->state == MAIL_STATE_CHANGED)
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateMail, "UPDATE mail SET has_items = ?, expire_time = ?, deliver_time = ?, money = ?, cod = ?, checked = ? WHERE id = ?");
stmt.addUInt32(m->HasItems() ? 1 : 0);
stmt.addUInt64(uint64(m->expire_time));
stmt.addUInt64(uint64(m->deliver_time));
stmt.addUInt32(m->money);
stmt.addUInt32(m->COD);
stmt.addUInt32(m->checked);
stmt.addUInt32(m->messageID);
stmt.Execute();
if (m->removedItems.size())
{
stmt = CharacterDatabase.CreateStatement(deleteMailItems, "DELETE FROM mail_items WHERE item_guid = ?");
for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
stmt.PExecute(*itr2);
m->removedItems.clear();
}
m->state = MAIL_STATE_UNCHANGED;
}
else if (m->state == MAIL_STATE_DELETED)
{
if (m->HasItems())
{
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteItem, "DELETE FROM item_instance WHERE guid = ?");
for(MailItemInfoVec::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
stmt.PExecute(itr2->item_guid);
}
SqlStatement stmt = CharacterDatabase.CreateStatement(deleteMain, "DELETE FROM mail WHERE id = ?");
stmt.PExecute(m->messageID);
stmt = CharacterDatabase.CreateStatement(deleteItems, "DELETE FROM mail_items WHERE mail_id = ?");
stmt.PExecute(m->messageID);
}
}
//deallocate deleted mails...
for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
{
if ((*itr)->state == MAIL_STATE_DELETED)
{
Mail* m = *itr;
m_mail.erase(itr);
delete m;
itr = m_mail.begin();
}
else
++itr;
}
m_mailsUpdated = false;
}
void Player::_SaveQuestStatus()
{
static SqlStatementID insertQuestStatus ;
static SqlStatementID updateQuestStatus ;
// we don't need transactions here.
for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
{
switch (i->second.uState)
{
case QUEST_NEW :
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insertQuestStatus, "INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4,itemcount5,itemcount6) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(i->first);
stmt.addUInt8(i->second.m_status);
stmt.addUInt8(i->second.m_rewarded);
stmt.addUInt8(i->second.m_explored);
stmt.addUInt64(uint64(i->second.m_timer / IN_MILLISECONDS+ sWorld.GetGameTime()));
for (int k = 0; k < QUEST_OBJECTIVES_COUNT; ++k)
stmt.addUInt32(i->second.m_creatureOrGOcount[k]);
for (int k = 0; k < QUEST_ITEM_OBJECTIVES_COUNT; ++k)
stmt.addUInt32(i->second.m_itemcount[k]);
stmt.Execute();
}
break;
case QUEST_CHANGED :
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updateQuestStatus, "UPDATE character_queststatus SET status = ?,rewarded = ?,explored = ?,timer = ?,"
"mobcount1 = ?,mobcount2 = ?,mobcount3 = ?,mobcount4 = ?,itemcount1 = ?,itemcount2 = ?,itemcount3 = ?,itemcount4 = ?,itemcount5 = ?,itemcount6 = ? WHERE guid = ? AND quest = ?");
stmt.addUInt8(i->second.m_status);
stmt.addUInt8(i->second.m_rewarded);
stmt.addUInt8(i->second.m_explored);
stmt.addUInt64(uint64(i->second.m_timer / IN_MILLISECONDS + sWorld.GetGameTime()));
for (int k = 0; k < QUEST_OBJECTIVES_COUNT; ++k)
stmt.addUInt32(i->second.m_creatureOrGOcount[k]);
for (int k = 0; k < QUEST_ITEM_OBJECTIVES_COUNT; ++k)
stmt.addUInt32(i->second.m_itemcount[k]);
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(i->first);
stmt.Execute();
}
break;
case QUEST_UNCHANGED:
break;
};
i->second.uState = QUEST_UNCHANGED;
}
}
void Player::_SaveDailyQuestStatus()
{
if (!m_DailyQuestChanged)
return;
// we don't need transactions here.
static SqlStatementID delQuestStatus ;
static SqlStatementID insQuestStatus ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(delQuestStatus, "DELETE FROM character_queststatus_daily WHERE guid = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insQuestStatus, "INSERT INTO character_queststatus_daily (guid,quest) VALUES (?, ?)");
stmtDel.PExecute(GetGUIDLow());
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
stmtIns.PExecute(GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx));
m_DailyQuestChanged = false;
}
void Player::_SaveWeeklyQuestStatus()
{
if (!m_WeeklyQuestChanged || m_weeklyquests.empty())
return;
// we don't need transactions here.
static SqlStatementID delQuestStatus ;
static SqlStatementID insQuestStatus ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(delQuestStatus, "DELETE FROM character_queststatus_weekly WHERE guid = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insQuestStatus, "INSERT INTO character_queststatus_weekly (guid,quest) VALUES (?, ?)");
stmtDel.PExecute(GetGUIDLow());
for (QuestSet::const_iterator iter = m_weeklyquests.begin(); iter != m_weeklyquests.end(); ++iter)
{
uint32 quest_id = *iter;
stmtIns.PExecute(GetGUIDLow(), quest_id);
}
m_WeeklyQuestChanged = false;
}
void Player::_SaveMonthlyQuestStatus()
{
if (!m_MonthlyQuestChanged || m_monthlyquests.empty())
return;
// we don't need transactions here.
static SqlStatementID deleteQuest ;
static SqlStatementID insertQuest ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(deleteQuest, "DELETE FROM character_queststatus_monthly WHERE guid = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insertQuest, "INSERT INTO character_queststatus_monthly (guid, quest) VALUES (?, ?)");
stmtDel.PExecute(GetGUIDLow());
for (QuestSet::const_iterator iter = m_monthlyquests.begin(); iter != m_monthlyquests.end(); ++iter)
{
uint32 quest_id = *iter;
stmtIns.PExecute(GetGUIDLow(), quest_id);
}
m_MonthlyQuestChanged = false;
}
void Player::_SaveSkills()
{
static SqlStatementID delSkills ;
static SqlStatementID insSkills ;
static SqlStatementID updSkills ;
// we don't need transactions here.
for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
{
if (itr->second.uState == SKILL_UNCHANGED)
{
++itr;
continue;
}
if (itr->second.uState == SKILL_DELETED)
{
SqlStatement stmt = CharacterDatabase.CreateStatement(delSkills, "DELETE FROM character_skills WHERE guid = ? AND skill = ?");
stmt.PExecute(GetGUIDLow(), itr->first );
mSkillStatus.erase(itr++);
continue;
}
uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
uint16 value = SKILL_VALUE(valueData);
uint16 max = SKILL_MAX(valueData);
switch (itr->second.uState)
{
case SKILL_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insSkills, "INSERT INTO character_skills (guid, skill, value, max) VALUES (?, ?, ?, ?)");
stmt.PExecute(GetGUIDLow(), itr->first, value, max);
}
break;
case SKILL_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updSkills, "UPDATE character_skills SET value = ?, max = ? WHERE guid = ? AND skill = ?");
stmt.PExecute(value, max, GetGUIDLow(), itr->first );
}
break;
case SKILL_UNCHANGED:
case SKILL_DELETED:
MANGOS_ASSERT(false);
break;
};
itr->second.uState = SKILL_UNCHANGED;
++itr;
}
}
void Player::_SaveSpells()
{
static SqlStatementID delSpells ;
static SqlStatementID insSpells ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(delSpells, "DELETE FROM character_spell WHERE guid = ? and spell = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insSpells, "INSERT INTO character_spell (guid,spell,active,disabled) VALUES (?, ?, ?, ?)");
for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
{
uint32 talentCosts = GetTalentSpellCost(itr->first);
if (!talentCosts)
{
if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED)
stmtDel.PExecute(GetGUIDLow(), itr->first);
// add only changed/new not dependent spells
if (!itr->second.dependent && (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED))
stmtIns.PExecute(GetGUIDLow(), itr->first, uint8(itr->second.active ? 1 : 0), uint8(itr->second.disabled ? 1 : 0));
}
if (itr->second.state == PLAYERSPELL_REMOVED)
m_spells.erase(itr++);
else
{
itr->second.state = PLAYERSPELL_UNCHANGED;
++itr;
}
}
}
void Player::_SaveTalents()
{
static SqlStatementID delTalents ;
static SqlStatementID insTalents ;
SqlStatement stmtDel = CharacterDatabase.CreateStatement(delTalents, "DELETE FROM character_talent WHERE guid = ? and talent_id = ? and spec = ?");
SqlStatement stmtIns = CharacterDatabase.CreateStatement(insTalents, "INSERT INTO character_talent (guid, talent_id, current_rank , spec) VALUES (?, ?, ?, ?)");
for (uint32 i = 0; i < MAX_TALENT_SPEC_COUNT; ++i)
{
for (PlayerTalentMap::iterator itr = m_talents[i].begin(); itr != m_talents[i].end();)
{
if (itr->second.state == PLAYERSPELL_REMOVED || itr->second.state == PLAYERSPELL_CHANGED)
stmtDel.PExecute(GetGUIDLow(),itr->first, i);
// add only changed/new talents
if (itr->second.state == PLAYERSPELL_NEW || itr->second.state == PLAYERSPELL_CHANGED)
stmtIns.PExecute(GetGUIDLow(), itr->first, itr->second.currentRank, i);
if (itr->second.state == PLAYERSPELL_REMOVED)
m_talents[i].erase(itr++);
else
{
itr->second.state = PLAYERSPELL_UNCHANGED;
++itr;
}
}
}
}
// save player stats -- only for external usage
// real stats will be recalculated on player login
void Player::_SaveStats()
{
// check if stat saving is enabled and if char level is high enough
if(!sWorld.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE) || getLevel() < sWorld.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE))
return;
static SqlStatementID delStats ;
static SqlStatementID insertStats ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delStats, "DELETE FROM character_stats WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
stmt = CharacterDatabase.CreateStatement(insertStats, "INSERT INTO character_stats (guid, maxhealth, maxpower1, maxpower2, maxpower3, maxpower4, maxpower5, maxpower6, maxpower7, "
"strength, agility, stamina, intellect, spirit, armor, resHoly, resFire, resNature, resFrost, resShadow, resArcane, "
"blockPct, dodgePct, parryPct, critPct, rangedCritPct, spellCritPct, attackPower, rangedAttackPower, spellPower, "
"apmelee, ranged, blockrating, defrating, dodgerating, parryrating, resilience, manaregen, "
"melee_hitrating, melee_critrating, melee_hasterating, melee_mainmindmg, melee_mainmaxdmg, "
"melee_offmindmg, melee_offmaxdmg, melee_maintime, melee_offtime, ranged_critrating, ranged_hasterating, "
"ranged_hitrating, ranged_mindmg, ranged_maxdmg, ranged_attacktime, "
"spell_hitrating, spell_critrating, spell_hasterating, spell_bonusdmg, spell_bonusheal, spell_critproc, account, name, race, class, gender, level, map, money, totaltime, online, arenaPoints, totalHonorPoints, totalKills, equipmentCache, specCount, activeSpec, data) "
"VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(GetMaxHealth());
for(int i = 0; i < MAX_POWERS; ++i)
stmt.addUInt32(GetMaxPower(Powers(i)));
for(int i = 0; i < MAX_STATS; ++i)
stmt.addFloat(GetStat(Stats(i)));
// armor + school resistances
for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
stmt.addUInt32(GetResistance(SpellSchools(i)));
stmt.addFloat(GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_DODGE_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_PARRY_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_CRIT_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE));
stmt.addFloat(GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1));
stmt.addUInt32(GetUInt32Value(UNIT_FIELD_ATTACK_POWER));
stmt.addUInt32(GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER));
stmt.addUInt32(GetBaseSpellPowerBonus());
stmt.addUInt32(GetUInt32Value(MANGOSR2_AP_MELEE_1)+GetUInt32Value(MANGOSR2_AP_MELEE_2));
stmt.addUInt32(GetUInt32Value(MANGOSR2_AP_RANGED_1)+GetUInt32Value(MANGOSR2_AP_RANGED_2));
stmt.addUInt32(GetUInt32Value(MANGOSR2_BLOCKRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_DEFRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_DODGERATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_PARRYRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_RESILIENCE));
stmt.addFloat(GetFloatValue(MANGOSR2_MANAREGEN));
stmt.addUInt32(GetUInt32Value(MANGOSR2_MELEE_HITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_MELEE_CRITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_MELEE_HASTERATING));
stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_MAINMINDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_MAINMAXDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_OFFMINDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_MELEE_OFFMAXDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_MELLE_MAINTIME));
stmt.addFloat(GetFloatValue(MANGOSR2_MELLE_OFFTIME));
stmt.addUInt32(GetUInt32Value(MANGOSR2_RANGED_CRITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_RANGED_HASTERATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_RANGED_HITRATING));
stmt.addFloat(GetFloatValue(MANGOSR2_RANGED_MINDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_RANGED_MAXDMG));
stmt.addFloat(GetFloatValue(MANGOSR2_RANGED_ATTACKTIME));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_HITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_CRITRATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_HASTERATING));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_BONUSDMG));
stmt.addUInt32(GetUInt32Value(MANGOSR2_SPELL_BONUSHEAL));
stmt.addFloat(GetFloatValue(MANGOSR2_SPELL_CRITPROC));
stmt.addUInt32(GetSession()->GetAccountId());
stmt.addString(m_name); // duh
stmt.addUInt32((uint32)getRace());
stmt.addUInt32((uint32)getClass());
stmt.addUInt32((uint32)getGender());
stmt.addUInt32(getLevel());
stmt.addUInt32(GetMapId());
stmt.addUInt32(GetMoney());
stmt.addUInt32(m_Played_time[PLAYED_TIME_TOTAL]);
stmt.addUInt32(IsInWorld() ? 1 : 0);
stmt.addUInt32(GetArenaPoints());
stmt.addUInt32(GetHonorPoints());
stmt.addUInt32(GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS));
std::ostringstream ss; // duh
for(uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i ) // EquipmentCache string
{
ss << GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + i) << " ";
}
stmt.addString(ss); // equipment cache string
stmt.addUInt32(uint32(m_specsCount));
stmt.addUInt32(uint32(m_activeSpec));
std::ostringstream ps; // duh
for(uint16 i = 0; i < m_valuesCount; ++i ) //data string
{
ps << GetUInt32Value(i) << " ";
}
stmt.addString(ps); //data string
stmt.Execute();
}
void Player::outDebugStatsValues() const
{
// optimize disabled debug output
if(!sLog.HasLogLevelOrHigher(LOG_LVL_DEBUG) || sLog.HasLogFilter(LOG_FILTER_PLAYER_STATS))
return;
sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
}
/*********************************************************/
/*** FLOOD FILTER SYSTEM ***/
/*********************************************************/
void Player::UpdateSpeakTime()
{
// ignore chat spam protection for GMs in any mode
if (GetSession()->GetSecurity() > SEC_PLAYER)
return;
time_t current = time (NULL);
if (m_speakTime > current)
{
uint32 max_count = sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT);
if(!max_count)
return;
++m_speakCount;
if (m_speakCount >= max_count)
{
// prevent overwrite mute time, if message send just before mutes set, for example.
time_t new_mute = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME);
if (GetSession()->m_muteTime < new_mute)
GetSession()->m_muteTime = new_mute;
m_speakCount = 0;
}
}
else
m_speakCount = 0;
m_speakTime = current + sWorld.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY);
}
bool Player::CanSpeak() const
{
return GetSession()->m_muteTime <= time (NULL);
}
/*********************************************************/
/*** LOW LEVEL FUNCTIONS:Notifiers ***/
/*********************************************************/
void Player::SendAttackSwingNotInRange()
{
WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
GetSession()->SendPacket( &data );
}
void Player::SavePositionInDB(ObjectGuid guid, uint32 mapid, float x, float y, float z, float o, uint32 zone)
{
std::ostringstream ss;
ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
<< "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
<< "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
<< "transguid='0',taxi_path='' WHERE guid='"<< guid.GetCounter() <<"'";
DEBUG_LOG("%s", ss.str().c_str());
CharacterDatabase.Execute(ss.str().c_str());
}
void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
{
char buf[11];
snprintf(buf,11,"%u",value);
if (index >= tokens.size())
return;
tokens[index] = buf;
}
void Player::Customize(ObjectGuid guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
{
// 0
QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", guid.GetCounter());
if (!result)
return;
Field* fields = result->Fetch();
uint32 player_bytes2 = fields[0].GetUInt32();
player_bytes2 &= ~0xFF;
player_bytes2 |= facialHair;
CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, guid.GetCounter());
delete result;
}
void Player::SendAttackSwingDeadTarget()
{
WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
GetSession()->SendPacket( &data );
}
void Player::SendAttackSwingCantAttack()
{
WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
GetSession()->SendPacket( &data );
}
void Player::SendAttackSwingCancelAttack()
{
WorldPacket data(SMSG_CANCEL_COMBAT, 0);
GetSession()->SendPacket( &data );
}
void Player::SendAttackSwingBadFacingAttack()
{
WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
GetSession()->SendPacket( &data );
}
void Player::SendAutoRepeatCancel(Unit *target)
{
WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
data << target->GetPackGUID();
GetSession()->SendPacket( &data );
}
void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
{
WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
data << uint32(Area);
data << uint32(Experience);
GetSession()->SendPacket(&data);
}
void Player::SendDungeonDifficulty(bool IsInGroup)
{
uint8 val = 0x00000001;
WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
data << uint32(GetDungeonDifficulty());
data << uint32(val);
data << uint32(IsInGroup);
GetSession()->SendPacket(&data);
}
void Player::SendRaidDifficulty(bool IsInGroup)
{
uint8 val = 0x00000001;
WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
data << uint32(GetRaidDifficulty());
data << uint32(val);
data << uint32(IsInGroup);
GetSession()->SendPacket(&data);
}
void Player::SendResetFailedNotify(uint32 mapid)
{
WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
data << uint32(mapid);
GetSession()->SendPacket(&data);
}
/// Reset all solo instances and optionally send a message on success for each
void Player::ResetInstances(InstanceResetMethod method, bool isRaid)
{
// method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
// we assume that when the difficulty changes, all instances that can be reset will be
Difficulty diff = GetDifficulty(isRaid);
for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
{
DungeonPersistentState *state = itr->second.state;
const MapEntry *entry = sMapStore.LookupEntry(itr->first);
if (!entry || entry->IsRaid() != isRaid || !state->CanReset())
{
++itr;
continue;
}
if (method == INSTANCE_RESET_ALL)
{
// the "reset all instances" method can only reset normal maps
if (entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
{
++itr;
continue;
}
}
// if the map is loaded, reset it
if (Map *map = sMapMgr.FindMap(state->GetMapId(), state->GetInstanceId()))
if (map->IsDungeon())
((DungeonMap*)map)->Reset(method);
// since this is a solo instance there should not be any players inside
if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
SendResetInstanceSuccess(state->GetMapId());
state->DeleteFromDB();
m_boundInstances[diff].erase(itr++);
// the following should remove the instance save from the manager and delete it as well
state->RemovePlayer(this);
}
}
void Player::SendResetInstanceSuccess(uint32 MapId)
{
WorldPacket data(SMSG_INSTANCE_RESET, 4);
data << uint32(MapId);
GetSession()->SendPacket(&data);
}
void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
{
// TODO: find what other fail reasons there are besides players in the instance
WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
data << uint32(reason);
data << uint32(MapId);
GetSession()->SendPacket(&data);
}
/*********************************************************/
/*** Update timers ***/
/*********************************************************/
///checks the 15 afk reports per 5 minutes limit
void Player::UpdateAfkReport(time_t currTime)
{
if (m_bgData.bgAfkReportedTimer <= currTime)
{
m_bgData.bgAfkReportedCount = 0;
m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
}
}
void Player::UpdateContestedPvP(uint32 diff)
{
if(!m_contestedPvPTimer||isInCombat())
return;
if (m_contestedPvPTimer <= diff)
{
ResetContestedPvP();
}
else
m_contestedPvPTimer -= diff;
}
void Player::UpdatePvPFlag(time_t currTime)
{
if(!IsPvP())
return;
if (pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
return;
UpdatePvP(false);
}
void Player::UpdateDuelFlag(time_t currTime)
{
if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
return;
SetUInt32Value(PLAYER_DUEL_TEAM, 1);
duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
duel->startTimer = 0;
duel->startTime = currTime;
duel->opponent->duel->startTimer = 0;
duel->opponent->duel->startTime = currTime;
}
void Player::RemovePet(PetSaveMode mode)
{
GroupPetList groupPets = GetPets();
if (!groupPets.empty())
{
for (GroupPetList::const_iterator itr = groupPets.begin(); itr != groupPets.end(); ++itr)
if (Pet* _pet = GetMap()->GetPet(*itr))
_pet->Unsummon(mode, this);
}
}
void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
{
*data << uint8(msgtype);
*data << uint32(language);
*data << ObjectGuid(GetObjectGuid());
*data << uint32(language); //language 2.1.0 ?
*data << ObjectGuid(GetObjectGuid());
*data << uint32(text.length()+1);
*data << text;
*data << uint8(chatTag());
}
void Player::Say(const std::string& text, const uint32 language)
{
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY),true);
}
void Player::Yell(const std::string& text, const uint32 language)
{
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL),true);
}
void Player::TextEmote(const std::string& text)
{
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
}
void Player::Whisper(const std::string& text, uint32 language, ObjectGuid receiver)
{
if (language != LANG_ADDON) // if not addon data
language = LANG_UNIVERSAL; // whispers should always be readable
Player *rPlayer = sObjectMgr.GetPlayer(receiver);
WorldPacket data(SMSG_MESSAGECHAT, 200);
BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
rPlayer->GetSession()->SendPacket(&data);
// not send confirmation for addon messages
if (language != LANG_ADDON)
{
data.Initialize(SMSG_MESSAGECHAT, 200);
rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
GetSession()->SendPacket(&data);
}
if (!isAcceptWhispers())
{
SetAcceptWhispers(true);
ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
}
// announce afk or dnd message
if (rPlayer->isAFK())
ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->autoReplyMsg.c_str());
else if (rPlayer->isDND())
ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->autoReplyMsg.c_str());
}
void Player::PetSpellInitialize()
{
Pet* pet = GetPet();
if(!pet)
return;
DEBUG_LOG("Pet Spells Groups");
CharmInfo *charmInfo = pet->GetCharmInfo();
if (!charmInfo)
return;
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
data << pet->GetObjectGuid();
data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
data << uint32(0);
data << uint32(charmInfo->GetState());
// action bar loop
charmInfo->BuildActionBar(&data);
size_t spellsCountPos = data.wpos();
// spells count
uint8 addlist = 0;
data << uint8(addlist); // placeholder
if (pet->IsPermanentPetFor(this))
{
// spells loop
for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
{
if (itr->second.state == PETSPELL_REMOVED)
continue;
data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
++addlist;
}
}
data.put<uint8>(spellsCountPos, addlist);
uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
data << uint8(cooldownsCount);
time_t curTime = time(NULL);
for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
{
time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spellid
data << uint16(0); // spell category?
data << uint32(cooldown); // cooldown
data << uint32(0); // category cooldown
}
for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
{
time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spellid
data << uint16(0); // spell category?
data << uint32(0); // cooldown
data << uint32(cooldown); // category cooldown
}
GetSession()->SendPacket(&data);
}
void Player::SendPetGUIDs()
{
GroupPetList m_groupPets = GetPets();
WorldPacket data(SMSG_PET_GUIDS, 4+8*m_groupPets.size());
data << uint32(m_groupPets.size()); // count
if (!m_groupPets.empty())
{
for (GroupPetList::const_iterator itr = m_groupPets.begin(); itr != m_groupPets.end(); ++itr)
data << (*itr);
}
GetSession()->SendPacket(&data);
}
void Player::PossessSpellInitialize()
{
Unit* charm = GetCharm();
if(!charm)
return;
CharmInfo *charmInfo = charm->GetCharmInfo();
if(!charmInfo)
{
sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
return;
}
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
data << charm->GetObjectGuid();
data << uint16(charm->GetObjectGuid().IsAnyTypeCreature() ? ((Creature*)charm)->GetCreatureInfo()->family : 0);
data << uint32(0);
data << uint32(charmInfo->GetState());
charmInfo->BuildActionBar(&data);
data << uint8(0); // spells count
data << uint8(0); // cooldowns count
GetSession()->SendPacket(&data);
}
void Player::VehicleSpellInitialize()
{
Creature* charm = (Creature*)GetCharm();
if (!charm)
return;
CharmInfo *charmInfo = charm->GetCharmInfo();
if (!charmInfo)
{
sLog.outError("Player::VehicleSpellInitialize(): vehicle (GUID: %u) has no charminfo!", charm->GetGUIDLow());
return;
}
size_t cooldownsCount = charm->m_CreatureSpellCooldowns.size() + charm->m_CreatureCategoryCooldowns.size();
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1+cooldownsCount*(4+2+4+4));
data << charm->GetObjectGuid();
data << uint16(((Creature*)charm)->GetCreatureInfo()->family);
data << uint32(0);
data << uint32(charmInfo->GetState());
charmInfo->BuildActionBar(&data);
data << uint8(0); // additional spells count
data << uint8(cooldownsCount);
time_t curTime = time(NULL);
for (CreatureSpellCooldowns::const_iterator itr = charm->m_CreatureSpellCooldowns.begin(); itr != charm->m_CreatureSpellCooldowns.end(); ++itr)
{
time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spellid
data << uint16(0); // spell category?
data << uint32(cooldown); // cooldown
data << uint32(0); // category cooldown
}
for (CreatureSpellCooldowns::const_iterator itr = charm->m_CreatureCategoryCooldowns.begin(); itr != charm->m_CreatureCategoryCooldowns.end(); ++itr)
{
time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILLISECONDS : 0;
data << uint32(itr->first); // spellid
data << uint16(0); // spell category?
data << uint32(0); // cooldown
data << uint32(cooldown); // category cooldown
}
GetSession()->SendPacket(&data);
}
void Player::CharmSpellInitialize()
{
Unit* charm = GetCharm();
if(!charm)
return;
CharmInfo *charmInfo = charm->GetCharmInfo();
if(!charmInfo)
{
sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
return;
}
uint8 addlist = 0;
if (charm->GetTypeId() != TYPEID_PLAYER)
{
CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
if (cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
{
for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
{
if (charmInfo->GetCharmSpell(i)->GetAction())
++addlist;
}
}
}
WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
data << charm->GetObjectGuid();
data << uint16(charm->GetObjectGuid().IsAnyTypeCreature() ? ((Creature*)charm)->GetCreatureInfo()->family : 0);
data << uint32(0);
data << uint32(charmInfo->GetState());
charmInfo->BuildActionBar(&data);
data << uint8(addlist);
if (addlist)
{
for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
{
CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
if (cspell->GetAction())
data << uint32(cspell->packedData);
}
}
data << uint8(0); // cooldowns count
GetSession()->SendPacket(&data);
}
void Player::RemovePetActionBar()
{
WorldPacket data(SMSG_PET_SPELLS, 8);
data << ObjectGuid();
SendDirectMessage(&data);
}
void Player::AddSpellMod(Aura* aura, bool apply)
{
Modifier const* mod = aura->GetModifier();
uint16 Opcode= (mod->m_auraname == SPELL_AURA_ADD_FLAT_MODIFIER) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
for(int eff = 0; eff < 96; ++eff)
{
if (aura->GetAuraSpellClassMask().test(eff))
{
int32 val = 0;
for (AuraList::const_iterator itr = m_spellMods[mod->m_miscvalue].begin(); itr != m_spellMods[mod->m_miscvalue].end(); ++itr)
{
if ((*itr)->GetModifier()->m_auraname == mod->m_auraname && ((*itr)->GetAuraSpellClassMask().test(eff)))
val += (*itr)->GetModifier()->m_amount;
}
val += apply ? mod->m_amount : -(mod->m_amount);
WorldPacket data(Opcode, (1+1+4));
data << uint8(eff);
data << uint8(mod->m_miscvalue);
data << int32(val);
SendDirectMessage(&data);
}
}
if (apply)
m_spellMods[mod->m_miscvalue].push_back(aura);
else
m_spellMods[mod->m_miscvalue].remove(aura);
}
template <class T> T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &basevalue, Spell const* spell)
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spellId);
if (!spellInfo)
return 0;
int32 totalpct = 0;
int32 totalflat = 0;
for (AuraList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
{
Aura *aura = *itr;
Modifier const* mod = aura->GetModifier();
if (!aura->isAffectedOnSpell(spellInfo))
continue;
if (mod->m_auraname == SPELL_AURA_ADD_FLAT_MODIFIER)
totalflat += mod->m_amount;
else
{
// skip percent mods for null basevalue (most important for spell mods with charges )
if (basevalue == T(0))
continue;
// special case (skip >10sec spell casts for instant cast setting)
if (mod->m_miscvalue == SPELLMOD_CASTING_TIME
&& basevalue >= T(10*IN_MILLISECONDS) && mod->m_amount <= -100)
continue;
totalpct += mod->m_amount;
}
}
float diff = (float)basevalue*(float)totalpct/100.0f + (float)totalflat;
basevalue = T((float)basevalue + diff);
return T(diff);
}
template int32 Player::ApplySpellMod<int32>(uint32 spellId, SpellModOp op, int32 &basevalue, Spell const* spell);
template uint32 Player::ApplySpellMod<uint32>(uint32 spellId, SpellModOp op, uint32 &basevalue, Spell const* spell);
template float Player::ApplySpellMod<float>(uint32 spellId, SpellModOp op, float &basevalue, Spell const* spell);
// send Proficiency
void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask)
{
WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4);
data << uint8(itemClass) << uint32(itemSubclassMask);
GetSession()->SendPacket (&data);
}
void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type)
{
uint32 lowguid = guid.GetCounter();
QueryResult *result = NULL;
if (type == 10)
result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", lowguid);
else
result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", lowguid, type);
if (result)
{
do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
{ // and SendPetitionQueryOpcode reads data from the DB
Field *fields = result->Fetch();
ObjectGuid ownerguid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32());
ObjectGuid petitionguid = ObjectGuid(HIGHGUID_ITEM, fields[1].GetUInt32());
// send update if charter owner in game
Player* owner = sObjectMgr.GetPlayer(ownerguid);
if (owner)
owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
} while ( result->NextRow() );
delete result;
if (type==10)
CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", lowguid);
else
CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", lowguid, type);
}
CharacterDatabase.BeginTransaction();
if (type == 10)
{
CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", lowguid);
CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", lowguid);
}
else
{
CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", lowguid, type);
CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", lowguid, type);
}
CharacterDatabase.CommitTransaction();
}
void Player::LeaveAllArenaTeams(ObjectGuid guid)
{
uint32 lowguid = guid.GetCounter();
QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", lowguid);
if (!result)
return;
do
{
Field *fields = result->Fetch();
if (uint32 at_id = fields[0].GetUInt32())
if (ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id))
at->DelMember(guid);
} while (result->NextRow());
delete result;
}
void Player::SetRestBonus (float rest_bonus_new)
{
// Prevent resting on max level
if (getLevel() >= sWorld.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL))
rest_bonus_new = 0;
if (rest_bonus_new < 0)
rest_bonus_new = 0;
float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5f/2.0f;
if (rest_bonus_new > rest_bonus_max)
m_rest_bonus = rest_bonus_max;
else
m_rest_bonus = rest_bonus_new;
// update data for client
if (GetAccountLinkedState() != STATE_NOT_LINKED)
SetByteValue(PLAYER_BYTES_2, 3, 0x06); // Set Reststate = Refer-A-Friend
else
{
if (m_rest_bonus>10)
SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
else if (m_rest_bonus<=1)
SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
}
//RestTickUpdate
SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
}
void Player::HandleStealthedUnitsDetection()
{
std::list<Unit*> stealthedUnits;
MaNGOS::AnyStealthedCheck u_check(this);
MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
Cell::VisitAllObjects(this, searcher, MAX_PLAYER_STEALTH_DETECT_RANGE);
WorldObject const* viewPoint = GetCamera().GetBody();
for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
{
if((*i)==this)
continue;
bool hasAtClient = HaveAtClient((*i));
bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
if (hasDetected)
{
if(!hasAtClient)
{
ObjectGuid i_guid = (*i)->GetObjectGuid();
(*i)->SendCreateUpdateToPlayer(this);
m_clientGUIDs.insert(i_guid);
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is detected in stealth by player %u. Distance = %f",i_guid.GetString().c_str(),GetGUIDLow(),GetDistance(*i));
// target aura duration for caster show only if target exist at caster client
// send data at target visibility change (adding to client)
if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
SendAurasForTarget(*i);
}
}
else
{
if (hasAtClient)
{
(*i)->DestroyForPlayer(this);
m_clientGUIDs.erase((*i)->GetObjectGuid());
}
}
}
}
bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
{
if (nodes.size() < 2)
return false;
// not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
if (GetSession()->isLogingOut() || isInCombat())
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIPLAYERBUSY);
GetSession()->SendPacket(&data);
return false;
}
if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
return false;
// taximaster case
if (npc)
{
// not let cheating with start flight mounted
if (IsMounted() || GetVehicle())
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
GetSession()->SendPacket(&data);
return false;
}
if (IsInDisallowedMountForm())
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
GetSession()->SendPacket(&data);
return false;
}
// not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
if (IsNonMeleeSpellCasted(false))
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIPLAYERBUSY);
GetSession()->SendPacket(&data);
return false;
}
}
// cast case or scripted call case
else
{
RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
ExitVehicle();
if (IsInDisallowedMountForm())
RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
if (spell->m_spellInfo->Id != spellid)
InterruptSpell(CURRENT_GENERIC_SPELL,false);
InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
if (spell->m_spellInfo->Id != spellid)
InterruptSpell(CURRENT_CHANNELED_SPELL,true);
}
uint32 sourcenode = nodes[0];
// starting node too far away (cheat?)
TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
if (!node)
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXINOSUCHPATH);
GetSession()->SendPacket(&data);
return false;
}
// check node starting pos data set case if provided
if (fabs(node->x) > M_NULL_F || fabs(node->y) > M_NULL_F || fabs(node->z) > M_NULL_F)
{
if (node->map_id != GetMapId() ||
(node->x - GetPositionX())*(node->x - GetPositionX())+
(node->y - GetPositionY())*(node->y - GetPositionY())+
(node->z - GetPositionZ())*(node->z - GetPositionZ()) >
(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXITOOFARAWAY);
GetSession()->SendPacket(&data);
return false;
}
}
// node must have pos if taxi master case (npc != NULL)
else if (npc)
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
GetSession()->SendPacket(&data);
return false;
}
// Prepare to flight start now
// stop combat at start taxi flight if any
CombatStop();
// stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
TradeCancel(true);
// clean not finished taxi path if any
m_taxi.ClearTaxiDestinations();
// 0 element current node
m_taxi.AddTaxiDestination(sourcenode);
// fill destinations path tail
uint32 sourcepath = 0;
uint32 totalcost = 0;
uint32 prevnode = sourcenode;
uint32 lastnode = 0;
for(uint32 i = 1; i < nodes.size(); ++i)
{
uint32 path, cost;
lastnode = nodes[i];
sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost);
if(!path)
{
m_taxi.ClearTaxiDestinations();
return false;
}
totalcost += cost;
if (prevnode == sourcenode)
sourcepath = path;
m_taxi.AddTaxiDestination(lastnode);
prevnode = lastnode;
}
// get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
// in spell case allow 0 model
if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
GetSession()->SendPacket(&data);
m_taxi.ClearTaxiDestinations();
return false;
}
uint32 money = GetMoney();
if (npc)
totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
if (money < totalcost)
{
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXINOTENOUGHMONEY);
GetSession()->SendPacket(&data);
m_taxi.ClearTaxiDestinations();
return false;
}
//Checks and preparations done, DO FLIGHT
ModifyMoney(-(int32)totalcost);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
// prevent stealth flight
RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
data << uint32(ERR_TAXIOK);
GetSession()->SendPacket(&data);
DEBUG_LOG("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
GetSession()->SendDoFlight(mount_display_id, sourcepath);
return true;
}
bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
{
TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
if(!entry)
return false;
std::vector<uint32> nodes;
nodes.resize(2);
nodes[0] = entry->from;
nodes[1] = entry->to;
return ActivateTaxiPathTo(nodes,NULL,spellid);
}
void Player::ContinueTaxiFlight()
{
uint32 sourceNode = m_taxi.GetTaxiSource();
if (!sourceNode)
return;
DEBUG_LOG( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(), true);
uint32 path = m_taxi.GetCurrentTaxiPath();
// search appropriate start path node
uint32 startNode = 0;
TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
float distPrev = MAP_SIZE*MAP_SIZE;
float distNext =
(nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
(nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
(nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
for(uint32 i = 1; i < nodeList.size(); ++i)
{
TaxiPathNodeEntry const& node = nodeList[i];
TaxiPathNodeEntry const& prevNode = nodeList[i-1];
// skip nodes at another map
if (node.mapid != GetMapId())
continue;
distPrev = distNext;
distNext =
(node.x-GetPositionX())*(node.x-GetPositionX())+
(node.y-GetPositionY())*(node.y-GetPositionY())+
(node.z-GetPositionZ())*(node.z-GetPositionZ());
float distNodes =
(node.x-prevNode.x)*(node.x-prevNode.x)+
(node.y-prevNode.y)*(node.y-prevNode.y)+
(node.z-prevNode.z)*(node.z-prevNode.z);
if (distNext + distPrev < distNodes)
{
startNode = i;
break;
}
}
GetSession()->SendDoFlight(mountDisplayId, path, startNode);
}
void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
{
// last check 2.0.10
WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
data << GetObjectGuid();
data << uint8(0x0); // flags (0x1, 0x2)
time_t curTime = time(NULL);
for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED)
continue;
uint32 unSpellId = itr->first;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
if (!spellInfo)
{
MANGOS_ASSERT(spellInfo);
continue;
}
// Not send cooldown for this spells
if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
continue;
if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
{
data << uint32(unSpellId);
data << uint32(unTimeMs); // in m.secs
AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILLISECONDS);
}
}
GetSession()->SendPacket(&data);
}
void Player::SendModifyCooldown( uint32 spell_id, int32 delta)
{
SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id);
if (!spellInfo)
return;
uint32 cooldown = GetSpellCooldownDelay(spell_id);
if (cooldown == 0 && delta < 0)
return;
int32 result = int32(cooldown * IN_MILLISECONDS + delta);
if (result < 0)
result = 0;
AddSpellCooldown(spell_id, 0, uint32(time(NULL) + int32(result / IN_MILLISECONDS)));
WorldPacket data(SMSG_MODIFY_COOLDOWN, 4 + 8 + 4);
data << uint32(spell_id);
data << GetObjectGuid();
data << int32(result > 0 ? delta : result - cooldown * IN_MILLISECONDS);
GetSession()->SendPacket(&data);
}
void Player::InitDataForForm(bool reapplyMods)
{
ShapeshiftForm form = GetShapeshiftForm();
SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form);
if (ssEntry && ssEntry->attackSpeed)
{
SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
}
else
SetRegularAttackTime();
switch(form)
{
case FORM_CAT:
{
if (getPowerType()!=POWER_ENERGY)
setPowerType(POWER_ENERGY);
break;
}
case FORM_BEAR:
case FORM_DIREBEAR:
{
if (getPowerType()!=POWER_RAGE)
setPowerType(POWER_RAGE);
break;
}
default: // 0, for example
{
ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
if (cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
setPowerType(Powers(cEntry->powerType));
break;
}
}
// update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
if (!reapplyMods)
UpdateEquipSpellsAtFormChange();
UpdateAttackPowerAndDamage();
UpdateAttackPowerAndDamage(true);
}
void Player::InitDisplayIds()
{
PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
if(!info)
{
sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
return;
}
// reset scale before reapply auras
SetObjectScale(DEFAULT_OBJECT_SCALE);
uint8 gender = getGender();
switch(gender)
{
case GENDER_FEMALE:
SetDisplayId(info->displayId_f );
SetNativeDisplayId(info->displayId_f );
break;
case GENDER_MALE:
SetDisplayId(info->displayId_m );
SetNativeDisplayId(info->displayId_m );
break;
default:
sLog.outError("Invalid gender %u for player",gender);
return;
}
}
void Player::TakeExtendedCost(uint32 extendedCostId, uint32 count)
{
ItemExtendedCostEntry const* extendedCost = sItemExtendedCostStore.LookupEntry(extendedCostId);
if (extendedCost->reqhonorpoints)
ModifyHonorPoints(-int32(extendedCost->reqhonorpoints * count));
if (extendedCost->reqarenapoints)
ModifyArenaPoints(-int32(extendedCost->reqarenapoints * count));
for (uint8 i = 0; i < MAX_EXTENDED_COST_ITEMS; ++i)
{
if (extendedCost->reqitem[i])
DestroyItemCount(extendedCost->reqitem[i], extendedCost->reqitemcount[i] * count, true);
}
}
// Return true is the bought item has a max count to force refresh of window by caller
bool Player::BuyItemFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot)
{
// cheating attempt
if (count < 1) count = 1;
if (!isAlive())
return false;
ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
if (!pProto)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
return false;
}
Creature *pCreature = GetNPCIfCanInteractWith(vendorGuid, UNIT_NPC_FLAG_VENDOR);
if (!pCreature)
{
DEBUG_LOG("WORLD: BuyItemFromVendor - %s not found or you can't interact with him.", vendorGuid.GetString().c_str());
SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
return false;
}
VendorItemData const* vItems = pCreature->GetVendorItems();
VendorItemData const* tItems = pCreature->GetVendorTemplateItems();
if ((!vItems || vItems->Empty()) && (!tItems || tItems->Empty()))
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
return false;
}
uint32 vCount = vItems ? vItems->GetItemCount() : 0;
uint32 tCount = tItems ? tItems->GetItemCount() : 0;
if (vendorslot >= vCount+tCount)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
return false;
}
VendorItem const* crItem = vendorslot < vCount ? vItems->GetItem(vendorslot) : tItems->GetItem(vendorslot - vCount);
if (!crItem) // store diff item (cheating)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
return false;
}
if (crItem->item != item) // store diff item (cheating or special convert)
{
bool converted = false;
// possible item converted for BoA case
ItemPrototype const* crProto = ObjectMgr::GetItemPrototype(crItem->item);
if (crProto->Flags & ITEM_FLAG_BOA && crProto->RequiredReputationFaction &&
uint32(GetReputationRank(crProto->RequiredReputationFaction)) >= crProto->RequiredReputationRank)
converted = (sObjectMgr.GetItemConvert(crItem->item, getRaceMask()) != 0);
if (!converted)
{
SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
return false;
}
}
uint32 totalCount = pProto->BuyCount * count;
// check current item amount if it limited
if (crItem->maxcount != 0)
{
if (pCreature->GetVendorItemCurrentCount(crItem) < totalCount)
{
SendBuyError(BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
return false;
}
}
if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
{
SendBuyError(BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
return false;
}
if (uint32 extendedCostId = crItem->ExtendedCost)
{
ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(extendedCostId);
if (!iece)
{
sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, extendedCostId);
return false;
}
// honor points price
if (GetHonorPoints() < (iece->reqhonorpoints * count))
{
SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
return false;
}
// arena points price
if (GetArenaPoints() < (iece->reqarenapoints * count))
{
SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
return false;
}
// item base price
for (uint8 i = 0; i < MAX_EXTENDED_COST_ITEMS; ++i)
{
if (iece->reqitem[i] && !HasItemCount(iece->reqitem[i], iece->reqitemcount[i] * count))
{
SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
return false;
}
}
// check for personal arena rating requirement
if (GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating)
{
// probably not the proper equip err
SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, NULL, NULL);
return false;
}
}
uint32 price = (crItem->ExtendedCost == 0 || pProto->Flags2 & ITEM_FLAG2_EXT_COST_REQUIRES_GOLD) ? pProto->BuyPrice * count : 0;
// reputation discount
if (price)
price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
if (GetMoney() < price)
{
SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
return false;
}
Item* pItem = NULL;
if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
{
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(bag, slot, dest, item, totalCount);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, NULL, NULL, item);
return false;
}
ModifyMoney(-int32(price));
if (crItem->ExtendedCost)
TakeExtendedCost(crItem->ExtendedCost, count);
pItem = StoreNewItem(dest, item, true);
}
else if (IsEquipmentPos(bag, slot))
{
if (totalCount != 1)
{
SendEquipError(EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL);
return false;
}
uint16 dest;
InventoryResult msg = CanEquipNewItem(slot, dest, item, false);
if (msg != EQUIP_ERR_OK)
{
SendEquipError(msg, NULL, NULL, item);
return false;
}
ModifyMoney(-int32(price));
if (crItem->ExtendedCost)
TakeExtendedCost(crItem->ExtendedCost, count);
pItem = EquipNewItem(dest, item, true);
if (pItem)
AutoUnequipOffhandIfNeed();
}
else
{
SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL);
return false;
}
if (!pItem)
return false;
uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem, totalCount);
WorldPacket data(SMSG_BUY_ITEM, 8+4+4+4);
data << pCreature->GetObjectGuid();
data << uint32(vendorslot + 1); // numbered from 1 at client
data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
data << uint32(count);
GetSession()->SendPacket(&data);
SendNewItem(pItem, totalCount, true, false, false);
return crItem->maxcount != 0;
}
uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot)
{
// returns the maximal personal arena rating that can be used to purchase items requiring this condition
// the personal rating of the arena team must match the required limit as well
// so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
uint32 max_personal_rating = 0;
for(int i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
{
if (ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i)))
{
uint32 p_rating = GetArenaPersonalRating(i);
uint32 t_rating = at->GetRating();
p_rating = p_rating < t_rating ? p_rating : t_rating;
if (max_personal_rating < p_rating)
max_personal_rating = p_rating;
}
}
return max_personal_rating;
}
void Player::UpdateHomebindTime(uint32 time)
{
// GMs never get homebind timer online
if (m_InstanceValid || isGameMaster())
{
if (m_HomebindTimer) // instance valid, but timer not reset
{
// hide reminder
WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
data << uint32(0);
data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
GetSession()->SendPacket(&data);
}
// instance is valid, reset homebind timer
m_HomebindTimer = 0;
}
else if (m_HomebindTimer > 0)
{
if (time >= m_HomebindTimer)
{
// teleport to nearest graveyard
RepopAtGraveyard();
}
else
m_HomebindTimer -= time;
}
else
{
// instance is invalid, start homebind timer
m_HomebindTimer = 15000;
// send message to player
WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
data << uint32(m_HomebindTimer);
data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
GetSession()->SendPacket(&data);
DEBUG_LOG("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
}
}
void Player::UpdatePvP(bool state, bool ovrride)
{
if(!state || ovrride)
{
SetPvP(state);
pvpInfo.endTimer = 0;
}
else
{
if (pvpInfo.endTimer != 0)
pvpInfo.endTimer = time(NULL);
else
SetPvP(state);
}
}
void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
{
// init cooldown values
uint32 cat = 0;
int32 rec = -1;
int32 catrec = -1;
// some special item spells without correct cooldown in SpellInfo
// cooldown information stored in item prototype
// This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
if (itemId)
{
if (ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
{
for(int idx = 0; idx < 5; ++idx)
{
if (proto->Spells[idx].SpellId == spellInfo->Id)
{
cat = proto->Spells[idx].SpellCategory;
rec = proto->Spells[idx].SpellCooldown;
catrec = proto->Spells[idx].SpellCategoryCooldown;
break;
}
}
}
}
// if no cooldown found above then base at DBC data
if (rec < 0 && catrec < 0)
{
cat = spellInfo->Category;
rec = spellInfo->RecoveryTime;
catrec = spellInfo->CategoryRecoveryTime;
}
time_t curTime = time(NULL);
time_t catrecTime;
time_t recTime;
// overwrite time for selected category
if (infinityCooldown)
{
// use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
// but not allow ignore until reset or re-login
catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
}
else
{
// shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
// prevent 0 cooldowns set by another way
if (rec <= 0 && catrec <= 0 && (cat == 76 || (IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT)))
rec = GetAttackTime(RANGED_ATTACK);
// Now we have cooldown data (if found any), time to apply mods
if (rec > 0)
ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
if (catrec > 0)
ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
// replace negative cooldowns by 0
if (rec < 0) rec = 0;
if (catrec < 0) catrec = 0;
// no cooldown after applying spell mods
if (rec == 0 && catrec == 0)
return;
catrecTime = catrec ? curTime+catrec/IN_MILLISECONDS : 0;
recTime = rec ? curTime+rec/IN_MILLISECONDS : catrecTime;
}
// self spell cooldown
if (recTime > 0)
AddSpellCooldown(spellInfo->Id, itemId, recTime);
// category spells
if (cat && catrec > 0)
{
SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
if (i_scstore != sSpellCategoryStore.end())
{
for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
{
if (*i_scset == spellInfo->Id) // skip main spell, already handled above
continue;
AddSpellCooldown(*i_scset, itemId, catrecTime);
}
}
}
}
void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
{
SpellCooldown sc;
sc.end = end_time;
sc.itemid = itemid;
MAPLOCK_WRITE(this, MAP_LOCK_TYPE_DEFAULT);
m_spellCooldowns[spellid] = sc;
}
void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
{
// start cooldowns at server side, if any
AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
// Send activate cooldown timer (possible 0) at client side
WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
data << uint32(spellInfo->Id);
data << GetObjectGuid();
SendDirectMessage(&data);
}
void Player::UpdatePotionCooldown(Spell* spell)
{
// no potion used in combat or still in combat
if(!m_lastPotionId || isInCombat())
return;
// Call not from spell cast, send cooldown event for item spells if no in combat
if(!spell)
{
// spell/item pair let set proper cooldown (except nonexistent charged spell cooldown spellmods for potions)
if (ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
for(int idx = 0; idx < 5; ++idx)
if (proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
if (SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
SendCooldownEvent(spellInfo,m_lastPotionId);
}
// from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
else
SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
m_lastPotionId = 0;
}
//slot to be excluded while counting
bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
{
if(!enchantmentcondition)
return true;
SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
if(!Condition)
return true;
uint8 curcount[4] = {0, 0, 0, 0};
//counting current equipped gem colors
for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i == slot)
continue;
Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
if (pItem2 && !pItem2->IsBroken() && pItem2->GetProto()->Socket[0].Color)
{
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
uint32 gemid = enchantEntry->GemID;
if(!gemid)
continue;
ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
if(!gemProto)
continue;
GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
if(!gemProperty)
continue;
uint8 GemColor = gemProperty->color;
for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
{
if (tmpcolormask & GemColor)
++curcount[b];
}
}
}
}
bool activate = true;
for(int i = 0; i < 5; ++i)
{
if(!Condition->Color[i])
continue;
uint32 _cur_gem = curcount[Condition->Color[i] - 1];
// if have <CompareColor> use them as count, else use <value> from Condition
uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
switch(Condition->Comparator[i])
{
case 2: // requires less <color> than (<value> || <comparecolor>) gems
activate &= (_cur_gem < _cmp_gem) ? true : false;
break;
case 3: // requires more <color> than (<value> || <comparecolor>) gems
activate &= (_cur_gem > _cmp_gem) ? true : false;
break;
case 5: // requires at least <color> than (<value> || <comparecolor>) gems
activate &= (_cur_gem >= _cmp_gem) ? true : false;
break;
}
}
DEBUG_LOG("Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no");
return activate;
}
void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
{
//cycle all equipped items
for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
//enchants for the slot being socketed are handled by Player::ApplyItemMods
if (slot == exceptslot)
continue;
Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
if(!pItem || !pItem->GetProto()->Socket[0].Color)
continue;
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
uint32 condition = enchantEntry->EnchantmentCondition;
if (condition)
{
//was enchant active with/without item?
bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
//should it now be?
if (wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
{
// ignore item gem conditions
//if state changed, (dis)apply enchant
ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
}
}
}
}
}
//if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
{
//cycle all equipped items
for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
{
//enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
if (slot == exceptslot)
continue;
Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
continue;
//cycle all (gem)enchants
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id) //if no enchant go to next enchant(slot)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
//only metagems to be (de)activated, so only enchants with condition
uint32 condition = enchantEntry->EnchantmentCondition;
if (condition)
ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
}
}
}
void Player::SetBattleGroundEntryPoint(bool forLFG)
{
m_bgData.forLFG = forLFG;
// Taxi path store
if (!m_taxi.empty())
{
m_bgData.mountSpell = 0;
m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
// On taxi we don't need check for dungeon
m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
m_bgData.m_needSave = true;
return;
}
else
{
m_bgData.ClearTaxiPath();
// Mount spell id storing
if (IsMounted())
{
AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
if (!auras.empty())
m_bgData.mountSpell = (*auras.begin())->GetId();
}
else
m_bgData.mountSpell = 0;
// If map is dungeon find linked graveyard
if (GetMap()->IsDungeon())
{
if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
{
m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
m_bgData.m_needSave = true;
return;
}
else
sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
}
// If new entry point is not BG or arena set it
else if (!GetMap()->IsBattleGroundOrArena())
{
m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
m_bgData.m_needSave = true;
return;
}
}
// In error cases use homebind position
m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
m_bgData.m_needSave = true;
}
void Player::LeaveBattleground(bool teleportToEntryPoint)
{
if (BattleGround *bg = GetBattleGround())
{
bg->RemovePlayerAtLeave(GetObjectGuid(), teleportToEntryPoint, true);
// call after remove to be sure that player resurrected for correct cast
if ( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER) )
{
if ( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
{
//lets check if player was teleported from BG and schedule delayed Deserter spell cast
if (IsBeingTeleportedFar())
{
ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
return;
}
CastSpell(this, 26013, true); // Deserter
}
}
// Prevent more execute BG update codes
if (bg->isBattleGround() && bg->GetStatus() == STATUS_IN_PROGRESS && !bg->GetPlayersSize())
bg->SetStatus(STATUS_WAIT_LEAVE);
}
}
bool Player::CanJoinToBattleground() const
{
// check Deserter debuff
if (GetDummyAura(26013))
return false;
return true;
}
bool Player::CanReportAfkDueToLimit()
{
// a player can complain about 15 people per 5 minutes
if (m_bgData.bgAfkReportedCount++ >= 15)
return false;
return true;
}
///This player has been blamed to be inactive in a battleground
void Player::ReportedAfkBy(Player* reporter)
{
BattleGround* bg = GetBattleGround();
// Battleground also must be in progress!
if (!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam() || bg->GetStatus() != STATUS_IN_PROGRESS)
return;
// check if player has 'Idle' or 'Inactive' debuff
if (m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, EFFECT_INDEX_0) && !HasAura(43681, EFFECT_INDEX_0) && reporter->CanReportAfkDueToLimit())
{
m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
// 3 players have to complain to apply debuff
if (m_bgData.bgAfkReporter.size() >= 3)
{
// cast 'Idle' spell
CastSpell(this, 43680, true);
m_bgData.bgAfkReporter.clear();
}
}
}
bool Player::IsVisibleInGridForPlayer( Player* pl ) const
{
// gamemaster in GM mode see all, including ghosts
if (pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
return true;
// player see dead player/ghost from own group/raid
if (IsInSameRaidWith(pl))
return true;
// Live player see live player or dead player with not realized corpse
if (pl->isAlive() || pl->m_deathTimer > 0)
return isAlive() || m_deathTimer > 0;
// Ghost see other friendly ghosts, that's for sure
if (!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
return true;
// Dead player see live players near own corpse
if (isAlive())
{
if (Corpse *corpse = pl->GetCorpse())
{
// 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
if (corpse->IsWithinDistInMap(this, (20 + 25) * sWorld.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO)))
return true;
}
}
// and not see any other
return false;
}
bool Player::IsVisibleGloballyFor( Player* u ) const
{
if (!u)
return false;
// Always can see self
if (u==this)
return true;
// Visible units, always are visible for all players
if (GetVisibility() == VISIBILITY_ON)
return true;
// GMs are visible for higher gms (or players are visible for gms)
if (u->GetSession()->GetSecurity() > SEC_PLAYER)
return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
// non faction visibility non-breakable for non-GMs
if (GetVisibility() == VISIBILITY_OFF)
return false;
// non-gm stealth/invisibility not hide from global player lists
return true;
}
template<class T>
inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
{
}
template<>
inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
{
if (p->GetPetGuid() == t->GetObjectGuid() && ((Creature*)t)->IsPet())
((Pet*)t)->Unsummon(PET_SAVE_REAGENTS);
}
void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
{
if (HaveAtClient(target))
{
if(!target->isVisibleForInState(this, viewPoint, true))
{
ObjectGuid t_guid = target->GetObjectGuid();
if (target->GetTypeId()==TYPEID_UNIT)
{
BeforeVisibilityDestroy<Creature>((Creature*)target,this);
// at remove from map (destroy) show kill animation (in different out of range/stealth case)
target->DestroyForPlayer(this, !target->IsInWorld() && ((Creature*)target)->isDead());
}
else
target->DestroyForPlayer(this);
m_clientGUIDs.erase(t_guid);
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s out of range for player %u. Distance = %f",t_guid.GetString().c_str(),GetGUIDLow(),GetDistance(target));
}
}
else
{
if (target->isVisibleForInState(this, viewPoint, false))
{
target->SendCreateUpdateToPlayer(this);
if (target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
m_clientGUIDs.insert(target->GetObjectGuid());
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
// target aura duration for caster show only if target exist at caster client
// send data at target visibility change (adding to client)
if (target!=this && target->isType(TYPEMASK_UNIT))
SendAurasForTarget((Unit*)target);
}
}
}
template<class T>
inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, T* target)
{
s64.insert(target->GetObjectGuid());
}
template<>
inline void UpdateVisibilityOf_helper(ObjectGuidSet& s64, GameObject* target)
{
if(!target->IsTransport())
s64.insert(target->GetObjectGuid());
}
template<class T>
void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, std::set<WorldObject*>& visibleNow)
{
if (HaveAtClient(target))
{
if(!target->isVisibleForInState(this,viewPoint,true))
{
BeforeVisibilityDestroy<T>(target,this);
ObjectGuid t_guid = target->GetObjectGuid();
target->BuildOutOfRangeUpdateBlock(&data);
m_clientGUIDs.erase(t_guid);
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is out of range for %s. Distance = %f", t_guid.GetString().c_str(), GetGuidStr().c_str(), GetDistance(target));
}
}
else
{
if (target->isVisibleForInState(this,viewPoint,false))
{
visibleNow.insert(target);
target->BuildCreateUpdateBlockForPlayer(&data, this);
UpdateVisibilityOf_helper(m_clientGUIDs,target);
DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is visible now for %s. Distance = %f", target->GetGuidStr().c_str(), GetGuidStr().c_str(), GetDistance(target));
}
}
}
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, std::set<WorldObject*>& visibleNow);
void Player::SetPhaseMask(uint32 newPhaseMask, bool update)
{
// GM-mode have mask PHASEMASK_ANYWHERE always
if (isGameMaster())
newPhaseMask = PHASEMASK_ANYWHERE;
// phase auras normally not expected at BG but anyway better check
if (BattleGround *bg = GetBattleGround())
bg->EventPlayerDroppedFlag(this);
Unit::SetPhaseMask(newPhaseMask, update);
GetSession()->SendSetPhaseShift(GetPhaseMask());
}
void Player::InitPrimaryProfessions()
{
uint32 maxProfs = GetSession()->GetSecurity() < AccountTypes(sWorld.getConfig(CONFIG_UINT32_TRADE_SKILL_GMIGNORE_MAX_PRIMARY_COUNT))
? sWorld.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL) : 10;
SetFreePrimaryProfessions(maxProfs);
}
void Player::SendComboPoints(ObjectGuid targetGuid, uint8 combopoints)
{
Unit* combotarget = GetMap()->GetUnit(targetGuid);
if (combotarget)
{
WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
data << combotarget->GetPackGUID();
data << uint8(combopoints);
GetSession()->SendPacket(&data);
}
/*else
{
// can be NULL, and then points=0. Use unknown; to reset points of some sort?
data << PackedGuid();
data << uint8(0);
GetSession()->SendPacket(&data);
}*/
}
void Player::SendPetComboPoints(Unit* pet, ObjectGuid targetGuid, uint8 combopoints)
{
Unit* combotarget = pet ? pet->GetMap()->GetUnit(targetGuid) : NULL;
if (pet && combotarget)
{
WorldPacket data(SMSG_PET_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+pet->GetPackGUID().size()+1);
data << pet->GetPackGUID();
data << combotarget->GetPackGUID();
data << uint8(combopoints);
GetSession()->SendPacket(&data);
}
}
void Player::SetGroup(Group *group, int8 subgroup)
{
if (group == NULL)
m_group.unlink();
else
{
// never use SetGroup without a subgroup unless you specify NULL for group
MANGOS_ASSERT(subgroup >= 0);
m_group.link(group, this);
m_group.setSubGroup((uint8)subgroup);
}
}
void Player::SendInitialPacketsBeforeAddToMap()
{
GetSocial()->SendSocialList();
// Homebind
WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
data << m_homebindX << m_homebindY << m_homebindZ;
data << (uint32) m_homebindMapId;
data << (uint32) m_homebindAreaId;
GetSession()->SendPacket(&data);
// SMSG_SET_PROFICIENCY
// SMSG_SET_PCT_SPELL_MODIFIER
// SMSG_SET_FLAT_SPELL_MODIFIER
SendTalentsInfoData(false);
data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
data << uint32(GetMap()->GetDifficulty());
data << uint32(0);
GetSession()->SendPacket(&data);
SendInitialSpells();
data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
data << uint32(0); // count, for(count) uint32;
GetSession()->SendPacket(&data);
SendInitialActionButtons();
m_reputationMgr.SendInitialReputations();
if(!isAlive())
SendCorpseReclaimDelay(true);
SendInitWorldStates(GetZoneId(), GetAreaId());
SendEquipmentSetList();
m_achievementMgr.SendAllAchievementData();
data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
data << (float)0.01666667f; // game speed
data << uint32(0); // added in 3.1.2
GetSession()->SendPacket( &data );
// SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
// SMSG_PET_GUIDS
// SMSG_POWER_UPDATE
// set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
if (IsFreeFlying() || IsTaxiFlying())
m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING);
SetMover(this);
}
void Player::SendInitialPacketsAfterAddToMap()
{
// update zone
uint32 newzone, newarea;
GetZoneAndAreaId(newzone,newarea);
UpdateZone(newzone,newarea); // also call SendInitWorldStates();
ResetTimeSync();
SendTimeSync();
CastSpell(this, 836, true); // LOGINEFFECT
// set some aura effects that send packet to player client after add player to map
// SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
// same auras state lost at far teleport, send it one more time in this case also
static const AuraType auratypes[] =
{
SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
SPELL_AURA_FLY, SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED, SPELL_AURA_NONE
};
for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
{
Unit::AuraList const& auraList = GetAurasByType(*itr);
if(!auraList.empty())
auraList.front()->ApplyModifier(true,true);
}
if (HasAuraType(SPELL_AURA_MOD_STUN))
SetMovement(MOVE_ROOT);
// manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
if (HasAuraType(SPELL_AURA_MOD_ROOT))
{
WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
data2 << GetPackGUID();
data2 << (uint32)2;
SendMessageToSet(&data2,true);
}
if (GetVehicle())
{
WorldPacket data3(SMSG_FORCE_MOVE_ROOT, 10);
data3 << GetPackGUID();
data3 << uint32((m_movementInfo.GetVehicleSeatFlags() & SEAT_FLAG_CAN_CAST) ? 2 : 0);
SendMessageToSet(&data3,true);
}
SendAurasForTarget(this);
SendEnchantmentDurations(); // must be after add to map
SendItemDurations(); // must be after add to map
}
void Player::SendUpdateToOutOfRangeGroupMembers()
{
if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
return;
if (Group* group = GetGroup())
group->UpdatePlayerOutOfRange(this);
m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
m_auraUpdateMask = 0;
if (Pet *pet = GetPet())
pet->ResetAuraUpdateMask();
}
void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
{
WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
data << uint32(mapid);
data << uint8(reason); // transfer abort reason
switch(reason)
{
case TRANSFER_ABORT_INSUF_EXPAN_LVL:
case TRANSFER_ABORT_DIFFICULTY:
case TRANSFER_ABORT_UNIQUE_MESSAGE:
data << uint8(arg);
break;
}
GetSession()->SendPacket(&data);
}
void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
{
// type of warning, based on the time remaining until reset
uint32 type;
if (time > 3600)
type = RAID_INSTANCE_WELCOME;
else if (time > 900 && time <= 3600)
type = RAID_INSTANCE_WARNING_HOURS;
else if (time > 300 && time <= 900)
type = RAID_INSTANCE_WARNING_MIN;
else
type = RAID_INSTANCE_WARNING_MIN_SOON;
WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
data << uint32(type);
data << uint32(mapid);
data << uint32(difficulty); // difficulty
data << uint32(time);
if (type == RAID_INSTANCE_WELCOME)
{
data << uint8(0); // is your (1)
data << uint8(0); // is extended (1), ignored if prev field is 0
}
GetSession()->SendPacket(&data);
}
void Player::ApplyEquipCooldown( Item * pItem )
{
if (pItem->GetProto()->Flags & ITEM_FLAG_NO_EQUIP_COOLDOWN)
return;
for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
{
_Spell const& spellData = pItem->GetProto()->Spells[i];
// no spell
if ( !spellData.SpellId )
continue;
// wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
if ( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
continue;
AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
data << ObjectGuid(pItem->GetObjectGuid());
data << uint32(spellData.SpellId);
GetSession()->SendPacket(&data);
}
}
void Player::resetSpells()
{
// not need after this call
if (HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
// make full copy of map (spells removed and marked as deleted at another spell remove
// and we can't use original map for safe iterative with visit each spell at loop end
PlayerSpellMap smap = GetSpellMap();
for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
learnDefaultSpells();
learnQuestRewardedSpells();
}
void Player::learnDefaultSpells()
{
// learn default race/class spells
PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass());
for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
{
uint32 tspell = *itr;
DEBUG_LOG("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
addSpell(tspell, true, true, true, false);
else // but send in normal spell in game learn case
learnSpell(tspell, true);
}
}
void Player::learnQuestRewardedSpells(Quest const* quest)
{
uint32 spell_id = quest->GetRewSpellCast();
// skip quests without rewarded spell
if ( !spell_id )
return;
SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
if(!spellInfo)
return;
// check learned spells state
bool found = false;
for(int i=0; i < MAX_EFFECT_INDEX; ++i)
{
if (spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
{
found = true;
break;
}
}
// skip quests with not teaching spell or already known spell
if(!found)
return;
// prevent learn non first rank unknown profession and second specialization for same profession)
uint32 learned_0 = spellInfo->EffectTriggerSpell[EFFECT_INDEX_0];
if ( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
{
// not have first rank learned (unlearned prof?)
uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0);
if ( !HasSpell(first_spell) )
return;
SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
if(!learnedInfo)
return;
// specialization
if (learnedInfo->Effect[EFFECT_INDEX_0] == SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[EFFECT_INDEX_1] == 0)
{
// search other specialization for same prof
for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
{
if (itr->second.state == PLAYERSPELL_REMOVED || itr->first==learned_0)
continue;
SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
if(!itrInfo)
return;
// compare only specializations
if (itrInfo->Effect[EFFECT_INDEX_0] != SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[EFFECT_INDEX_1] != 0)
continue;
// compare same chain spells
if (sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell)
continue;
// now we have 2 specialization, learn possible only if found is lesser specialization rank
if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first))
return;
}
}
}
CastSpell( this, spell_id, true);
}
void Player::learnQuestRewardedSpells()
{
// learn spells received from quest completing
for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
{
// skip no rewarded quests
if(!itr->second.m_rewarded)
continue;
Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first);
if ( !quest )
continue;
learnQuestRewardedSpells(quest);
}
}
void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
{
uint32 raceMask = getRaceMask();
uint32 classMask = getClassMask();
for (uint32 j = 0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
{
SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
continue;
// Check race if set
if (pAbility->racemask && !(pAbility->racemask & raceMask))
continue;
// Check class if set
if (pAbility->classmask && !(pAbility->classmask & classMask))
continue;
if (sSpellStore.LookupEntry(pAbility->spellId))
{
// need unlearn spell
if (skill_value < pAbility->req_skill_value)
removeSpell(pAbility->spellId);
// need learn
else if (!IsInWorld())
addSpell(pAbility->spellId, true, true, true, false);
else
learnSpell(pAbility->spellId, true);
}
}
}
void Player::SendAurasForTarget(Unit *target)
{
WorldPacket data(SMSG_AURA_UPDATE_ALL);
data << target->GetPackGUID();
MAPLOCK_READ(target,MAP_LOCK_TYPE_AURAS);
Unit::VisibleAuraMap const& visibleAuras = target->GetVisibleAuras();
for (Unit::VisibleAuraMap::const_iterator itr = visibleAuras.begin(); itr != visibleAuras.end(); ++itr)
{
SpellAuraHolderConstBounds bounds = target->GetSpellAuraHolderBounds(itr->second);
for (SpellAuraHolderMap::const_iterator iter = bounds.first; iter != bounds.second; ++iter)
iter->second->BuildUpdatePacket(data);
}
GetSession()->SendPacket(&data);
}
void Player::SetDailyQuestStatus( uint32 quest_id )
{
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
{
if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
{
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
m_DailyQuestChanged = true;
break;
}
}
}
void Player::SetWeeklyQuestStatus( uint32 quest_id )
{
m_weeklyquests.insert(quest_id);
m_WeeklyQuestChanged = true;
}
void Player::SetMonthlyQuestStatus(uint32 quest_id)
{
m_monthlyquests.insert(quest_id);
m_MonthlyQuestChanged = true;
}
void Player::ResetDailyQuestStatus()
{
for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
// DB data deleted in caller
m_DailyQuestChanged = false;
}
void Player::ResetWeeklyQuestStatus()
{
if (m_weeklyquests.empty())
return;
m_weeklyquests.clear();
// DB data deleted in caller
m_WeeklyQuestChanged = false;
}
void Player::ResetMonthlyQuestStatus()
{
if (m_monthlyquests.empty())
return;
m_monthlyquests.clear();
// DB data deleted in caller
m_MonthlyQuestChanged = false;
}
BattleGround* Player::GetBattleGround() const
{
if (GetBattleGroundId()==0)
return NULL;
return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
}
bool Player::InArena() const
{
BattleGround *bg = GetBattleGround();
if(!bg || !bg->isArena())
return false;
return true;
}
bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
{
// get a template bg instead of running one
BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
if(!bg)
return false;
// limit check leel to dbc compatible level range
uint32 level = getLevel();
if (level > DEFAULT_MAX_LEVEL)
level = DEFAULT_MAX_LEVEL;
if (level < bg->GetMinLevel() || level > bg->GetMaxLevel())
return false;
return true;
}
float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
{
FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
if(!vendor_faction || !vendor_faction->faction)
return 1.0f;
ReputationRank rank = GetReputationRank(vendor_faction->faction);
if (rank <= REP_NEUTRAL)
return 1.0f;
return 1.0f - 0.05f* (rank - REP_NEUTRAL);
}
/**
* Check spell availability for training base at SkillLineAbility/SkillRaceClassInfo data.
* Checked allowed race/class and dependent from race/class allowed min level
*
* @param spell_id checked spell id
* @param pReqlevel if arg provided then function work in view mode (level check not applied but detected minlevel returned to var by arg pointer.
if arg not provided then considered train action mode and level checked
* @return true if spell available for show in trainer list (with skip level check) or training.
*/
bool Player::IsSpellFitByClassAndRace(uint32 spell_id, uint32* pReqlevel /*= NULL*/) const
{
uint32 racemask = getRaceMask();
uint32 classmask = getClassMask();
SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
if (bounds.first==bounds.second)
return true;
for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
{
SkillLineAbilityEntry const* abilityEntry = _spell_idx->second;
// skip wrong race skills
if (abilityEntry->racemask && (abilityEntry->racemask & racemask) == 0)
continue;
// skip wrong class skills
if (abilityEntry->classmask && (abilityEntry->classmask & classmask) == 0)
continue;
SkillRaceClassInfoMapBounds bounds = sSpellMgr.GetSkillRaceClassInfoMapBounds(abilityEntry->skillId);
for (SkillRaceClassInfoMap::const_iterator itr = bounds.first; itr != bounds.second; ++itr)
{
SkillRaceClassInfoEntry const* skillRCEntry = itr->second;
if ((skillRCEntry->raceMask & racemask) && (skillRCEntry->classMask & classmask))
{
if (skillRCEntry->flags & ABILITY_SKILL_NONTRAINABLE)
return false;
if (pReqlevel) // show trainers list case
{
if (skillRCEntry->reqLevel)
{
*pReqlevel = skillRCEntry->reqLevel;
return true;
}
}
else // check availble case at train
{
if (skillRCEntry->reqLevel && getLevel() < skillRCEntry->reqLevel)
return false;
}
}
}
return true;
}
return false;
}
bool Player::HasQuestForGO(int32 GOId) const
{
for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
{
uint32 questid = GetQuestSlotQuestId(i);
if ( questid == 0 )
continue;
QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
if (qs_itr == mQuestStatus.end())
continue;
QuestStatusData const& qs = qs_itr->second;
if (qs.m_status == QUEST_STATUS_INCOMPLETE)
{
Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
if(!qinfo)
continue;
if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid())
continue;
for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
{
if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
continue;
if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
return true;
}
}
}
return false;
}
void Player::UpdateForQuestWorldObjects()
{
if (m_clientGUIDs.empty() || !GetMap())
return;
UpdateData udata;
WorldPacket packet;
for(ObjectGuidSet::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
{
if (itr->IsGameObject())
{
if (GameObject *obj = GetMap()->GetGameObject(*itr))
obj->BuildValuesUpdateBlockForPlayer(&udata,this);
}
else if (itr->IsCreatureOrVehicle())
{
Creature *obj = GetMap()->GetAnyTypeCreature(*itr);
if(!obj)
continue;
// check if this unit requires quest specific flags
if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
continue;
SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry());
for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
{
if (_itr->second.questStart || _itr->second.questEnd)
{
obj->BuildCreateUpdateBlockForPlayer(&udata,this);
break;
}
}
}
}
udata.BuildPacket(&packet);
GetSession()->SendPacket(&packet);
}
void Player::SummonIfPossible(bool agree)
{
if(!agree)
{
m_summon_expire = 0;
return;
}
// expire and auto declined
if (m_summon_expire < time(NULL))
return;
// stop taxi flight at summon
if (IsTaxiFlying())
{
GetMotionMaster()->MoveIdle();
m_taxi.ClearTaxiDestinations();
}
// drop flag at summon
// this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
if (BattleGround *bg = GetBattleGround())
bg->EventPlayerDroppedFlag(this);
m_summon_expire = 0;
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
}
void Player::RemoveItemDurations( Item *item )
{
for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
{
if(*itr==item)
{
m_itemDuration.erase(itr);
break;
}
}
}
void Player::AddItemDurations( Item *item )
{
if (item->GetUInt32Value(ITEM_FIELD_DURATION))
{
m_itemDuration.push_back(item);
item->SendTimeUpdate(this);
}
}
void Player::AutoUnequipOffhandIfNeed()
{
Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
if(!offItem)
return;
// need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
if ((CanDualWield() || offItem->GetProto()->InventoryType == INVTYPE_SHIELD || offItem->GetProto()->InventoryType == INVTYPE_HOLDABLE) &&
(CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed())))
return;
ItemPosCountVec off_dest;
uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
if ( off_msg == EQUIP_ERR_OK )
{
RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
StoreItem( off_dest, offItem, true );
}
else
{
MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
CharacterDatabase.BeginTransaction();
offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
CharacterDatabase.CommitTransaction();
std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
MailDraft(subject, "There's were problems with equipping this item.").AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);
}
}
bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
{
if (spellInfo->EquippedItemClass < 0)
return true;
// scan other equipped items for same requirements (mostly 2 daggers/etc)
// for optimize check 2 used cases only
switch(spellInfo->EquippedItemClass)
{
case ITEM_CLASS_WEAPON:
{
for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
break;
}
case ITEM_CLASS_ARMOR:
{
// tabard not have dependent spells
for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
// shields can be equipped to offhand slot
if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
// ranged slot can have some armor subclasses
if (Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
if (item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
return true;
break;
}
default:
sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
break;
}
return false;
}
bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
{
// don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
return true;
// Check no reagent use mask
ClassFamilyMask noReagentMask(GetUInt64Value(PLAYER_NO_REAGENT_COST_1), GetUInt32Value(PLAYER_NO_REAGENT_COST_1+2));
if (spellInfo->IsFitToFamilyMask(noReagentMask))
return true;
return false;
}
void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
{
SpellAuraHolderMap& auras = GetSpellAuraHolderMap();
for(SpellAuraHolderMap::const_iterator itr = auras.begin(); itr != auras.end(); )
{
// skip passive (passive item dependent spells work in another way) and not self applied auras
SpellEntry const* spellInfo = itr->second->GetSpellProto();
if (itr->second->IsPassive() || itr->second->GetCasterGuid() != GetObjectGuid())
{
++itr;
continue;
}
// Remove spells triggered by equipped item auras
if (pItem->HasTriggeredByAuraSpell(spellInfo))
{
RemoveAurasDueToSpell(itr->second->GetId());
itr = auras.begin();
continue;
}
// skip if not item dependent or have alternative item
if (HasItemFitToSpellReqirements(spellInfo,pItem))
{
++itr;
continue;
}
// no alt item, remove aura, restart check
RemoveAurasDueToSpell(itr->second->GetId());
itr = auras.begin();
}
// currently casted spells can be dependent from item
for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
InterruptSpell(CurrentSpellTypes(i));
}
uint32 Player::GetResurrectionSpellId()
{
// search priceless resurrection possibilities
uint32 prio = 0;
uint32 spell_id = 0;
AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
{
// Soulstone Resurrection // prio: 3 (max, non death persistent)
if ( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
{
switch((*itr)->GetId())
{
case 20707: spell_id = 3026; break; // rank 1
case 20762: spell_id = 20758; break; // rank 2
case 20763: spell_id = 20759; break; // rank 3
case 20764: spell_id = 20760; break; // rank 4
case 20765: spell_id = 20761; break; // rank 5
case 27239: spell_id = 27240; break; // rank 6
case 47883: spell_id = 47882; break; // rank 7
default:
sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
continue;
}
prio = 3;
}
// Twisting Nether // prio: 2 (max)
else if((*itr)->GetId()==23701 && roll_chance_i(10))
{
prio = 2;
spell_id = 23700;
}
}
// Reincarnation (passive spell) // prio: 1
// Glyph of Renewed Life remove reagent requiremnnt
if (prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, EFFECT_INDEX_0)))
spell_id = 21169;
return spell_id;
}
// Used in triggers for check "Only to targets that grant experience or honor" req
bool Player::isHonorOrXPTarget(Unit* pVictim) const
{
if (!pVictim)
return false;
uint32 v_level = pVictim->getLevel();
uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
// Victim level less gray level
if (v_level<=k_grey)
return false;
if (pVictim->GetTypeId() == TYPEID_UNIT)
{
if (((Creature*)pVictim)->IsTotem() ||
((Creature*)pVictim)->IsPet() ||
((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
return false;
}
return true;
}
void Player::RewardSinglePlayerAtKill(Unit* pVictim)
{
bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
uint32 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
// honor can be in PvP and !PvP (racial leader) cases
RewardHonor(pVictim,1);
// xp and reputation only in !PvP case
if(!PvP)
{
RewardReputation(pVictim,1);
GiveXP(xp, pVictim);
if (Pet* pet = GetPet())
pet->GivePetXP(xp);
// normal creature (not pet/etc) can be only in !PvP case
if (pVictim->GetTypeId()==TYPEID_UNIT)
if (CreatureInfo const* normalInfo = ObjectMgr::GetCreatureTemplate(pVictim->GetEntry()))
KilledMonster(normalInfo, pVictim->GetObjectGuid());
}
}
void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
{
ObjectGuid creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetObjectGuid() : ObjectGuid();
// prepare data for near group iteration
if (Group *pGroup = GetGroup())
{
for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* pGroupGuy = itr->getSource();
if (!pGroupGuy)
continue;
if (!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
continue; // member (alive or dead) or his corpse at req. distance
// quest objectives updated only for alive group member or dead but with not released body
if (pGroupGuy->isAlive()|| !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
}
}
else // if (!pGroup)
KilledMonsterCredit(creature_id, creature_guid);
}
void Player::RewardPlayerAndGroupAtCast(WorldObject* pRewardSource, uint32 spellid)
{
// prepare data for near group iteration
if (Group *pGroup = GetGroup())
{
for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* pGroupGuy = itr->getSource();
if(!pGroupGuy)
continue;
if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
continue; // member (alive or dead) or his corpse at req. distance
// quest objectives updated only for alive group member or dead but with not released body
if (pGroupGuy->isAlive()|| !pGroupGuy->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
pGroupGuy->CastedCreatureOrGO(pRewardSource->GetEntry(), pRewardSource->GetObjectGuid(), spellid, pGroupGuy == this);
}
}
else // if (!pGroup)
CastedCreatureOrGO(pRewardSource->GetEntry(), pRewardSource->GetObjectGuid(), spellid);
}
bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
{
if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE)))
return true;
if (isAlive())
return false;
Corpse* corpse = GetCorpse();
if (!corpse)
return false;
return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE));
}
uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
{
Item* item = GetWeaponForAttack(attType,true,true);
// unarmed only with base attack
if (attType != BASE_ATTACK && !item)
return 0;
// weapon skill or (unarmed for base attack)
uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
return GetBaseSkillValue(skill);
}
void Player::ResurectUsingRequestData()
{
/// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
if (m_resurrectGuid.IsPlayer())
TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
//we cannot resurrect player when we triggered far teleport
//player will be resurrected upon teleportation
if (IsBeingTeleportedFar())
{
ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
return;
}
ResurrectPlayer(0.0f,false);
if (GetMaxHealth() > m_resurrectHealth)
SetHealth( m_resurrectHealth );
else
SetHealth( GetMaxHealth() );
if (GetMaxPower(POWER_MANA) > m_resurrectMana)
SetPower(POWER_MANA, m_resurrectMana );
else
SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
SetPower(POWER_RAGE, 0 );
SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
SpawnCorpseBones();
}
void Player::SetClientControl(Unit* target, uint8 allowMove)
{
WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
data << target->GetPackGUID();
data << uint8(allowMove);
if (GetSession())
GetSession()->SendPacket(&data);
}
void Player::UpdateZoneDependentAuras()
{
// Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(m_zoneUpdateId);
for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this, m_zoneUpdateId, 0))
if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
CastSpell(this,itr->second->spellId,true);
}
void Player::UpdateAreaDependentAuras()
{
// remove auras from spells with area limitations
SpellIdSet toRemoveSpellList;
{
MAPLOCK_READ(this,MAP_LOCK_TYPE_AURAS);
SpellAuraHolderMap const& holdersMap = GetSpellAuraHolderMap();
for(SpellAuraHolderMap::const_iterator iter = holdersMap.begin(); iter != holdersMap.end(); ++iter)
{
// use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
if (iter->second && (sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(), GetMapId(), m_zoneUpdateId, m_areaUpdateId, this) != SPELL_CAST_OK))
toRemoveSpellList.insert(iter->first);
}
}
if (!toRemoveSpellList.empty())
for (SpellIdSet::iterator i = toRemoveSpellList.begin(); i != toRemoveSpellList.end(); ++i)
RemoveAurasDueToSpell(*i);
// some auras applied at subzone enter
SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(m_areaUpdateId);
for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
if (itr->second->autocast && itr->second->IsFitToRequirements(this, m_zoneUpdateId, m_areaUpdateId))
if (!HasAura(itr->second->spellId, EFFECT_INDEX_0))
CastSpell(this,itr->second->spellId,true);
}
struct UpdateZoneDependentPetsHelper
{
explicit UpdateZoneDependentPetsHelper(Player* _owner, uint32 zone, uint32 area) : owner(_owner), zone_id(zone), area_id(area) {}
void operator()(Unit* unit) const
{
if (unit->GetTypeId() == TYPEID_UNIT && ((Creature*)unit)->IsPet() && !((Pet*)unit)->IsPermanentPetFor(owner))
if (uint32 spell_id = unit->GetUInt32Value(UNIT_CREATED_BY_SPELL))
if (SpellEntry const* spellEntry = sSpellStore.LookupEntry(spell_id))
if (sSpellMgr.GetSpellAllowedInLocationError(spellEntry, owner->GetMapId(), zone_id, area_id, owner) != SPELL_CAST_OK)
((Pet*)unit)->Unsummon(PET_SAVE_AS_DELETED, owner);
}
Player* owner;
uint32 zone_id;
uint32 area_id;
};
void Player::UpdateZoneDependentPets()
{
// check pet (permanent pets ignored), minipet, guardians (including protector)
CallForAllControlledUnits(UpdateZoneDependentPetsHelper(this, m_zoneUpdateId, m_areaUpdateId), CONTROLLED_PET|CONTROLLED_GUARDIANS|CONTROLLED_MINIPET);
}
uint32 Player::GetCorpseReclaimDelay(bool pvp) const
{
if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
(!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
{
return copseReclaimDelay[0];
}
time_t now = time(NULL);
// 0..2 full period
uint32 count = (now < m_deathExpireTime) ? uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP) : 0;
return copseReclaimDelay[count];
}
void Player::UpdateCorpseReclaimDelay()
{
bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
if ((pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
(!pvp && !sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
return;
time_t now = time(NULL);
if (now < m_deathExpireTime)
{
// full and partly periods 1..3
uint32 count = uint32((m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1);
if (count < MAX_DEATH_COUNT)
m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
else
m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
}
else
m_deathExpireTime = now+DEATH_EXPIRE_STEP;
}
void Player::SendCorpseReclaimDelay(bool load)
{
Corpse* corpse = GetCorpse();
if (!corpse)
return;
uint32 delay;
if (load)
{
if (corpse->GetGhostTime() > m_deathExpireTime)
return;
bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
uint32 count;
if ((pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
(!pvp && sWorld.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE)))
{
count = uint32(m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
if (count>=MAX_DEATH_COUNT)
count = MAX_DEATH_COUNT-1;
}
else
count=0;
time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
time_t now = time(NULL);
if (now >= expected_time)
return;
delay = uint32(expected_time-now);
}
else
delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
//! corpse reclaim delay 30 * 1000ms or longer at often deaths
WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
data << uint32(delay*IN_MILLISECONDS);
GetSession()->SendPacket( &data );
}
Player* Player::GetNextRandomRaidMember(float radius)
{
Group *pGroup = GetGroup();
if(!pGroup)
return NULL;
std::vector<Player*> nearMembers;
nearMembers.reserve(pGroup->GetMembersCount());
for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* Target = itr->getSource();
// IsHostileTo check duel and controlled by enemy
if ( Target && Target != this && IsWithinDistInMap(Target, radius) &&
!Target->HasInvisibilityAura() && !IsHostileTo(Target) )
nearMembers.push_back(Target);
}
if (nearMembers.empty())
return NULL;
uint32 randTarget = urand(0,nearMembers.size()-1);
return nearMembers[randTarget];
}
PartyResult Player::CanUninviteFromGroup() const
{
const Group* grp = GetGroup();
if (!grp)
return ERR_NOT_IN_GROUP;
if (!grp->IsLeader(GetObjectGuid()) && !grp->IsAssistant(GetObjectGuid()))
return ERR_NOT_LEADER;
if (InBattleGround())
return ERR_INVITE_RESTRICTED;
return ERR_PARTY_RESULT_OK;
}
void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
{
//we must move references from m_group to m_originalGroup
SetOriginalGroup(GetGroup(), GetSubGroup());
m_group.unlink();
m_group.link(group, this);
m_group.setSubGroup((uint8)subgroup);
}
void Player::RemoveFromBattleGroundRaid()
{
//remove existing reference
m_group.unlink();
if ( Group* group = GetOriginalGroup() )
{
m_group.link(group, this);
m_group.setSubGroup(GetOriginalSubGroup());
}
SetOriginalGroup(NULL);
}
void Player::SetOriginalGroup(Group *group, int8 subgroup)
{
if ( group == NULL )
m_originalGroup.unlink();
else
{
// never use SetOriginalGroup without a subgroup unless you specify NULL for group
MANGOS_ASSERT(subgroup >= 0);
m_originalGroup.link(group, this);
m_originalGroup.setSubGroup((uint8)subgroup);
}
}
void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
{
GridMapLiquidData liquid_status;
GridMapLiquidStatus res = m->GetTerrain()->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
if (!res)
{
m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWATER_INDARKWATER);
// Small hack for enable breath in WMO
/* if (IsInWater())
m_MirrorTimerFlags|=UNDERWATER_INWATER; */
return;
}
// All liquids type - check under water position
if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
{
if ( res & LIQUID_MAP_UNDER_WATER)
m_MirrorTimerFlags |= UNDERWATER_INWATER;
else
m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
}
// Allow travel in dark water on taxi or transport
if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !IsTaxiFlying() && !GetTransport())
m_MirrorTimerFlags |= UNDERWATER_INDARKWATER;
else
m_MirrorTimerFlags &= ~UNDERWATER_INDARKWATER;
// in lava check, anywhere in lava level
if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
{
if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
m_MirrorTimerFlags |= UNDERWATER_INLAVA;
else
m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
}
// in slime check, anywhere in slime level
if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
{
if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
m_MirrorTimerFlags |= UNDERWATER_INSLIME;
else
m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
}
}
void Player::SetCanParry( bool value )
{
if (m_canParry==value)
return;
m_canParry = value;
UpdateParryPercentage();
}
void Player::SetCanBlock( bool value )
{
if (m_canBlock==value)
return;
m_canBlock = value;
UpdateBlockPercentage();
}
bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
{
for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
if (itr->pos == pos)
return true;
return false;
}
bool Player::CanUseBattleGroundObject()
{
// TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
// maybe gameobject code should handle that ForceReaction usage
// BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
return ( //InBattleGround() && // in battleground - not need, check in other cases
//!IsMounted() && - not correct, player is dismounted when he clicks on flag
//player cannot use object when he is invulnerable (immune)
!isTotalImmune() && // not totally immune
//i'm not sure if these two are correct, because invisible players should get visible when they click on flag
!HasStealthAura() && // not stealthed
!HasInvisibilityAura() && // not invisible
!HasAura(SPELL_RECENTLY_DROPPED_FLAG, EFFECT_INDEX_0) &&// can't pickup
isAlive() // live player
);
}
bool Player::CanCaptureTowerPoint()
{
return ( !HasStealthAura() && // not stealthed
!HasInvisibilityAura() && // not invisible
isAlive() // live player
);
}
uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, uint8 newskintone)
{
uint32 level = getLevel();
if (level > GT_MAX_LEVEL)
level = GT_MAX_LEVEL; // max level in this dbc
uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
uint8 skintone = GetByteValue(PLAYER_BYTES, 0);
if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) &&
((skintone == newskintone) || (newskintone == -1)))
return 0;
GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
if(!bsc) // shouldn't happen
return 0xFFFFFFFF;
float cost = 0;
if (hairstyle != newhairstyle)
cost += bsc->cost; // full price
if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
cost += bsc->cost * 0.5f; // +1/2 of price
if (facialhair != newfacialhair)
cost += bsc->cost * 0.75f; // +3/4 of price
if (skintone != newskintone && newskintone != -1) // +1/2 of price
cost += bsc->cost * 0.5f;
return uint32(cost);
}
void Player::InitGlyphsForLevel()
{
for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
if (GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
if (gs->Order)
SetGlyphSlot(gs->Order - 1, gs->Id);
uint32 level = getLevel();
uint32 value = 0;
// 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
if (level >= 15)
value |= (0x01 | 0x02);
if (level >= 30)
value |= 0x08;
if (level >= 50)
value |= 0x04;
if (level >= 70)
value |= 0x10;
if (level >= 80)
value |= 0x20;
SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
}
void Player::ApplyGlyph(uint8 slot, bool apply)
{
if (uint32 glyph = GetGlyph(slot))
{
if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
{
if (apply)
{
CastSpell(this, gp->SpellId, true);
SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, glyph);
}
else
{
RemoveAurasDueToSpell(gp->SpellId);
SetUInt32Value(PLAYER_FIELD_GLYPHS_1 + slot, 0);
}
}
}
}
void Player::ApplyGlyphs(bool apply)
{
for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
ApplyGlyph(i,apply);
}
bool Player::isTotalImmune()
{
AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
uint32 immuneMask = 0;
for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
{
immuneMask |= (*itr)->GetModifier()->m_miscvalue;
if ( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
return true;
}
return false;
}
bool Player::HasTitle(uint32 bitIndex) const
{
if (bitIndex > MAX_TITLE_INDEX)
return false;
uint32 fieldIndexOffset = bitIndex / 32;
uint32 flag = 1 << (bitIndex % 32);
return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
void Player::SetTitle(CharTitlesEntry const* title, bool lost)
{
uint32 fieldIndexOffset = title->bit_index / 32;
uint32 flag = 1 << (title->bit_index % 32);
if (lost)
{
if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
return;
RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
else
{
if (HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
return;
SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}
WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
data << uint32(title->bit_index);
data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
GetSession()->SendPacket(&data);
}
void Player::ConvertRune(uint8 index, RuneType newType, uint32 spellid)
{
SetCurrentRune(index, newType);
if (spellid != 0)
SetConvertedBy(index, spellid);
WorldPacket data(SMSG_CONVERT_RUNE, 2);
data << uint8(index);
data << uint8(newType);
GetSession()->SendPacket(&data);
}
bool Player::ActivateRunes(RuneType type, uint32 count)
{
bool modify = false;
for(uint32 j = 0; count > 0 && j < MAX_RUNES; ++j)
{
if (GetCurrentRune(j) == type && GetRuneCooldown(j) > 0)
{
SetRuneCooldown(j, 0);
--count;
modify = true;
}
}
return modify;
}
void Player::ResyncRunes()
{
WorldPacket data(SMSG_RESYNC_RUNES, 4 + MAX_RUNES * 2);
data << uint32(MAX_RUNES);
for(uint32 i = 0; i < MAX_RUNES; ++i)
{
data << uint8(GetCurrentRune(i)); // rune type
data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
}
GetSession()->SendPacket(&data);
}
void Player::AddRunePower(uint8 index)
{
WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
data << uint32(1 << index); // mask (0x00-0x3F probably)
GetSession()->SendPacket(&data);
}
static RuneType runeSlotTypes[MAX_RUNES] = {
/*0*/ RUNE_BLOOD,
/*1*/ RUNE_BLOOD,
/*2*/ RUNE_UNHOLY,
/*3*/ RUNE_UNHOLY,
/*4*/ RUNE_FROST,
/*5*/ RUNE_FROST
};
void Player::InitRunes()
{
if (getClass() != CLASS_DEATH_KNIGHT)
return;
m_runes = new Runes;
m_runes->runeState = 0;
m_runes->needConvert = 0;
for(uint32 i = 0; i < MAX_RUNES; ++i)
{
SetBaseRune(i, runeSlotTypes[i]); // init base types
SetCurrentRune(i, runeSlotTypes[i]); // init current types
SetRuneCooldown(i, 0); // reset cooldowns
SetConvertedBy(i, 0); // init spellid
m_runes->SetRuneState(i);
}
for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
}
bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
{
for(uint32 i = 0; i < MAX_RUNES; ++i)
if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
return false;
return true;
}
void Player::AutoStoreLoot(uint32 loot_id, LootStore const& store, bool broadcast, uint8 bag, uint8 slot)
{
Loot loot;
loot.FillLoot (loot_id, store, this, true);
AutoStoreLoot(loot, broadcast, bag, slot);
}
void Player::AutoStoreLoot(Loot& loot, bool broadcast, uint8 bag, uint8 slot)
{
uint32 max_slot = loot.GetMaxSlotInLootFor(this);
for(uint32 i = 0; i < max_slot; ++i)
{
LootItem* lootItem = loot.LootItemInSlot(i,this);
if (!lootItem)
continue;
ItemPosCountVec dest;
InventoryResult msg = CanStoreNewItem(bag,slot,dest,lootItem->itemid,lootItem->count);
if (msg != EQUIP_ERR_OK && slot != NULL_SLOT)
msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
if ( msg != EQUIP_ERR_OK && bag != NULL_BAG)
msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
if (msg != EQUIP_ERR_OK)
{
SendEquipError( msg, NULL, NULL, lootItem->itemid );
continue;
}
Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
SendNewItem(pItem, lootItem->count, false, false, broadcast);
}
}
Item* Player::ConvertItem(Item* item, uint32 newItemId)
{
uint16 pos = item->GetPos();
Item *pNewItem = Item::CreateItem(newItemId, 1, this);
if (!pNewItem)
return NULL;
// copy enchantments
for (uint8 j= PERM_ENCHANTMENT_SLOT; j<=TEMP_ENCHANTMENT_SLOT; ++j)
{
if (item->GetEnchantmentId(EnchantmentSlot(j)))
pNewItem->SetEnchantment(EnchantmentSlot(j), item->GetEnchantmentId(EnchantmentSlot(j)),
item->GetEnchantmentDuration(EnchantmentSlot(j)), item->GetEnchantmentCharges(EnchantmentSlot(j)));
}
// copy durability
if (item->GetUInt32Value(ITEM_FIELD_DURABILITY) < item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY))
{
double loosePercent = 1 - item->GetUInt32Value(ITEM_FIELD_DURABILITY) / double(item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY));
DurabilityLoss(pNewItem, loosePercent);
}
if (IsInventoryPos(pos))
{
ItemPosCountVec dest;
InventoryResult msg = CanStoreItem(item->GetBagSlot(), item->GetSlot(), dest, pNewItem, true);
// ignore cast/combat time restriction
if (msg == EQUIP_ERR_OK)
{
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
return StoreItem( dest, pNewItem, true);
}
}
else if (IsBankPos(pos))
{
ItemPosCountVec dest;
InventoryResult msg = CanBankItem(item->GetBagSlot(), item->GetSlot(), dest, pNewItem, true);
// ignore cast/combat time restriction
if (msg == EQUIP_ERR_OK)
{
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
return BankItem(dest, pNewItem, true);
}
}
else if (IsEquipmentPos (pos))
{
uint16 dest;
InventoryResult msg = CanEquipItem(item->GetSlot(), dest, pNewItem, true, false);
// ignore cast/combat time restriction
if (msg == EQUIP_ERR_OK)
{
DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
pNewItem = EquipItem(dest, pNewItem, true);
AutoUnequipOffhandIfNeed();
return pNewItem;
}
}
// fail
delete pNewItem;
return NULL;
}
uint32 Player::CalculateTalentsPoints() const
{
uint32 base_level = getClass() == CLASS_DEATH_KNIGHT ? 55 : 9;
uint32 base_talent = getLevel() <= base_level ? 0 : getLevel() - base_level;
uint32 talentPointsForLevel = base_talent + m_questRewardTalentCount;
return uint32(talentPointsForLevel * sWorld.getConfig(CONFIG_FLOAT_RATE_TALENT));
}
bool Player::CanStartFlyInArea(uint32 mapid, uint32 zone, uint32 area) const
{
if (isGameMaster())
return true;
// continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
if (v_map == 571 && !HasSpell(54197)) // Cold Weather Flying
return false;
// don't allow flying in Dalaran restricted areas
// (no other zones currently has areas with AREA_FLAG_CANNOT_FLY)
if (AreaTableEntry const* atEntry = GetAreaEntryByAreaID(area))
return (!(atEntry->flags & AREA_FLAG_CANNOT_FLY));
// TODO: disallow mounting in wintergrasp too when battle is in progress
// forced dismount part in Player::UpdateArea()
return true;
}
struct DoPlayerLearnSpell
{
DoPlayerLearnSpell(Player& _player) : player(_player) {}
void operator() (uint32 spell_id) { player.learnSpell(spell_id, false); }
Player& player;
};
void Player::learnSpellHighRank(uint32 spellid)
{
learnSpell(spellid, false);
DoPlayerLearnSpell worker(*this);
sSpellMgr.doForHighRanks(spellid, worker);
}
void Player::_LoadSkills(QueryResult *result)
{
// 0 1 2
// SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
uint32 count = 0;
if (result)
{
do
{
Field *fields = result->Fetch();
uint16 skill = fields[0].GetUInt16();
uint16 value = fields[1].GetUInt16();
uint16 max = fields[2].GetUInt16();
SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
if(!pSkill)
{
sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
continue;
}
// set fixed skill ranges
switch(GetSkillRangeType(pSkill,false))
{
case SKILL_RANGE_LANGUAGE: // 300..300
value = max = 300;
break;
case SKILL_RANGE_MONO: // 1..1, grey monolite bar
value = max = 1;
break;
default:
break;
}
if (value == 0)
{
sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
continue;
}
SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
learnSkillRewardedSpells(skill, value);
++count;
if (count >= PLAYER_MAX_SKILLS) // client limit
{
sLog.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
break;
}
} while (result->NextRow());
delete result;
}
for (; count < PLAYER_MAX_SKILLS; ++count)
{
SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
}
// special settings
if (getClass()==CLASS_DEATH_KNIGHT)
{
uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL));
if (base_level < 1)
base_level = 1;
uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
if (base_skill < 1)
base_skill = 1; // skill mast be known and then > 0 in any case
if (GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
SetSkill(SKILL_FIRST_AID, base_skill, base_skill);
if (GetPureSkillValue (SKILL_AXES) < base_skill)
SetSkill(SKILL_AXES, base_skill, base_skill);
if (GetPureSkillValue (SKILL_DEFENSE) < base_skill)
SetSkill(SKILL_DEFENSE, base_skill, base_skill);
if (GetPureSkillValue (SKILL_POLEARMS) < base_skill)
SetSkill(SKILL_POLEARMS, base_skill, base_skill);
if (GetPureSkillValue (SKILL_SWORDS) < base_skill)
SetSkill(SKILL_SWORDS, base_skill, base_skill);
if (GetPureSkillValue (SKILL_2H_AXES) < base_skill)
SetSkill(SKILL_2H_AXES, base_skill, base_skill);
if (GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
SetSkill(SKILL_2H_SWORDS, base_skill, base_skill);
if (GetPureSkillValue (SKILL_UNARMED) < base_skill)
SetSkill(SKILL_UNARMED, base_skill, base_skill);
}
}
uint32 Player::GetPhaseMaskForSpawn() const
{
uint32 phase = PHASEMASK_NORMAL;
if(!isGameMaster())
phase = GetPhaseMask();
else
{
AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
if(!phases.empty())
phase = phases.front()->GetMiscValue();
}
// some aura phases include 1 normal map in addition to phase itself
if (uint32 n_phase = phase & ~PHASEMASK_NORMAL)
return n_phase;
return PHASEMASK_NORMAL;
}
InventoryResult Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
{
ItemPrototype const* pProto = pItem->GetProto();
// proto based limitations
if (InventoryResult res = CanEquipUniqueItem(pProto,eslot,limit_count))
return res;
// check unique-equipped on gems
for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
{
uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
if(!enchant_id)
continue;
SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
if(!enchantEntry)
continue;
ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
if(!pGem)
continue;
// include for check equip another gems with same limit category for not equipped item (and then not counted)
uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
if (InventoryResult res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
return res;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
{
// check unique-equipped on item
if (itemProto->Flags & ITEM_FLAG_UNIQUE_EQUIPPED)
{
// there is an equip limit on this item
if (HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
}
// check unique-equipped limit
if (itemProto->ItemLimitCategory)
{
ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
if(!limitEntry)
return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
// NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
if (limit_count > limitEntry->maxCount)
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
// there is an equip limit on this item
if (HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;
}
return EQUIP_ERR_OK;
}
InventoryResult Player::CanEquipMoreJewelcraftingGems(uint32 count, uint8 except_slot) const
{
//uint32 tempcount = count;
for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (i == int(except_slot))
continue;
Item *pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if (!pItem)
continue;
ItemPrototype const *pProto = pItem->GetProto();
if (!pProto)
continue;
if (pProto->Socket[0].Color || pItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT))
{
count += pItem->GetJewelcraftingGemCount();
if (count > MAX_JEWELCRAFTING_GEMS)
return EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED;
}
}
return EQUIP_ERR_OK;
}
void Player::HandleFall(MovementInfo const& movementInfo)
{
// calculate total z distance of the fall
float z_diff = m_lastFallZ - movementInfo.GetPos()->z;
DEBUG_LOG("zDiff = %f", z_diff);
//Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
// 14.57 can be calculated by resolving damageperc formula below to 0
if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
!HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
!HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
{
//Safe fall, fall height reduction
int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
if (damageperc >0 )
{
uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getConfig(CONFIG_FLOAT_RATE_DAMAGE_FALL));
float height = movementInfo.GetPos()->z;
UpdateAllowedPositionZ(movementInfo.GetPos()->x, movementInfo.GetPos()->y, height);
if (damage > 0)
{
//Prevent fall damage from being more than the player maximum health
if (damage > GetMaxHealth())
damage = GetMaxHealth();
// Gust of Wind
if (GetDummyAura(43621))
damage = GetMaxHealth()/2;
uint32 original_health = GetHealth();
uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
// recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
if (isAlive() && final_damage < original_health)
GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
}
//Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.GetPos()->z, height, GetPositionZ(), movementInfo.GetFallTime(), height, damage, safe_fall);
}
}
RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_LANDING); // Remove auras that should be removed at landing
}
void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
{
GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
}
void Player::StartTimedAchievementCriteria(AchievementCriteriaTypes type, uint32 timedRequirementId, time_t startTime /*= 0*/)
{
GetAchievementMgr().StartTimedAchievementCriteria(type, timedRequirementId, startTime);
}
PlayerTalent const* Player::GetKnownTalentById(int32 talentId) const
{
PlayerTalentMap::const_iterator itr = m_talents[m_activeSpec].find(talentId);
if (itr != m_talents[m_activeSpec].end() && itr->second.state != PLAYERSPELL_REMOVED)
return &itr->second;
else
return NULL;
}
SpellEntry const* Player::GetKnownTalentRankById(int32 talentId) const
{
if (PlayerTalent const* talent = GetKnownTalentById(talentId))
return sSpellStore.LookupEntry(talent->talentEntry->RankID[talent->currentRank]);
else
return NULL;
}
void Player::LearnTalent(uint32 talentId, uint32 talentRank)
{
uint32 CurTalentPoints = GetFreeTalentPoints();
if (CurTalentPoints == 0)
return;
if (talentRank >= MAX_TALENT_RANK)
return;
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if(!talentInfo)
return;
TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
if(!talentTabInfo)
return;
// prevent learn talent for different class (cheating)
if ( (getClassMask() & talentTabInfo->ClassMask) == 0 )
return;
// find current max talent rank
uint32 curtalent_maxrank = 0;
if (PlayerTalent const* talent = GetKnownTalentById(talentId))
curtalent_maxrank = talent->currentRank + 1;
// we already have same or higher talent rank learned
if (curtalent_maxrank >= (talentRank + 1))
return;
// check if we have enough talent points
if (CurTalentPoints < (talentRank - curtalent_maxrank + 1))
return;
// Check if it requires another talent
if (talentInfo->DependsOn > 0)
{
if (TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
{
bool hasEnoughRank = false;
PlayerTalentMap::iterator dependsOnTalent = m_talents[m_activeSpec].find(depTalentInfo->TalentID);
if (dependsOnTalent != m_talents[m_activeSpec].end() && dependsOnTalent->second.state != PLAYERSPELL_REMOVED)
{
PlayerTalent depTalent = (*dependsOnTalent).second;
if (depTalent.currentRank >= talentInfo->DependsOnRank)
hasEnoughRank = true;
}
if (!hasEnoughRank)
return;
}
}
// Find out how many points we have in this field
uint32 spentPoints = 0;
uint32 tTab = talentInfo->TalentTab;
if (talentInfo->Row > 0)
{
for (PlayerTalentMap::const_iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end(); ++iter)
if (iter->second.state != PLAYERSPELL_REMOVED && iter->second.talentEntry->TalentTab == tTab)
spentPoints += iter->second.currentRank + 1;
}
// not have required min points spent in talent tree
if (spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
return;
// spell not set in talent.dbc
uint32 spellid = talentInfo->RankID[talentRank];
if ( spellid == 0 )
{
sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
return;
}
// already known
if (HasSpell(spellid))
return;
// learn! (other talent ranks will unlearned at learning)
learnSpell(spellid, false);
DETAIL_LOG("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
}
void Player::LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRank)
{
Pet *pet = GetPet();
if (!pet)
return;
if (petGuid != pet->GetObjectGuid())
return;
uint32 CurTalentPoints = pet->GetFreeTalentPoints();
if (CurTalentPoints == 0)
return;
if (talentRank >= MAX_PET_TALENT_RANK)
return;
TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
if(!talentInfo)
return;
TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
if(!talentTabInfo)
return;
CreatureInfo const *ci = pet->GetCreatureInfo();
if(!ci)
return;
CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
if(!pet_family)
return;
if (pet_family->petTalentType < 0) // not hunter pet
return;
// prevent learn talent for different family (cheating)
if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
return;
// find current max talent rank
int32 curtalent_maxrank = 0;
for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
{
if (talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
{
curtalent_maxrank = k + 1;
break;
}
}
// we already have same or higher talent rank learned
if (curtalent_maxrank >= int32(talentRank + 1))
return;
// check if we have enough talent points
if (CurTalentPoints < (talentRank - curtalent_maxrank + 1))
return;
// Check if it requires another talent
if (talentInfo->DependsOn > 0)
{
if (TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
{
bool hasEnoughRank = false;
for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
{
if (depTalentInfo->RankID[i] != 0)
if (pet->HasSpell(depTalentInfo->RankID[i]))
hasEnoughRank = true;
}
if (!hasEnoughRank)
return;
}
}
// Find out how many points we have in this field
uint32 spentPoints = 0;
uint32 tTab = talentInfo->TalentTab;
if (talentInfo->Row > 0)
{
unsigned int numRows = sTalentStore.GetNumRows();
for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
{
// Someday, someone needs to revamp
const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
if (tmpTalent) // the way talents are tracked
{
if (tmpTalent->TalentTab == tTab)
{
for (int j = 0; j < MAX_TALENT_RANK; ++j)
{
if (tmpTalent->RankID[j] != 0)
{
if (pet->HasSpell(tmpTalent->RankID[j]))
{
spentPoints += j + 1;
}
}
}
}
}
}
}
// not have required min points spent in talent tree
if (spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
return;
// spell not set in talent.dbc
uint32 spellid = talentInfo->RankID[talentRank];
if ( spellid == 0 )
{
sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
return;
}
// already known
if (pet->HasSpell(spellid))
return;
// learn! (other talent ranks will unlearned at learning)
pet->learnSpell(spellid);
DETAIL_LOG("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
}
void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
{
if (CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
{
if (apply)
SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
else
RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
}
}
void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
{
if (m_lastFallTime >= minfo.GetFallTime() || m_lastFallZ <= minfo.GetPos()->z || opcode == MSG_MOVE_FALL_LAND)
SetFallInformation(minfo.GetFallTime(), minfo.GetPos()->z);
}
void Player::UnsummonPetTemporaryIfAny(bool full)
{
Pet* minipet = GetMiniPet();
if (full && minipet)
minipet->Unsummon(PET_SAVE_AS_DELETED, this);
Pet* pet = GetPet();
if (!pet)
return;
Map* petmap = pet->GetMap();
if (!petmap)
return;
GroupPetList m_groupPetsTmp = GetPets(); // Original list may be modified in this function
if (m_groupPetsTmp.empty())
return;
for (GroupPetList::const_iterator itr = m_groupPetsTmp.begin(); itr != m_groupPetsTmp.end(); ++itr)
{
if (Pet* pet = petmap->GetPet(*itr))
{
if (!sWorld.getConfig(CONFIG_BOOL_PET_SAVE_ALL))
{
if (!GetTemporaryUnsummonedPetCount() && pet->isControlled() && !pet->isTemporarySummoned() && !pet->GetPetCounter())
{
SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber());
pet->Unsummon(PET_SAVE_AS_CURRENT, this);
}
else
if (full)
pet->Unsummon(PET_SAVE_NOT_IN_SLOT, this);
}
else
{
SetTemporaryUnsummonedPetNumber(pet->GetCharmInfo()->GetPetNumber(), pet->GetPetCounter());
if (!pet->GetPetCounter() && pet->getPetType() == HUNTER_PET)
pet->Unsummon(PET_SAVE_AS_CURRENT, this);
else
pet->Unsummon(PET_SAVE_NOT_IN_SLOT, this);
}
DEBUG_LOG("Player::UnsummonPetTemporaryIfAny tempusummon pet %s ",(*itr).GetString().c_str());
}
}
}
void Player::ResummonPetTemporaryUnSummonedIfAny()
{
if (!GetTemporaryUnsummonedPetCount())
return;
// not resummon in not appropriate state
if (IsPetNeedBeTemporaryUnsummoned())
return;
// if (GetPetGuid())
// return;
// sort petlist - 0 must be _last_
for (uint8 count = GetTemporaryUnsummonedPetCount(); count != 0; --count)
{
uint32 petnum = GetTemporaryUnsummonedPetNumber(count-1);
if (petnum == 0)
continue;
DEBUG_LOG("Player::ResummonPetTemporaryUnSummonedIfAny summon pet %u count %u",petnum, count-1);
Pet* NewPet = new Pet;
NewPet->SetPetCounter(count-1);
if(!NewPet->LoadPetFromDB(this, 0, petnum))
delete NewPet;
}
ClearTemporaryUnsummonedPetStorage();
}
uint32 Player::GetTemporaryUnsummonedPetNumber(uint8 count)
{
PetNumberList::const_iterator itr = m_temporaryUnsummonedPetNumber.find(count);
return itr != m_temporaryUnsummonedPetNumber.end() ? itr->second : 0;
};
bool Player::canSeeSpellClickOn(Creature const *c) const
{
if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
return false;
SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry());
for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
if (itr->second.IsFitToRequirements(this))
return true;
return false;
}
void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
{
*data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
*data << uint8(m_specsCount); // talent group count (0, 1 or 2)
*data << uint8(m_activeSpec); // talent group index (0 or 1)
if (m_specsCount)
{
// loop through all specs (only 1 for now)
for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
{
uint8 talentIdCount = 0;
size_t pos = data->wpos();
*data << uint8(talentIdCount); // [PH], talentIdCount
// find class talent tabs (all players have 3 talent tabs)
uint32 const* talentTabIds = GetTalentTabPages(getClass());
for(uint32 i = 0; i < 3; ++i)
{
uint32 talentTabId = talentTabIds[i];
for(PlayerTalentMap::iterator iter = m_talents[specIdx].begin(); iter != m_talents[specIdx].end(); ++iter)
{
PlayerTalent talent = (*iter).second;
if (talent.state == PLAYERSPELL_REMOVED)
continue;
// skip another tab talents
if (talent.talentEntry->TalentTab != talentTabId)
continue;
*data << uint32(talent.talentEntry->TalentID); // Talent.dbc
*data << uint8(talent.currentRank); // talentMaxRank (0-4)
++talentIdCount;
}
}
data->put<uint8>(pos, talentIdCount); // put real count
*data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
// GlyphProperties.dbc
for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
*data << uint16(m_glyphs[specIdx][i].GetId());
}
}
}
void Player::BuildPetTalentsInfoData(WorldPacket *data)
{
uint32 unspentTalentPoints = 0;
size_t pointsPos = data->wpos();
*data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
uint8 talentIdCount = 0;
size_t countPos = data->wpos();
*data << uint8(talentIdCount); // [PH], talentIdCount
Pet *pet = GetPet();
if(!pet)
return;
unspentTalentPoints = pet->GetFreeTalentPoints();
data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
CreatureInfo const *ci = pet->GetCreatureInfo();
if(!ci)
return;
CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
if(!pet_family || pet_family->petTalentType < 0)
return;
for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
{
TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
if(!talentTabInfo)
continue;
if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
continue;
for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
{
TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
if(!talentInfo)
continue;
// skip another tab talents
if (talentInfo->TalentTab != talentTabId)
continue;
// find max talent rank
int32 curtalent_maxrank = -1;
for(int32 k = 4; k > -1; --k)
{
if (talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
{
curtalent_maxrank = k;
break;
}
}
// not learned talent
if (curtalent_maxrank < 0)
continue;
*data << uint32(talentInfo->TalentID); // Talent.dbc
*data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
++talentIdCount;
}
data->put<uint8>(countPos, talentIdCount); // put real count
break;
}
}
void Player::SendTalentsInfoData(bool pet)
{
WorldPacket data(SMSG_TALENT_UPDATE, 50);
data << uint8(pet ? 1 : 0);
if (pet)
BuildPetTalentsInfoData(&data);
else
BuildPlayerTalentsInfoData(&data);
GetSession()->SendPacket(&data);
}
void Player::BuildEnchantmentsInfoData(WorldPacket *data)
{
uint32 slotUsedMask = 0;
size_t slotUsedMaskPos = data->wpos();
*data << uint32(slotUsedMask); // slotUsedMask < 0x80000
for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
if(!item)
continue;
slotUsedMask |= (1 << i);
*data << uint32(item->GetEntry()); // item entry
uint16 enchantmentMask = 0;
size_t enchantmentMaskPos = data->wpos();
*data << uint16(enchantmentMask); // enchantmentMask < 0x1000
for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
{
uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
if(!enchId)
continue;
enchantmentMask |= (1 << j);
*data << uint16(enchId); // enchantmentId?
}
data->put<uint16>(enchantmentMaskPos, enchantmentMask);
*data << uint16(item->GetItemRandomPropertyId());
*data << item->GetGuidValue(ITEM_FIELD_CREATOR).WriteAsPacked();
*data << uint32(item->GetItemSuffixFactor());
}
data->put<uint32>(slotUsedMaskPos, slotUsedMask);
}
void Player::SendEquipmentSetList()
{
uint32 count = 0;
WorldPacket data(SMSG_LOAD_EQUIPMENT_SET, 4);
size_t count_pos = data.wpos();
data << uint32(count); // count placeholder
for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
{
if (itr->second.state==EQUIPMENT_SET_DELETED)
continue;
data.appendPackGUID(itr->second.Guid);
data << uint32(itr->first);
data << itr->second.Name;
data << itr->second.IconName;
for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
{
// ignored slots stored in IgnoreMask, client wants "1" as raw GUID, so no HIGHGUID_ITEM
if (itr->second.IgnoreMask & (1 << i))
data << ObjectGuid(uint64(1)).WriteAsPacked();
else
data << ObjectGuid(HIGHGUID_ITEM, itr->second.Items[i]).WriteAsPacked();
}
++count; // client have limit but it checked at loading and set
}
data.put<uint32>(count_pos, count);
GetSession()->SendPacket(&data);
}
void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
{
if (eqset.Guid != 0)
{
bool found = false;
for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
{
if((itr->second.Guid == eqset.Guid) && (itr->first == index))
{
found = true;
break;
}
}
if(!found) // something wrong...
{
sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
return;
}
}
EquipmentSet& eqslot = m_EquipmentSets[index];
EquipmentSetUpdateState old_state = eqslot.state;
eqslot = eqset;
if (eqset.Guid == 0)
{
eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid();
WorldPacket data(SMSG_EQUIPMENT_SET_ID, 4 + 1);
data << uint32(index);
data.appendPackGUID(eqslot.Guid);
GetSession()->SendPacket(&data);
}
eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
}
void Player::_SaveEquipmentSets()
{
static SqlStatementID updSets ;
static SqlStatementID insSets ;
static SqlStatementID delSets ;
for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
{
uint32 index = itr->first;
EquipmentSet& eqset = itr->second;
switch(eqset.state)
{
case EQUIPMENT_SET_UNCHANGED:
++itr;
break; // nothing do
case EQUIPMENT_SET_CHANGED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(updSets, "UPDATE character_equipmentsets SET name=?, iconname=?, ignore_mask=?, item0=?, item1=?, item2=?, item3=?, item4=?, "
"item5=?, item6=?, item7=?, item8=?, item9=?, item10=?, item11=?, item12=?, item13=?, item14=?, "
"item15=?, item16=?, item17=?, item18=? WHERE guid=? AND setguid=? AND setindex=?");
stmt.addString(eqset.Name);
stmt.addString(eqset.IconName);
stmt.addUInt32(eqset.IgnoreMask);
for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
stmt.addUInt32(eqset.Items[i]);
stmt.addUInt32(GetGUIDLow());
stmt.addUInt64(eqset.Guid);
stmt.addUInt32(index);
stmt.Execute();
eqset.state = EQUIPMENT_SET_UNCHANGED;
++itr;
break;
}
case EQUIPMENT_SET_NEW:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(insSets, "INSERT INTO character_equipmentsets VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.addUInt32(GetGUIDLow());
stmt.addUInt64(eqset.Guid);
stmt.addUInt32(index);
stmt.addString(eqset.Name);
stmt.addString(eqset.IconName);
stmt.addUInt32(eqset.IgnoreMask);
for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
stmt.addUInt32(eqset.Items[i]);
stmt.Execute();
eqset.state = EQUIPMENT_SET_UNCHANGED;
++itr;
break;
}
case EQUIPMENT_SET_DELETED:
{
SqlStatement stmt = CharacterDatabase.CreateStatement(delSets, "DELETE FROM character_equipmentsets WHERE setguid = ?");
stmt.PExecute(eqset.Guid);
m_EquipmentSets.erase(itr++);
break;
}
}
}
}
void Player::_SaveBGData(bool forceClean)
{
if (forceClean)
m_bgData = BGData();
// nothing save
else if (!m_bgData.m_needSave)
return;
static SqlStatementID delBGData ;
static SqlStatementID insBGData ;
SqlStatement stmt = CharacterDatabase.CreateStatement(delBGData, "DELETE FROM character_battleground_data WHERE guid = ?");
stmt.PExecute(GetGUIDLow());
if (m_bgData.bgInstanceID || m_bgData.forLFG)
{
stmt = CharacterDatabase.CreateStatement(insBGData, "INSERT INTO character_battleground_data VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
/* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
stmt.addUInt32(GetGUIDLow());
stmt.addUInt32(m_bgData.bgInstanceID);
stmt.addUInt32(uint32(m_bgData.bgTeam));
stmt.addFloat(m_bgData.joinPos.coord_x);
stmt.addFloat(m_bgData.joinPos.coord_y);
stmt.addFloat(m_bgData.joinPos.coord_z);
stmt.addFloat(m_bgData.joinPos.orientation);
stmt.addUInt32(m_bgData.joinPos.mapid);
stmt.addUInt32(m_bgData.taxiPath[0]);
stmt.addUInt32(m_bgData.taxiPath[1]);
stmt.addUInt32(m_bgData.mountSpell);
stmt.Execute();
}
m_bgData.m_needSave = false;
}
void Player::DeleteEquipmentSet(uint64 setGuid)
{
for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
{
if (itr->second.Guid == setGuid)
{
if (itr->second.state == EQUIPMENT_SET_NEW)
m_EquipmentSets.erase(itr);
else
itr->second.state = EQUIPMENT_SET_DELETED;
break;
}
}
}
void Player::ActivateSpec(uint8 specNum)
{
if (GetActiveSpec() == specNum)
return;
if (specNum >= GetSpecsCount())
return;
if (Pet* pet = GetPet())
pet->Unsummon(PET_SAVE_REAGENTS, this);
SendActionButtons(2);
// prevent deletion of action buttons by client at spell unlearn or by player while spec change in progress
SendLockActionButtons();
ApplyGlyphs(false);
// copy of new talent spec (we will use it as model for converting current tlanet state to new)
PlayerTalentMap tempSpec = m_talents[specNum];
// copy old spec talents to new one, must be before spec switch to have previous spec num(as m_activeSpec)
m_talents[specNum] = m_talents[m_activeSpec];
SetActiveSpec(specNum);
// remove all talent spells that don't exist in next spec but exist in old
for (PlayerTalentMap::iterator specIter = m_talents[m_activeSpec].begin(); specIter != m_talents[m_activeSpec].end();)
{
PlayerTalent& talent = specIter->second;
if (talent.state == PLAYERSPELL_REMOVED)
{
++specIter;
continue;
}
PlayerTalentMap::iterator iterTempSpec = tempSpec.find(specIter->first);
// remove any talent rank if talent not listed in temp spec
if (iterTempSpec == tempSpec.end() || iterTempSpec->second.state == PLAYERSPELL_REMOVED)
{
TalentEntry const *talentInfo = talent.talentEntry;
for(int r = 0; r < MAX_TALENT_RANK; ++r)
if (talentInfo->RankID[r])
{
removeSpell(talentInfo->RankID[r],!IsPassiveSpell(talentInfo->RankID[r]),false);
SpellEntry const *spellInfo = sSpellStore.LookupEntry(talentInfo->RankID[r]);
for (int k = 0; k < MAX_EFFECT_INDEX; ++k)
if (spellInfo->EffectTriggerSpell[k])
removeSpell(spellInfo->EffectTriggerSpell[k]);
// if spell is a buff, remove it from group members
// TODO: this should affect all players, not only group members?
if (SpellEntry const *spellInfo = sSpellStore.LookupEntry(talentInfo->RankID[r]))
{
bool bRemoveAura = false;
for (int i = 0; i < MAX_EFFECT_INDEX; ++i)
{
if ((spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AURA ||
spellInfo->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA_RAID) &&
IsPositiveEffect(spellInfo, SpellEffectIndex(i)))
{
bRemoveAura = true;
break;
}
}
Group *group = GetGroup();
if (bRemoveAura && group)
{
for(GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
if (Player *pGroupGuy = itr->getSource())
{
if (pGroupGuy->GetObjectGuid() == GetObjectGuid())
continue;
if (SpellAuraHolderPtr holder = pGroupGuy->GetSpellAuraHolder(talentInfo->RankID[r], GetObjectGuid()))
pGroupGuy->RemoveSpellAuraHolder(holder);
}
}
}
}
}
specIter = m_talents[m_activeSpec].begin();
}
else
++specIter;
}
// now new spec data have only talents (maybe different rank) as in temp spec data, sync ranks then.
for (PlayerTalentMap::const_iterator tempIter = tempSpec.begin(); tempIter != tempSpec.end(); ++tempIter)
{
PlayerTalent const& talent = tempIter->second;
// removed state talent already unlearned in prev. loop
// but we need restore it if it deleted for finish removed-marked data in DB
if (talent.state == PLAYERSPELL_REMOVED)
{
m_talents[m_activeSpec][tempIter->first] = talent;
continue;
}
uint32 talentSpellId = talent.talentEntry->RankID[talent.currentRank];
// learn talent spells if they not in new spec (old spec copy)
// and if they have different rank
if (PlayerTalent const* cur_talent = GetKnownTalentById(tempIter->first))
{
if (cur_talent->currentRank != talent.currentRank)
learnSpell(talentSpellId, false);
}
else
learnSpell(talentSpellId, false);
// sync states - original state is changed in addSpell that learnSpell calls
PlayerTalentMap::iterator specIter = m_talents[m_activeSpec].find(tempIter->first);
if (specIter != m_talents[m_activeSpec].end())
specIter->second.state = talent.state;
else
{
sLog.outError("ActivateSpec: Talent spell %u expected to learned at spec switch but not listed in talents at final check!", talentSpellId);
// attempt resync DB state (deleted lost spell from DB)
if (talent.state != PLAYERSPELL_NEW)
{
PlayerTalent& talentNew = m_talents[m_activeSpec][tempIter->first];
talentNew = talent;
talentNew.state = PLAYERSPELL_REMOVED;
}
}
}
InitTalentForLevel();
// recheck action buttons (not checked at loading/spec copy)
ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); )
{
if (itr->second.uState != ACTIONBUTTON_DELETED)
{
// remove broken without any output (it can be not correct because talents not copied at spec creating)
if (!IsActionButtonDataValid(itr->first,itr->second.GetAction(),itr->second.GetType(), this, false))
{
removeActionButton(m_activeSpec,itr->first);
itr = currentActionButtonList.begin();
continue;
}
}
++itr;
}
ResummonPetTemporaryUnSummonedIfAny();
ApplyGlyphs(true);
SendInitialActionButtons();
Powers pw = getPowerType();
if (pw != POWER_MANA)
SetPower(POWER_MANA, 0);
SetPower(pw, 0);
}
void Player::UpdateSpecCount(uint8 count)
{
uint8 curCount = GetSpecsCount();
if (curCount == count)
return;
// maybe current spec data must be copied to 0 spec?
if (m_activeSpec >= count)
ActivateSpec(0);
// copy spec data from new specs
if (count > curCount)
{
// copy action buttons from active spec (more easy in this case iterate first by button)
ActionButtonList const& currentActionButtonList = m_actionButtons[m_activeSpec];
for(ActionButtonList::const_iterator itr = currentActionButtonList.begin(); itr != currentActionButtonList.end(); ++itr)
{
if (itr->second.uState != ACTIONBUTTON_DELETED)
{
for(uint8 spec = curCount; spec < count; ++spec)
addActionButton(spec,itr->first,itr->second.GetAction(),itr->second.GetType());
}
}
}
// delete spec data for removed specs
else if (count < curCount)
{
// delete action buttons for removed spec
for(uint8 spec = count; spec < curCount; ++spec)
{
// delete action buttons for removed spec
for(uint8 button = 0; button < MAX_ACTION_BUTTONS; ++button)
removeActionButton(spec,button);
}
}
SetSpecsCount(count);
SendTalentsInfoData(false);
}
void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
{
m_atLoginFlags &= ~f;
if (in_db_also)
CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
}
void Player::SendClearCooldown( uint32 spell_id, Unit* target )
{
if (!target)
return;
WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
data << uint32(spell_id);
data << target->GetObjectGuid();
SendDirectMessage(&data);
}
void Player::BuildTeleportAckMsg(WorldPacket& data, float x, float y, float z, float ang) const
{
MovementInfo mi = m_movementInfo;
mi.ChangePosition(x, y, z, ang);
data.Initialize(MSG_MOVE_TELEPORT_ACK, 64);
data << GetPackGUID();
data << uint32(0); // this value increments every time
data << mi;
}
bool Player::HasMovementFlag( MovementFlags f ) const
{
return m_movementInfo.HasMovementFlag(f);
}
void Player::ResetTimeSync()
{
m_timeSyncCounter = 0;
m_timeSyncTimer = 0;
m_timeSyncClient = 0;
m_timeSyncServer = WorldTimer::getMSTime();
}
void Player::SendTimeSync()
{
WorldPacket data(SMSG_TIME_SYNC_REQ, 4);
data << uint32(m_timeSyncCounter++);
GetSession()->SendPacket(&data);
// Schedule next sync in 10 sec
m_timeSyncTimer = 10000;
m_timeSyncServer = WorldTimer::getMSTime();
}
void Player::SendDuelCountdown(uint32 counter)
{
WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
data << uint32(counter); // seconds
GetSession()->SendPacket(&data);
}
bool Player::IsImmuneToSpell(SpellEntry const* spellInfo) const
{
return Unit::IsImmuneToSpell(spellInfo);
}
bool Player::IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index) const
{
switch(spellInfo->Effect[index])
{
case SPELL_EFFECT_ATTACK_ME:
return true;
default:
break;
}
switch(spellInfo->EffectApplyAuraName[index])
{
case SPELL_AURA_MOD_TAUNT:
return true;
default:
break;
}
return Unit::IsImmuneToSpellEffect(spellInfo, index);
}
void Player::SetHomebindToLocation(WorldLocation const& loc, uint32 area_id)
{
m_homebindMapId = loc.mapid;
m_homebindAreaId = area_id;
m_homebindX = loc.coord_x;
m_homebindY = loc.coord_y;
m_homebindZ = loc.coord_z;
// update sql homebind
CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow());
}
Object* Player::GetObjectByTypeMask(ObjectGuid guid, TypeMask typemask)
{
switch(guid.GetHigh())
{
case HIGHGUID_ITEM:
if (typemask & TYPEMASK_ITEM)
return GetItemByGuid(guid);
break;
case HIGHGUID_PLAYER:
if (GetObjectGuid()==guid)
return this;
if ((typemask & TYPEMASK_PLAYER) && IsInWorld())
return ObjectAccessor::FindPlayer(guid);
break;
case HIGHGUID_GAMEOBJECT:
if ((typemask & TYPEMASK_GAMEOBJECT) && IsInWorld())
return GetMap()->GetGameObject(guid);
break;
case HIGHGUID_UNIT:
case HIGHGUID_VEHICLE:
if ((typemask & TYPEMASK_UNIT) && IsInWorld())
return GetMap()->GetCreature(guid);
break;
case HIGHGUID_PET:
if ((typemask & TYPEMASK_UNIT) && IsInWorld())
return GetMap()->GetPet(guid);
break;
case HIGHGUID_DYNAMICOBJECT:
if ((typemask & TYPEMASK_DYNAMICOBJECT) && IsInWorld())
return GetMap()->GetDynamicObject(guid);
break;
case HIGHGUID_TRANSPORT:
case HIGHGUID_CORPSE:
case HIGHGUID_MO_TRANSPORT:
case HIGHGUID_INSTANCE:
case HIGHGUID_GROUP:
default:
break;
}
return NULL;
}
void Player::CompletedAchievement(AchievementEntry const* entry)
{
GetAchievementMgr().CompletedAchievement(entry);
}
void Player::CompletedAchievement(uint32 uiAchievementID)
{
GetAchievementMgr().CompletedAchievement(sAchievementStore.LookupEntry(uiAchievementID));
}
void Player::SetRestType( RestType n_r_type, uint32 areaTriggerId /*= 0*/)
{
rest_type = n_r_type;
if (rest_type == REST_TYPE_NO)
{
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
// Set player to FFA PVP when not in rested environment.
if (sWorld.IsFFAPvPRealm())
SetFFAPvP(true);
}
else
{
SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
inn_trigger_id = areaTriggerId;
time_inn_enter = time(NULL);
if (sWorld.IsFFAPvPRealm())
SetFFAPvP(false);
}
}
void Player::SetRandomWinner(bool isWinner)
{
m_IsBGRandomWinner = isWinner;
if (m_IsBGRandomWinner)
CharacterDatabase.PExecute("INSERT INTO character_battleground_random (guid) VALUES ('%u')", GetGUIDLow());
}
void Player::_LoadRandomBGStatus(QueryResult *result)
{
//QueryResult *result = CharacterDatabase.PQuery("SELECT guid FROM character_battleground_random WHERE guid = '%u'", GetGUIDLow());
if (result)
{
m_IsBGRandomWinner = true;
delete result;
}
}
// Refer-A-Friend
void Player::SendReferFriendError(ReferAFriendError err, Player * target)
{
WorldPacket data(SMSG_REFER_A_FRIEND_ERROR, 24);
data << uint32(err);
if (target && (err == ERR_REFER_A_FRIEND_NOT_IN_GROUP || err == ERR_REFER_A_FRIEND_SUMMON_OFFLINE_S))
data << target->GetName();
GetSession()->SendPacket(&data);
}
ReferAFriendError Player::GetReferFriendError(Player * target, bool summon)
{
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return summon ? ERR_REFER_A_FRIEND_SUMMON_OFFLINE_S : ERR_REFER_A_FRIEND_NO_TARGET;
if (!IsReferAFriendLinked(target))
return ERR_REFER_A_FRIEND_NOT_REFERRED_BY;
if (Group * gr1 = GetGroup())
{
Group * gr2 = target->GetGroup();
if (!gr2 || gr1->GetId() != gr2->GetId())
return ERR_REFER_A_FRIEND_NOT_IN_GROUP;
}
if (summon)
{
if (HasSpellCooldown(45927))
return ERR_REFER_A_FRIEND_SUMMON_COOLDOWN;
if (target->getLevel() > sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL))
return ERR_REFER_A_FRIEND_SUMMON_LEVEL_MAX_I;
if (MapEntry const* mEntry = sMapStore.LookupEntry(GetMapId()))
if (mEntry->Expansion() > target->GetSession()->Expansion())
return ERR_REFER_A_FRIEND_INSUF_EXPAN_LVL;
}
else
{
if (GetTeam() != target->GetTeam() && !sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP))
return ERR_REFER_A_FRIEND_DIFFERENT_FACTION;
if (getLevel() <= target->getLevel())
return ERR_REFER_A_FRIEND_TARGET_TOO_HIGH;
if (!GetGrantableLevels())
return ERR_REFER_A_FRIEND_INSUFFICIENT_GRANTABLE_LEVELS;
if (GetDistance(target) > DEFAULT_VISIBILITY_DISTANCE || !target->IsVisibleGloballyFor(this))
return ERR_REFER_A_FRIEND_TOO_FAR;
if (target->getLevel() >= sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL))
return ERR_REFER_A_FRIEND_GRANT_LEVEL_MAX_I;
}
return ERR_REFER_A_FRIEND_NONE;
}
void Player::ChangeGrantableLevels(uint8 increase)
{
if (increase)
{
if (m_GrantableLevelsCount <= int32(sWorld.getConfig(CONFIG_UINT32_RAF_MAXGRANTLEVEL) * sWorld.getConfig(CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL)))
m_GrantableLevelsCount += increase;
}
else
{
m_GrantableLevelsCount -= 1;
if (m_GrantableLevelsCount < 0)
m_GrantableLevelsCount = 0;
}
// set/unset flag - granted levels
if (m_GrantableLevelsCount > 0)
{
if (!HasByteFlag(PLAYER_FIELD_BYTES, 1, 0x01))
SetByteFlag(PLAYER_FIELD_BYTES, 1, 0x01);
}
else
{
if (HasByteFlag(PLAYER_FIELD_BYTES, 1, 0x01))
RemoveByteFlag(PLAYER_FIELD_BYTES, 1, 0x01);
}
}
bool Player::CheckRAFConditions()
{
if (Group * grp = GetGroup())
{
for(GroupReference *itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* member = itr->getSource();
if (!member || !member->isAlive())
continue;
if (GetObjectGuid() == member->GetObjectGuid())
continue;
if (member->GetAccountLinkedState() == STATE_NOT_LINKED)
continue;
if (GetDistance(member) < 100 && (getLevel() <= member->getLevel() + 4))
return true;
}
}
return false;
}
AccountLinkedState Player::GetAccountLinkedState()
{
RafLinkedList const* referredAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), true);
RafLinkedList const* referalAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), false);
if (!referredAccounts || !referalAccounts)
return STATE_NOT_LINKED;
if (!referredAccounts->empty() && !referalAccounts->empty())
return STATE_DUAL;
if (!referredAccounts->empty())
return STATE_REFER;
if (!referalAccounts->empty())
return STATE_REFERRAL;
return STATE_NOT_LINKED;
}
void Player::LoadAccountLinkedState()
{
RafLinkedList const* referredAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), true);
if (referredAccounts)
{
if (referredAccounts->size() > sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERERS))
sLog.outError("Player:RAF:Warning: loaded %u referred accounts instead of %u for player %s",referredAccounts->size(),sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERERS),GetObjectGuid().GetString().c_str());
else
DEBUG_LOG("Player:RAF: loaded %u referred accounts for player %u",referredAccounts->size(),GetObjectGuid().GetString().c_str());
}
RafLinkedList const* referalAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), false);
if (referalAccounts)
{
if (referalAccounts->size() > sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERALS))
sLog.outError("Player:RAF:Warning: loaded %u referal accounts instead of %u for player %u",referalAccounts->size(),sWorld.getConfig(CONFIG_UINT32_RAF_MAXREFERALS),GetObjectGuid().GetString().c_str());
else
DEBUG_LOG("Player:RAF: loaded %u referal accounts for player %u",referalAccounts->size(),GetObjectGuid().GetString().c_str());
}
}
bool Player::IsReferAFriendLinked(Player* target)
{
// check link this(refer) - target(referral)
RafLinkedList const* referalAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), false);
if (referalAccounts)
{
for (RafLinkedList::const_iterator itr = referalAccounts->begin(); itr != referalAccounts->end(); ++itr)
if ((*itr) == target->GetSession()->GetAccountId())
return true;
}
// check link target(refer) - this(referral)
RafLinkedList const* referredAccounts = sAccountMgr.GetRAFAccounts(GetSession()->GetAccountId(), true);
if (referredAccounts)
{
for (RafLinkedList::const_iterator itr = referredAccounts->begin(); itr != referredAccounts->end(); ++itr)
if ((*itr) == target->GetSession()->GetAccountId())
return true;
}
return false;
}
AreaLockStatus Player::GetAreaTriggerLockStatus(AreaTrigger const* at, Difficulty difficulty)
{
if (!at)
return AREA_LOCKSTATUS_UNKNOWN_ERROR;
MapEntry const* mapEntry = sMapStore.LookupEntry(at->target_mapId);
if (!mapEntry)
return AREA_LOCKSTATUS_UNKNOWN_ERROR;
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(at->target_mapId,difficulty);
if (mapEntry->IsDungeon() && !mapDiff)
return AREA_LOCKSTATUS_MISSING_DIFFICULTY;
if (isGameMaster())
return AREA_LOCKSTATUS_OK;
if (GetSession()->Expansion() < mapEntry->Expansion())
return AREA_LOCKSTATUS_INSUFFICIENT_EXPANSION;
if (getLevel() < at->requiredLevel && !sWorld.getConfig(CONFIG_BOOL_INSTANCE_IGNORE_LEVEL))
return AREA_LOCKSTATUS_TOO_LOW_LEVEL;
if (mapEntry->IsDungeon() && mapEntry->IsRaid() && !sWorld.getConfig(CONFIG_BOOL_INSTANCE_IGNORE_RAID))
if (!GetGroup() || !GetGroup()->isRaidGroup())
return AREA_LOCKSTATUS_RAID_LOCKED;
// must have one or the other, report the first one that's missing
if (at->requiredItem)
{
if (!HasItemCount(at->requiredItem, 1) &&
(!at->requiredItem2 || !HasItemCount(at->requiredItem2, 1)))
return AREA_LOCKSTATUS_MISSING_ITEM;
}
else if (at->requiredItem2 && !HasItemCount(at->requiredItem2, 1))
return AREA_LOCKSTATUS_MISSING_ITEM;
bool isRegularTargetMap = GetDifficulty(mapEntry->IsRaid()) == REGULAR_DIFFICULTY;
if (!isRegularTargetMap)
{
if (at->heroicKey)
{
if(!HasItemCount(at->heroicKey, 1) &&
(!at->heroicKey2 || !HasItemCount(at->heroicKey2, 1)))
return AREA_LOCKSTATUS_MISSING_ITEM;
}
else if (at->heroicKey2 && !HasItemCount(at->heroicKey2, 1))
return AREA_LOCKSTATUS_MISSING_ITEM;
}
if (GetTeam() == ALLIANCE)
{
if ((!isRegularTargetMap &&
(at->requiredQuestHeroicA && !GetQuestRewardStatus(at->requiredQuestHeroicA))) ||
(isRegularTargetMap &&
(at->requiredQuestA && !GetQuestRewardStatus(at->requiredQuestA))))
return AREA_LOCKSTATUS_QUEST_NOT_COMPLETED;
}
else if (GetTeam() == HORDE)
{
if ((!isRegularTargetMap &&
(at->requiredQuestHeroicH && !GetQuestRewardStatus(at->requiredQuestHeroicH))) ||
(isRegularTargetMap &&
(at->requiredQuestH && !GetQuestRewardStatus(at->requiredQuestH))))
return AREA_LOCKSTATUS_QUEST_NOT_COMPLETED;
}
uint32 achievCheck = 0;
if (difficulty == RAID_DIFFICULTY_10MAN_HEROIC)
achievCheck = at->achiev0;
else if (difficulty == RAID_DIFFICULTY_25MAN_HEROIC)
achievCheck = at->achiev1;
if (achievCheck)
{
bool bHasAchiev = false;
if (GetAchievementMgr().HasAchievement(achievCheck))
bHasAchiev = true;
else if (Group* group = GetGroup())
{
for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
{
Player* member = itr->getSource();
if (member && member->IsInWorld())
if (member->GetAchievementMgr().HasAchievement(achievCheck))
bHasAchiev = true;
}
}
if (!bHasAchiev)
return AREA_LOCKSTATUS_QUEST_NOT_COMPLETED;
}
// If the map is not created, assume it is possible to enter it.
DungeonPersistentState* state = GetBoundInstanceSaveForSelfOrGroup(at->target_mapId);
Map* map = sMapMgr.FindMap(at->target_mapId, state ? state->GetInstanceId() : 0);
if (map && at->combatMode == 1)
{
if (map->GetInstanceData() && map->GetInstanceData()->IsEncounterInProgress())
{
DEBUG_LOG("MAP: Player '%s' can't enter instance '%s' while an encounter is in progress.", GetObjectGuid().GetString().c_str(), map->GetMapName());
return AREA_LOCKSTATUS_ZONE_IN_COMBAT;
}
}
if (map && map->IsDungeon())
{
// cannot enter if the instance is full (player cap), GMs don't count
if (((DungeonMap*)map)->GetPlayersCountExceptGMs() >= ((DungeonMap*)map)->GetMaxPlayers())
return AREA_LOCKSTATUS_INSTANCE_IS_FULL;
InstancePlayerBind* pBind = GetBoundInstance(at->target_mapId, GetDifficulty(mapEntry->IsRaid()));
if (pBind && pBind->perm && pBind->state != state)
return AREA_LOCKSTATUS_HAS_BIND;
if (pBind && pBind->perm && pBind->state != map->GetPersistentState())
return AREA_LOCKSTATUS_HAS_BIND;
}
return AREA_LOCKSTATUS_OK;
};
AreaLockStatus Player::GetAreaLockStatus(uint32 mapId, Difficulty difficulty)
{
return GetAreaTriggerLockStatus(sObjectMgr.GetMapEntranceTrigger(mapId), difficulty);
};
bool Player::CheckTransferPossibility(uint32 mapId)
{
if (mapId == GetMapId())
return true;
MapEntry const* targetMapEntry = sMapStore.LookupEntry(mapId);
if (!targetMapEntry)
{
sLog.outError("Player::CheckTransferPossibility: player %s try teleport to map %u, but map not exists!", GetObjectGuid().GetString().c_str(), mapId);
return false;
}
// Battleground requirements checked in another place
if(InBattleGround() && targetMapEntry->IsBattleGroundOrArena())
return true;
AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(mapId);
if (!at)
{
if (isGameMaster())
{
sLog.outDetail("Player::CheckTransferPossibility: gamemaster %s try teleport to map %u, but entrance trigger not exists (possible for some test maps).", GetObjectGuid().GetString().c_str(), mapId);
return true;
}
if (targetMapEntry->IsContinent())
{
if (GetSession()->Expansion() < targetMapEntry->Expansion())
{
sLog.outError("Player::CheckTransferPossibility: player %s try teleport to map %u, but not has sufficient expansion (%u instead of %u)", GetObjectGuid().GetString().c_str(), mapId, GetSession()->Expansion(), targetMapEntry->Expansion());
return false;
}
return true;
}
sLog.outError("Player::CheckTransferPossibility: player %s try teleport to map %u, but entrance trigger not exists!", GetObjectGuid().GetString().c_str(), mapId);
return false;
}
return CheckTransferPossibility(at, targetMapEntry->IsContinent());
}
bool Player::CheckTransferPossibility(AreaTrigger const*& at, bool b_onlyMainReq)
{
if (!at)
return false;
if (at->target_mapId == GetMapId())
return true;
MapEntry const* targetMapEntry = sMapStore.LookupEntry(at->target_mapId);
if (!targetMapEntry)
return false;
if (!isGameMaster())
{
// ghost resurrected at enter attempt to dungeon with corpse (including fail enter cases)
if (!isAlive() && targetMapEntry->IsDungeon())
{
int32 corpseMapId = 0;
if (Corpse *corpse = GetCorpse())
corpseMapId = corpse->GetMapId();
// check back way from corpse to entrance
uint32 instance_map = corpseMapId;
do
{
// most often fast case
if (instance_map == targetMapEntry->MapID)
break;
InstanceTemplate const* instance = ObjectMgr::GetInstanceTemplate(instance_map);
instance_map = instance ? instance->parent : 0;
}
while (instance_map);
// corpse not in dungeon or some linked deep dungeons
if (!instance_map)
{
WorldPacket data(SMSG_AREA_TRIGGER_NO_CORPSE);
GetSession()->SendPacket(&data);
return false;
}
// need find areatrigger to inner dungeon for landing point
if (at->target_mapId != corpseMapId)
{
if (AreaTrigger const* corpseAt = sObjectMgr.GetMapEntranceTrigger(corpseMapId))
{
targetMapEntry = sMapStore.LookupEntry(corpseAt->target_mapId);
at = corpseAt;
}
}
// now we can resurrect player, and then check teleport requirements
ResurrectPlayer(0.5f);
SpawnCorpseBones();
}
}
AreaLockStatus status = GetAreaTriggerLockStatus(at, GetDifficulty(targetMapEntry->IsRaid()));
DEBUG_LOG("Player::CheckTransferPossibility %s check lock status of map %u (difficulty %u), result is %u", GetObjectGuid().GetString().c_str(), at->target_mapId, GetDifficulty(targetMapEntry->IsRaid()), status);
if (b_onlyMainReq)
{
switch (status)
{
case AREA_LOCKSTATUS_MISSING_ITEM:
case AREA_LOCKSTATUS_QUEST_NOT_COMPLETED:
case AREA_LOCKSTATUS_INSTANCE_IS_FULL:
case AREA_LOCKSTATUS_ZONE_IN_COMBAT:
case AREA_LOCKSTATUS_TOO_LOW_LEVEL:
return true;
default:
break;
}
}
switch (status)
{
case AREA_LOCKSTATUS_OK:
return true;
case AREA_LOCKSTATUS_TOO_LOW_LEVEL:
GetSession()->SendAreaTriggerMessage(GetSession()->GetMangosString(LANG_LEVEL_MINREQUIRED), at->requiredLevel);
return false;
case AREA_LOCKSTATUS_ZONE_IN_COMBAT:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_ZONE_IN_COMBAT);
return false;
case AREA_LOCKSTATUS_INSTANCE_IS_FULL:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_MAX_PLAYERS);
return false;
case AREA_LOCKSTATUS_QUEST_NOT_COMPLETED:
if(at->target_mapId == 269)
{
GetSession()->SendAreaTriggerMessage("%s", at->requiredFailedText.c_str());
return false;
}
// No break here!
case AREA_LOCKSTATUS_MISSING_ITEM:
{
MapDifficultyEntry const* mapDiff = GetMapDifficultyData(targetMapEntry->MapID,GetDifficulty(targetMapEntry->IsRaid()));
if (mapDiff && mapDiff->mapDifficultyFlags & MAP_DIFFICULTY_FLAG_CONDITION)
{
GetSession()->SendAreaTriggerMessage("%s", mapDiff->areaTriggerText[GetSession()->GetSessionDbcLocale()]);
}
// do not report anything for quest areatriggers
DEBUG_LOG("HandleAreaTriggerOpcode: LockAreaStatus %u, do action", uint8(GetAreaTriggerLockStatus(at, GetDifficulty(targetMapEntry->IsRaid()))));
return false;
}
case AREA_LOCKSTATUS_MISSING_DIFFICULTY:
{
Difficulty difficulty = GetDifficulty(targetMapEntry->IsRaid());
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_DIFFICULTY, difficulty > RAID_DIFFICULTY_10MAN_HEROIC ? RAID_DIFFICULTY_10MAN_HEROIC : difficulty);
return false;
}
case AREA_LOCKSTATUS_INSUFFICIENT_EXPANSION:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_INSUF_EXPAN_LVL, targetMapEntry->Expansion());
return false;
case AREA_LOCKSTATUS_NOT_ALLOWED:
case AREA_LOCKSTATUS_HAS_BIND:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_MAP_NOT_ALLOWED);
return false;
// TODO: messages for other cases
case AREA_LOCKSTATUS_RAID_LOCKED:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_NEED_GROUP);
return false;
// TODO: messages for other cases
case AREA_LOCKSTATUS_UNKNOWN_ERROR:
default:
SendTransferAborted(at->target_mapId, TRANSFER_ABORT_ERROR);
sLog.outError("Player::CheckTransferPossibility player %s has unhandled AreaLockStatus %u in map %u (difficulty %u), do nothing", GetObjectGuid().GetString().c_str(), status, at->target_mapId, GetDifficulty(targetMapEntry->IsRaid()));
return false;
}
return false;
};
uint32 Player::GetEquipGearScore(bool withBags, bool withBank)
{
if (withBags && withBank && m_cachedGS > 0)
return m_cachedGS;
GearScoreVec gearScore (EQUIPMENT_SLOT_END);
uint32 twoHandScore = 0;
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
_fillGearScoreData(item, &gearScore, twoHandScore);
}
if (withBags)
{
// check inventory
for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
_fillGearScoreData(item, &gearScore, twoHandScore);
}
// check bags
for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
{
if(Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
{
if (Item* item2 = pBag->GetItemByPos(j))
_fillGearScoreData(item2, &gearScore, twoHandScore);
}
}
}
}
if (withBank)
{
for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
_fillGearScoreData(item, &gearScore, twoHandScore);
}
for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
{
if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
{
if (item->IsBag())
{
Bag* bag = (Bag*)item;
for (uint8 j = 0; j < bag->GetBagSize(); ++j)
{
if (Item* item2 = bag->GetItemByPos(j))
_fillGearScoreData(item2, &gearScore, twoHandScore);
}
}
}
}
}
uint8 count = EQUIPMENT_SLOT_END - 2; // ignore body and tabard slots
uint32 sum = 0;
// check if 2h hand is higher level than main hand + off hand
if (gearScore[EQUIPMENT_SLOT_MAINHAND] + gearScore[EQUIPMENT_SLOT_OFFHAND] < twoHandScore * 2)
{
gearScore[EQUIPMENT_SLOT_OFFHAND] = 0; // off hand is ignored in calculations if 2h weapon has higher score
--count;
gearScore[EQUIPMENT_SLOT_MAINHAND] = twoHandScore;
}
for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
{
sum += gearScore[i];
}
if (count)
{
uint32 res = uint32(sum / count);
DEBUG_LOG("Player: calculating gear score for %u. Result is %u", GetObjectGuid().GetCounter(), res);
if (withBags && withBank)
m_cachedGS = res;
return res;
}
else
return 0;
}
void Player::_fillGearScoreData(Item* item, GearScoreVec* gearScore, uint32& twoHandScore)
{
if (!item)
return;
if (CanUseItem(item->GetProto()) != EQUIP_ERR_OK)
return;
uint8 type = item->GetProto()->InventoryType;
uint32 level = item->GetProto()->ItemLevel;
switch (type)
{
case INVTYPE_2HWEAPON:
twoHandScore = std::max(twoHandScore, level);
break;
case INVTYPE_WEAPON:
case INVTYPE_WEAPONMAINHAND:
(*gearScore)[SLOT_MAIN_HAND] = std::max((*gearScore)[SLOT_MAIN_HAND], level);
break;
case INVTYPE_SHIELD:
case INVTYPE_WEAPONOFFHAND:
(*gearScore)[EQUIPMENT_SLOT_OFFHAND] = std::max((*gearScore)[EQUIPMENT_SLOT_OFFHAND], level);
break;
case INVTYPE_THROWN:
case INVTYPE_RANGEDRIGHT:
case INVTYPE_RANGED:
case INVTYPE_QUIVER:
case INVTYPE_RELIC:
(*gearScore)[EQUIPMENT_SLOT_RANGED] = std::max((*gearScore)[EQUIPMENT_SLOT_RANGED], level);
break;
case INVTYPE_HEAD:
(*gearScore)[EQUIPMENT_SLOT_HEAD] = std::max((*gearScore)[EQUIPMENT_SLOT_HEAD], level);
break;
case INVTYPE_NECK:
(*gearScore)[EQUIPMENT_SLOT_NECK] = std::max((*gearScore)[EQUIPMENT_SLOT_NECK], level);
break;
case INVTYPE_SHOULDERS:
(*gearScore)[EQUIPMENT_SLOT_SHOULDERS] = std::max((*gearScore)[EQUIPMENT_SLOT_SHOULDERS], level);
break;
case INVTYPE_BODY:
(*gearScore)[EQUIPMENT_SLOT_BODY] = std::max((*gearScore)[EQUIPMENT_SLOT_BODY], level);
break;
case INVTYPE_CHEST:
(*gearScore)[EQUIPMENT_SLOT_CHEST] = std::max((*gearScore)[EQUIPMENT_SLOT_CHEST], level);
break;
case INVTYPE_WAIST:
(*gearScore)[EQUIPMENT_SLOT_WAIST] = std::max((*gearScore)[EQUIPMENT_SLOT_WAIST], level);
break;
case INVTYPE_LEGS:
(*gearScore)[EQUIPMENT_SLOT_LEGS] = std::max((*gearScore)[EQUIPMENT_SLOT_LEGS], level);
break;
case INVTYPE_FEET:
(*gearScore)[EQUIPMENT_SLOT_FEET] = std::max((*gearScore)[EQUIPMENT_SLOT_FEET], level);
break;
case INVTYPE_WRISTS:
(*gearScore)[EQUIPMENT_SLOT_WRISTS] = std::max((*gearScore)[EQUIPMENT_SLOT_WRISTS], level);
break;
case INVTYPE_HANDS:
(*gearScore)[EQUIPMENT_SLOT_HEAD] = std::max((*gearScore)[EQUIPMENT_SLOT_HEAD], level);
break;
// equipped gear score check uses both rings and trinkets for calculation, assume that for bags/banks it is the same
// with keeping second highest score at second slot
case INVTYPE_FINGER:
{
if ((*gearScore)[EQUIPMENT_SLOT_FINGER1] < level)
{
(*gearScore)[EQUIPMENT_SLOT_FINGER2] = (*gearScore)[EQUIPMENT_SLOT_FINGER1];
(*gearScore)[EQUIPMENT_SLOT_FINGER1] = level;
}
else if ((*gearScore)[EQUIPMENT_SLOT_FINGER2] < level)
(*gearScore)[EQUIPMENT_SLOT_FINGER2] = level;
break;
}
case INVTYPE_TRINKET:
{
if ((*gearScore)[EQUIPMENT_SLOT_TRINKET1] < level)
{
(*gearScore)[EQUIPMENT_SLOT_TRINKET2] = (*gearScore)[EQUIPMENT_SLOT_TRINKET1];
(*gearScore)[EQUIPMENT_SLOT_TRINKET1] = level;
}
else if ((*gearScore)[EQUIPMENT_SLOT_TRINKET2] < level)
(*gearScore)[EQUIPMENT_SLOT_TRINKET2] = level;
break;
}
case INVTYPE_CLOAK:
(*gearScore)[EQUIPMENT_SLOT_BACK] = std::max((*gearScore)[EQUIPMENT_SLOT_BACK], level);
break;
default:
break;
}
}
uint8 Player::GetTalentsCount(uint8 tab)
{
if (tab >2)
return 0;
if (m_cachedTC[tab] > 0)
return m_cachedTC[tab];
uint8 talentCount = 0;
uint32 const* talentTabIds = GetTalentTabPages(getClass());
uint32 talentTabId = talentTabIds[tab];
for (PlayerTalentMap::iterator iter = m_talents[m_activeSpec].begin(); iter != m_talents[m_activeSpec].end(); ++iter)
{
PlayerTalent talent = (*iter).second;
if (talent.state == PLAYERSPELL_REMOVED)
continue;
// skip another tab talents
if (talent.talentEntry->TalentTab != talentTabId)
continue;
talentCount += talent.currentRank + 1;
}
m_cachedTC[tab] = talentCount;
return talentCount;
}
uint32 Player::GetModelForForm(SpellShapeshiftFormEntry const* ssEntry) const
{
ShapeshiftForm form = ShapeshiftForm(ssEntry->ID);
Team team = TeamForRace(getRace());
uint32 modelid = 0;
// The following are the different shapeshifting models for cat/bear forms according
// to hair color for druids and skin tone for tauren introduced in patch 3.2
if (form == FORM_CAT || form == FORM_BEAR || form == FORM_DIREBEAR)
{
if (team == ALLIANCE)
{
uint8 hairColour = GetByteValue(PLAYER_BYTES, 3);
if (form == FORM_CAT)
{
if (hairColour >= 0 && hairColour <= 2) modelid = 29407;
else if (hairColour == 3 || hairColour == 5) modelid = 29405;
else if (hairColour == 6) modelid = 892;
else if (hairColour == 7) modelid = 29406;
else if (hairColour == 4) modelid = 29408;
}
else // form == FORM_BEAR || form == FORM_DIREBEAR
{
if (hairColour >= 0 && hairColour <= 2) modelid = 29413;
else if (hairColour == 3 || hairColour == 5) modelid = 29415;
else if (hairColour == 6) modelid = 29414;
else if (hairColour == 7) modelid = 29417;
else if (hairColour == 4) modelid = 29416;
}
}
else if (team == HORDE)
{
uint8 skinColour = GetByteValue(PLAYER_BYTES, 0);
if (getGender() == GENDER_MALE)
{
if (form == FORM_CAT)
{
if (skinColour >= 0 && skinColour <= 5) modelid = 29412;
else if (skinColour >= 6 && skinColour <= 8) modelid = 29411;
else if (skinColour >= 9 && skinColour <= 11) modelid = 29410;
else if (skinColour >= 12 && skinColour <= 14 || skinColour == 18) modelid = 29409;
else if (skinColour >= 15 && skinColour <= 17) modelid = 8571;
}
else // form == FORM_BEAR || form == FORM_DIREBEAR
{
if (skinColour >= 0 && skinColour <= 2) modelid = 29418;
else if (skinColour >= 3 && skinColour <= 5 || skinColour >= 12 && skinColour <= 14) modelid = 29419;
else if (skinColour >= 9 && skinColour <= 11 || skinColour >= 15 && skinColour <= 17) modelid = 29420;
else if (skinColour >= 6 && skinColour <= 8) modelid = 2289;
else if (skinColour == 18) modelid = 29421;
}
}
else // getGender() == GENDER_FEMALE
{
if (form == FORM_CAT)
{
if (skinColour >= 0 && skinColour <= 3) modelid = 29412;
else if (skinColour == 4 || skinColour == 5) modelid = 29411;
else if (skinColour == 6 || skinColour == 7) modelid = 29410;
else if (skinColour == 8 || skinColour == 9) modelid = 8571;
else if (skinColour == 10) modelid = 29409;
}
else // form == FORM_BEAR || form == FORM_DIREBEAR
{
if (skinColour == 0 || skinColour == 1) modelid = 29418;
else if (skinColour == 2 || skinColour == 3) modelid = 29419;
else if (skinColour == 4 || skinColour == 5) modelid = 2289;
else if (skinColour >= 6 && skinColour <= 9) modelid = 29420;
else if (skinColour == 10) modelid = 29421;
}
}
}
}
else if (team == HORDE)
{
if (ssEntry->modelID_H)
modelid = ssEntry->modelID_H; // 3.2.3 only the moonkin form has this information
else // get model for race
modelid = sObjectMgr.GetModelForRace(ssEntry->modelID_A, getRaceMask());
}
// nothing found in above, so use default
if (!modelid)
modelid = ssEntry->modelID_A;
return modelid;
}
float Player::GetCollisionHeight(bool mounted)
{
if (mounted)
{
CreatureDisplayInfoEntry const* mountDisplayInfo = sCreatureDisplayInfoStore.LookupEntry(GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID));
if (!mountDisplayInfo)
return GetCollisionHeight(false);
CreatureModelDataEntry const* mountModelData = sCreatureModelDataStore.LookupEntry(mountDisplayInfo->ModelId);
if (!mountModelData)
return GetCollisionHeight(false);
CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId());
MANGOS_ASSERT(displayInfo);
CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId);
MANGOS_ASSERT(modelData);
float scaleMod = GetFloatValue(OBJECT_FIELD_SCALE_X); // 99% sure about this
return scaleMod * mountModelData->MountHeight + modelData->CollisionHeight * 0.5f;
}
else
{
//! Dismounting case - use basic default model data
CreatureDisplayInfoEntry const* displayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId());
MANGOS_ASSERT(displayInfo);
CreatureModelDataEntry const* modelData = sCreatureModelDataStore.LookupEntry(displayInfo->ModelId);
MANGOS_ASSERT(modelData);
return modelData->CollisionHeight;
}
}
void Player::InterruptTaxiFlying()
{
// stop flight if need
if (IsTaxiFlying())
{
GetUnitStateMgr().DropAction(UNIT_ACTION_TAXI);
m_taxi.ClearTaxiDestinations();
GetUnitStateMgr().InitDefaults();
}
// save only in non-flight case
else
SaveRecallPosition();
}
| Java |
package com.javarush.task.task11.task1109;
/*
Как кошка с собакой
*/
public class Solution {
public static void main(String[] args) {
Cat cat = new Cat("Vaska", 5);
Dog dog = new Dog("Sharik", 4);
cat.isDogNear(dog);
dog.isCatNear(cat);
}
public static class Cat {
private String name;
private int speed;
public Cat(String name, int speed) {
this.name = name;
this.speed = speed;
}
private String getName() {
return name;
}
private int getSpeed() {
return speed;
}
public boolean isDogNear(Dog dog) {
return this.speed > dog.getSpeed();
}
}
public static class Dog {
private String name;
private int speed;
public Dog(String name, int speed) {
this.name = name;
this.speed = speed;
}
private String getName() {
return name;
}
private int getSpeed() {
return speed;
}
public boolean isCatNear(Cat cat) {
return this.speed > cat.getSpeed();
}
}
} | Java |
#!/usr/bin/perl
use warnings;
use strict;
use hdpTools;
use Annotation::Annotation;
my $config=$ARGV[0];
die "Usage: perl $0 <config file>\n\n" unless defined $config;
my $Annotation=Annotation->new($config);
warn "Loading GFF\n";
$Annotation->loadAnnotation();
warn "Loading Genome\n";
$Annotation->loadGenome();
warn "Loading Homology\n";
$Annotation->addHomologies();
my @targets=@{$Annotation->getHomologyTargets()};
my $allKids=$Annotation->getAllParentsOfID("PAC:28400253.CDS.3");
foreach my $child (@$allKids){
print $child."\n";
}
| Java |
<?php
/**
* Lost password form
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
?>
<?php wc_print_notices(); ?>
<section id="content">
<form method="post" class="form lost_reset_password">
<?php if( 'lost_password' == $args['form'] ) : ?>
<p class="red"><?php echo apply_filters( 'woocommerce_lost_password_message', __( 'Lost your password? Please enter your username or email address. You will receive a link to create a new password via email.', 'woocommerce' ) ); ?></p>
<!--<p class="form-row form-row-first"><label for="user_login"><?php _e( 'Username or email', 'woocommerce' ); ?></label> <input class="input-text" type="text" name="user_login" id="user_login" /></p>-->
<div class="col">
<div class="left">
<input class="input-text" type="text" name="user_login" id="user_login" placeholder="Username or email" />
</div>
</div>
<?php else : ?>
<p><?php echo apply_filters( 'woocommerce_reset_password_message', __( 'Enter a new password below.', 'woocommerce') ); ?></p>
<!--
<p class="form-row form-row-first">
<label for="password_1"><?php _e( 'New password', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="password" class="email" name="password_1" id="password_1" />
</p>
<p class="form-row form-row-last">
<label for="password_2"><?php _e( 'Re-enter new password', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="password" class="input-text" name="password_2" id="password_2" />
</p>-->
<div class="col">
<div class="left">
<input type="password" class="email" name="password_1" id="password_1" placeholder="Password*" />
</div>
</div>
<div class="col">
<div class="left">
<input type="password" class="input-text" name="password_2" id="password_2" placeholder="Re-enter Password*" />
</div>
</div>
<input type="hidden" name="reset_key" value="<?php echo isset( $args['key'] ) ? $args['key'] : ''; ?>" />
<input type="hidden" name="reset_login" value="<?php echo isset( $args['login'] ) ? $args['login'] : ''; ?>" />
<?php endif; ?>
<div class="clear"></div>
<div class="col">
<div class="left">
<input type="submit" class="button" name="wc_reset_password" value="<?php echo 'lost_password' == $args['form'] ? __( 'Reset Password', 'woocommerce' ) : __( 'Save', 'woocommerce' ); ?>" />
</div>
</div>
<!--<p class="form-row"><input type="submit" class="button" name="wc_reset_password" value="<?php echo 'lost_password' == $args['form'] ? __( 'Reset Password', 'woocommerce' ) : __( 'Save', 'woocommerce' ); ?>" /></p>-->
<?php wp_nonce_field( $args['form'] ); ?>
</form>
</section>
<script type="text/javascript">
jQuery('#reg_passmail').html('');
jQuery('#reg_passmail').append('<div class="col"></div>');
</script> | Java |
/*
* Demo on how to use /dev/crypto device for ciphering.
*
* Placed under public domain.
*
*/
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <crypto/cryptodev.h>
#include "asynchelper.h"
#include "testhelper.h"
#ifdef ENABLE_ASYNC
static int debug = 0;
#define DATA_SIZE 8*1024
#define BLOCK_SIZE 16
#define KEY_SIZE 16
static int
test_crypto(int cfd)
{
uint8_t plaintext_raw[DATA_SIZE + 63], *plaintext;
uint8_t ciphertext_raw[DATA_SIZE + 63], *ciphertext;
uint8_t iv[BLOCK_SIZE];
uint8_t key[KEY_SIZE];
struct session_op sess;
#ifdef CIOCGSESSINFO
struct session_info_op siop;
#endif
struct crypt_op cryp;
if (debug) printf("running %s\n", __func__);
memset(&sess, 0, sizeof(sess));
memset(&cryp, 0, sizeof(cryp));
memset(key, 0x33, sizeof(key));
memset(iv, 0x03, sizeof(iv));
/* Get crypto session for AES128 */
sess.cipher = CRYPTO_AES_CBC;
sess.keylen = KEY_SIZE;
sess.key = key;
if (ioctl(cfd, CIOCGSESSION, &sess)) {
perror("ioctl(CIOCGSESSION)");
return 1;
}
if (debug) printf("%s: got the session\n", __func__);
#ifdef CIOCGSESSINFO
siop.ses = sess.ses;
if (ioctl(cfd, CIOCGSESSINFO, &siop)) {
perror("ioctl(CIOCGSESSINFO)");
return 1;
}
plaintext = buf_align(plaintext_raw, siop.alignmask);
ciphertext = buf_align(ciphertext_raw, siop.alignmask);
#else
plaintext = plaintext_raw;
ciphertext = ciphertext_raw;
#endif
memset(plaintext, 0x15, DATA_SIZE);
/* Encrypt data.in to data.encrypted */
cryp.ses = sess.ses;
cryp.len = DATA_SIZE;
cryp.src = plaintext;
cryp.dst = ciphertext;
cryp.iv = iv;
cryp.op = COP_ENCRYPT;
DO_OR_DIE(do_async_crypt(cfd, &cryp), 0);
DO_OR_DIE(do_async_fetch(cfd, &cryp), 0);
if (debug) printf("%s: data encrypted\n", __func__);
if (ioctl(cfd, CIOCFSESSION, &sess.ses)) {
perror("ioctl(CIOCFSESSION)");
return 1;
}
if (debug) printf("%s: session finished\n", __func__);
if (ioctl(cfd, CIOCGSESSION, &sess)) {
perror("ioctl(CIOCGSESSION)");
return 1;
}
if (debug) printf("%s: got new session\n", __func__);
/* Decrypt data.encrypted to data.decrypted */
cryp.ses = sess.ses;
cryp.len = DATA_SIZE;
cryp.src = ciphertext;
cryp.dst = ciphertext;
cryp.iv = iv;
cryp.op = COP_DECRYPT;
DO_OR_DIE(do_async_crypt(cfd, &cryp), 0);
DO_OR_DIE(do_async_fetch(cfd, &cryp), 0);
if (debug) printf("%s: data encrypted\n", __func__);
/* Verify the result */
if (memcmp(plaintext, ciphertext, DATA_SIZE) != 0) {
fprintf(stderr,
"FAIL: Decrypted data are different from the input data.\n");
return 1;
} else if (debug)
printf("Test passed\n");
/* Finish crypto session */
if (ioctl(cfd, CIOCFSESSION, &sess.ses)) {
perror("ioctl(CIOCFSESSION)");
return 1;
}
return 0;
}
static int test_aes(int cfd)
{
uint8_t plaintext1_raw[BLOCK_SIZE + 63], *plaintext1;
uint8_t ciphertext1[BLOCK_SIZE] = { 0xdf, 0x55, 0x6a, 0x33, 0x43, 0x8d, 0xb8, 0x7b, 0xc4, 0x1b, 0x17, 0x52, 0xc5, 0x5e, 0x5e, 0x49 };
uint8_t iv1[BLOCK_SIZE];
uint8_t key1[KEY_SIZE] = { 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
uint8_t plaintext2_data[BLOCK_SIZE] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00 };
uint8_t plaintext2_raw[BLOCK_SIZE + 63], *plaintext2;
uint8_t ciphertext2[BLOCK_SIZE] = { 0xb7, 0x97, 0x2b, 0x39, 0x41, 0xc4, 0x4b, 0x90, 0xaf, 0xa7, 0xb2, 0x64, 0xbf, 0xba, 0x73, 0x87 };
uint8_t iv2[BLOCK_SIZE];
uint8_t key2[KEY_SIZE];
struct session_op sess1, sess2;
#ifdef CIOCGSESSINFO
struct session_info_op siop1, siop2;
#endif
struct crypt_op cryp1, cryp2;
memset(&sess1, 0, sizeof(sess1));
memset(&sess2, 0, sizeof(sess2));
memset(&cryp1, 0, sizeof(cryp1));
memset(&cryp2, 0, sizeof(cryp2));
/* Get crypto session for AES128 */
sess1.cipher = CRYPTO_AES_CBC;
sess1.keylen = KEY_SIZE;
sess1.key = key1;
if (ioctl(cfd, CIOCGSESSION, &sess1)) {
perror("ioctl(CIOCGSESSION)");
return 1;
}
#ifdef CIOCGSESSINFO
siop1.ses = sess1.ses;
if (ioctl(cfd, CIOCGSESSINFO, &siop1)) {
perror("ioctl(CIOCGSESSINFO)");
return 1;
}
plaintext1 = buf_align(plaintext1_raw, siop1.alignmask);
#else
plaintext1 = plaintext1_raw;
#endif
memset(plaintext1, 0x0, BLOCK_SIZE);
memset(iv1, 0x0, sizeof(iv1));
memset(key2, 0x0, sizeof(key2));
/* Get second crypto session for AES128 */
sess2.cipher = CRYPTO_AES_CBC;
sess2.keylen = KEY_SIZE;
sess2.key = key2;
if (ioctl(cfd, CIOCGSESSION, &sess2)) {
perror("ioctl(CIOCGSESSION)");
return 1;
}
#ifdef CIOCGSESSINFO
siop2.ses = sess2.ses;
if (ioctl(cfd, CIOCGSESSINFO, &siop2)) {
perror("ioctl(CIOCGSESSINFO)");
return 1;
}
plaintext2 = buf_align(plaintext2_raw, siop2.alignmask);
#else
plaintext2 = plaintext2_raw;
#endif
memcpy(plaintext2, plaintext2_data, BLOCK_SIZE);
/* Encrypt data.in to data.encrypted */
cryp1.ses = sess1.ses;
cryp1.len = BLOCK_SIZE;
cryp1.src = plaintext1;
cryp1.dst = plaintext1;
cryp1.iv = iv1;
cryp1.op = COP_ENCRYPT;
DO_OR_DIE(do_async_crypt(cfd, &cryp1), 0);
if (debug) printf("cryp1 written out\n");
memset(iv2, 0x0, sizeof(iv2));
/* Encrypt data.in to data.encrypted */
cryp2.ses = sess2.ses;
cryp2.len = BLOCK_SIZE;
cryp2.src = plaintext2;
cryp2.dst = plaintext2;
cryp2.iv = iv2;
cryp2.op = COP_ENCRYPT;
DO_OR_DIE(do_async_crypt(cfd, &cryp2), 0);
if (debug) printf("cryp2 written out\n");
DO_OR_DIE(do_async_fetch(cfd, &cryp1), 0);
DO_OR_DIE(do_async_fetch(cfd, &cryp2), 0);
if (debug) printf("cryp1 + cryp2 successfully read\n");
/* Verify the result */
if (memcmp(plaintext1, ciphertext1, BLOCK_SIZE) != 0) {
int i;
fprintf(stderr,
"FAIL: Decrypted data are different from the input data.\n");
printf("plaintext:");
for (i = 0; i < BLOCK_SIZE; i++) {
if ((i % 30) == 0)
printf("\n");
printf("%02x ", plaintext1[i]);
}
printf("ciphertext:");
for (i = 0; i < BLOCK_SIZE; i++) {
if ((i % 30) == 0)
printf("\n");
printf("%02x ", ciphertext1[i]);
}
printf("\n");
return 1;
} else {
if (debug) printf("result 1 passed\n");
}
/* Test 2 */
/* Verify the result */
if (memcmp(plaintext2, ciphertext2, BLOCK_SIZE) != 0) {
int i;
fprintf(stderr,
"FAIL: Decrypted data are different from the input data.\n");
printf("plaintext:");
for (i = 0; i < BLOCK_SIZE; i++) {
if ((i % 30) == 0)
printf("\n");
printf("%02x ", plaintext2[i]);
}
printf("ciphertext:");
for (i = 0; i < BLOCK_SIZE; i++) {
if ((i % 30) == 0)
printf("\n");
printf("%02x ", ciphertext2[i]);
}
printf("\n");
return 1;
} else {
if (debug) printf("result 2 passed\n");
}
if (debug) printf("AES Test passed\n");
/* Finish crypto session */
if (ioctl(cfd, CIOCFSESSION, &sess1.ses)) {
perror("ioctl(CIOCFSESSION)");
return 1;
}
if (ioctl(cfd, CIOCFSESSION, &sess2.ses)) {
perror("ioctl(CIOCFSESSION)");
return 1;
}
return 0;
}
int
main(int argc, char** argv)
{
int fd = -1, cfd = -1;
if (argc > 1) debug = 1;
/* Open the crypto device */
fd = open("/dev/crypto", O_RDWR, 0);
if (fd < 0) {
perror("open(/dev/crypto)");
return 1;
}
/* Clone file descriptor */
if (ioctl(fd, CRIOGET, &cfd)) {
perror("ioctl(CRIOGET)");
return 1;
}
/* Set close-on-exec (not really neede here) */
if (fcntl(cfd, F_SETFD, 1) == -1) {
perror("fcntl(F_SETFD)");
return 1;
}
/* Run the test itself */
if (test_aes(cfd))
return 1;
if (test_crypto(cfd))
return 1;
/* Close cloned descriptor */
if (close(cfd)) {
perror("close(cfd)");
return 1;
}
/* Close the original descriptor */
if (close(fd)) {
perror("close(fd)");
return 1;
}
return 0;
}
#else
int
main(int argc, char** argv)
{
return (0);
}
#endif
| Java |
<?php
/**
* @package FOF
* @copyright Copyright (c)2010-2020 Nicholas K. Dionysopoulos / Akeeba Ltd
* @license GNU General Public License version 2, or later
*/
namespace FOF30\Less\Parser;
use FOF30\Less\Less;
use Exception;
defined('_JEXEC') or die;
/**
* This class is taken verbatim from:
*
* lessphp v0.3.9
* http://leafo.net/lessphp
*
* LESS css compiler, adapted from http://lesscss.org
*
* Copyright 2012, Leaf Corcoran <leafot@gmail.com>
* Licensed under MIT or GPLv3, see LICENSE
*
* Responsible for taking a string of LESS code and converting it into a syntax tree
*
* @since 2.0
*/
class Parser
{
// Used to uniquely identify blocks
protected static $nextBlockId = 0;
protected static $precedence = array(
'=<' => 0,
'>=' => 0,
'=' => 0,
'<' => 0,
'>' => 0,
'+' => 1,
'-' => 1,
'*' => 2,
'/' => 2,
'%' => 2,
);
protected static $whitePattern;
protected static $commentMulti;
protected static $commentSingle = "//";
protected static $commentMultiLeft = "/*";
protected static $commentMultiRight = "*/";
// Regex string to match any of the operators
protected static $operatorString;
// These properties will supress division unless it's inside parenthases
protected static $supressDivisionProps = array('/border-radius$/i', '/^font$/i');
protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document");
protected $lineDirectives = array("charset");
/**
* if we are in parens we can be more liberal with whitespace around
* operators because it must resolve to a single value and thus is less
* ambiguous.
*
* Consider:
* property1: 10 -5; // is two numbers, 10 and -5
* property2: (10 -5); // should resolve to 5
*/
protected $inParens = false;
// Caches preg escaped literals
protected static $literalCache = array();
/**
* Constructor
*
* @param [type] $lessc [description]
* @param string $sourceName [description]
*/
public function __construct($lessc, $sourceName = null)
{
$this->eatWhiteDefault = true;
// Reference to less needed for vPrefix, mPrefix, and parentSelector
$this->lessc = $lessc;
// Name used for error messages
$this->sourceName = $sourceName;
$this->writeComments = false;
if (!self::$operatorString)
{
self::$operatorString = '(' . implode('|', array_map(array('\\FOF30\\Less\\Less', 'preg_quote'), array_keys(self::$precedence))) . ')';
$commentSingle = Less::preg_quote(self::$commentSingle);
$commentMultiLeft = Less::preg_quote(self::$commentMultiLeft);
$commentMultiRight = Less::preg_quote(self::$commentMultiRight);
self::$commentMulti = $commentMultiLeft . '.*?' . $commentMultiRight;
self::$whitePattern = '/' . $commentSingle . '[^\n]*\s*|(' . self::$commentMulti . ')\s*|\s+/Ais';
}
}
/**
* Parse text
*
* @param string $buffer [description]
*
* @return [type] [description]
*/
public function parse($buffer)
{
$this->count = 0;
$this->line = 1;
// Block stack
$this->env = null;
$this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
$this->pushSpecialBlock("root");
$this->eatWhiteDefault = true;
$this->seenComments = array();
/*
* trim whitespace on head
* if (preg_match('/^\s+/', $this->buffer, $m)) {
* $this->line += substr_count($m[0], "\n");
* $this->buffer = ltrim($this->buffer);
* }
*/
$this->whitespace();
// Parse the entire file
$lastCount = $this->count;
while (false !== $this->parseChunk());
if ($this->count != strlen($this->buffer))
{
$this->throwError();
}
// TODO report where the block was opened
if (!is_null($this->env->parent))
{
throw new exception('parse error: unclosed block');
}
return $this->env;
}
/**
* Parse a single chunk off the head of the buffer and append it to the
* current parse environment.
* Returns false when the buffer is empty, or when there is an error.
*
* This function is called repeatedly until the entire document is
* parsed.
*
* This parser is most similar to a recursive descent parser. Single
* functions represent discrete grammatical rules for the language, and
* they are able to capture the text that represents those rules.
*
* Consider the function lessc::keyword(). (all parse functions are
* structured the same)
*
* The function takes a single reference argument. When calling the
* function it will attempt to match a keyword on the head of the buffer.
* If it is successful, it will place the keyword in the referenced
* argument, advance the position in the buffer, and return true. If it
* fails then it won't advance the buffer and it will return false.
*
* All of these parse functions are powered by lessc::match(), which behaves
* the same way, but takes a literal regular expression. Sometimes it is
* more convenient to use match instead of creating a new function.
*
* Because of the format of the functions, to parse an entire string of
* grammatical rules, you can chain them together using &&.
*
* But, if some of the rules in the chain succeed before one fails, then
* the buffer position will be left at an invalid state. In order to
* avoid this, lessc::seek() is used to remember and set buffer positions.
*
* Before parsing a chain, use $s = $this->seek() to remember the current
* position into $s. Then if a chain fails, use $this->seek($s) to
* go back where we started.
*
* @return boolean
*/
protected function parseChunk()
{
if (empty($this->buffer))
{
return false;
}
$s = $this->seek();
// Setting a property
if ($this->keyword($key) && $this->assign()
&& $this->propertyValue($value, $key) && $this->end())
{
$this->append(array('assign', $key, $value), $s);
return true;
}
else
{
$this->seek($s);
}
// Look for special css blocks
if ($this->literal('@', false))
{
$this->count--;
// Media
if ($this->literal('@media'))
{
if (($this->mediaQueryList($mediaQueries) || true)
&& $this->literal('{'))
{
$media = $this->pushSpecialBlock("media");
$media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
return true;
}
else
{
$this->seek($s);
return false;
}
}
if ($this->literal("@", false) && $this->keyword($dirName))
{
if ($this->isDirective($dirName, $this->blockDirectives))
{
if (($this->openString("{", $dirValue, null, array(";")) || true)
&& $this->literal("{"))
{
$dir = $this->pushSpecialBlock("directive");
$dir->name = $dirName;
if (isset($dirValue))
{
$dir->value = $dirValue;
}
return true;
}
}
elseif ($this->isDirective($dirName, $this->lineDirectives))
{
if ($this->propertyValue($dirValue) && $this->end())
{
$this->append(array("directive", $dirName, $dirValue));
return true;
}
}
}
$this->seek($s);
}
// Setting a variable
if ($this->variable($var) && $this->assign()
&& $this->propertyValue($value) && $this->end())
{
$this->append(array('assign', $var, $value), $s);
return true;
}
else
{
$this->seek($s);
}
if ($this->import($importValue))
{
$this->append($importValue, $s);
return true;
}
// Opening parametric mixin
if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg)
&& ($this->guards($guards) || true)
&& $this->literal('{'))
{
$block = $this->pushBlock($this->fixTags(array($tag)));
$block->args = $args;
$block->isVararg = $isVararg;
if (!empty($guards))
{
$block->guards = $guards;
}
return true;
}
else
{
$this->seek($s);
}
// Opening a simple block
if ($this->tags($tags) && $this->literal('{'))
{
$tags = $this->fixTags($tags);
$this->pushBlock($tags);
return true;
}
else
{
$this->seek($s);
}
// Closing a block
if ($this->literal('}', false))
{
try
{
$block = $this->pop();
}
catch (exception $e)
{
$this->seek($s);
$this->throwError($e->getMessage());
}
$hidden = false;
if (is_null($block->type))
{
$hidden = true;
if (!isset($block->args))
{
foreach ($block->tags as $tag)
{
if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix)
{
$hidden = false;
break;
}
}
}
foreach ($block->tags as $tag)
{
if (is_string($tag))
{
$this->env->children[$tag][] = $block;
}
}
}
if (!$hidden)
{
$this->append(array('block', $block), $s);
}
// This is done here so comments aren't bundled into he block that was just closed
$this->whitespace();
return true;
}
// Mixin
if ($this->mixinTags($tags)
&& ($this->argumentValues($argv) || true)
&& ($this->keyword($suffix) || true)
&& $this->end())
{
$tags = $this->fixTags($tags);
$this->append(array('mixin', $tags, $argv, $suffix), $s);
return true;
}
else
{
$this->seek($s);
}
// Spare ;
if ($this->literal(';'))
{
return true;
}
// Got nothing, throw error
return false;
}
/**
* [isDirective description]
*
* @param string $dirname [description]
* @param [type] $directives [description]
*
* @return boolean
*/
protected function isDirective($dirname, $directives)
{
// TODO: cache pattern in parser
$pattern = implode("|", array_map(array("\\FOF30\\Less\\Less", "preg_quote"), $directives));
$pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
return preg_match($pattern, $dirname);
}
/**
* [fixTags description]
*
* @param [type] $tags [description]
*
* @return [type] [description]
*/
protected function fixTags($tags)
{
// Move @ tags out of variable namespace
foreach ($tags as &$tag)
{
if ($tag[0] == $this->lessc->vPrefix)
{
$tag[0] = $this->lessc->mPrefix;
}
}
return $tags;
}
/**
* a list of expressions
*
* @param [type] &$exps [description]
*
* @return boolean
*/
protected function expressionList(&$exps)
{
$values = array();
while ($this->expression($exp))
{
$values[] = $exp;
}
if (count($values) == 0)
{
return false;
}
$exps = Less::compressList($values, ' ');
return true;
}
/**
* Attempt to consume an expression.
*
* @param string &$out [description]
*
* @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
*
* @return boolean
*/
protected function expression(&$out)
{
if ($this->value($lhs))
{
$out = $this->expHelper($lhs, 0);
// Look for / shorthand
if (!empty($this->env->supressedDivision))
{
unset($this->env->supressedDivision);
$s = $this->seek();
if ($this->literal("/") && $this->value($rhs))
{
$out = array("list", "",
array($out, array("keyword", "/"), $rhs));
}
else
{
$this->seek($s);
}
}
return true;
}
return false;
}
/**
* Recursively parse infix equation with $lhs at precedence $minP
*
* @param type $lhs [description]
* @param type $minP [description]
*
* @return string
*/
protected function expHelper($lhs, $minP)
{
$this->inExp = true;
$ss = $this->seek();
while (true)
{
$whiteBefore = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]);
// If there is whitespace before the operator, then we require
// whitespace after the operator for it to be an expression
$needWhite = $whiteBefore && !$this->inParens;
if ($this->match(self::$operatorString . ($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP)
{
if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision))
{
foreach (self::$supressDivisionProps as $pattern)
{
if (preg_match($pattern, $this->env->currentProperty))
{
$this->env->supressedDivision = true;
break 2;
}
}
}
$whiteAfter = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]);
if (!$this->value($rhs))
{
break;
}
// Peek for next operator to see what to do with rhs
if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]])
{
$rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
}
$lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
$ss = $this->seek();
continue;
}
break;
}
$this->seek($ss);
return $lhs;
}
/**
* Consume a list of values for a property
*
* @param [type] &$value [description]
* @param [type] $keyName [description]
*
* @return boolean
*/
public function propertyValue(&$value, $keyName = null)
{
$values = array();
if ($keyName !== null)
{
$this->env->currentProperty = $keyName;
}
$s = null;
while ($this->expressionList($v))
{
$values[] = $v;
$s = $this->seek();
if (!$this->literal(','))
{
break;
}
}
if ($s)
{
$this->seek($s);
}
if ($keyName !== null)
{
unset($this->env->currentProperty);
}
if (count($values) == 0)
{
return false;
}
$value = Less::compressList($values, ', ');
return true;
}
/**
* [parenValue description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function parenValue(&$out)
{
$s = $this->seek();
// Speed shortcut
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(")
{
return false;
}
$inParens = $this->inParens;
if ($this->literal("(") && ($this->inParens = true) && $this->expression($exp) && $this->literal(")"))
{
$out = $exp;
$this->inParens = $inParens;
return true;
}
else
{
$this->inParens = $inParens;
$this->seek($s);
}
return false;
}
/**
* a single value
*
* @param [type] &$value [description]
*
* @return boolean
*/
protected function value(&$value)
{
$s = $this->seek();
// Speed shortcut
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-")
{
// Negation
if ($this->literal("-", false) &&(($this->variable($inner) && $inner = array("variable", $inner))
|| $this->unit($inner) || $this->parenValue($inner)))
{
$value = array("unary", "-", $inner);
return true;
}
else
{
$this->seek($s);
}
}
if ($this->parenValue($value))
{
return true;
}
if ($this->unit($value))
{
return true;
}
if ($this->color($value))
{
return true;
}
if ($this->func($value))
{
return true;
}
if ($this->string($value))
{
return true;
}
if ($this->keyword($word))
{
$value = array('keyword', $word);
return true;
}
// Try a variable
if ($this->variable($var))
{
$value = array('variable', $var);
return true;
}
// Unquote string (should this work on any type?
if ($this->literal("~") && $this->string($str))
{
$value = array("escape", $str);
return true;
}
else
{
$this->seek($s);
}
// Css hack: \0
if ($this->literal('\\') && $this->match('([0-9]+)', $m))
{
$value = array('keyword', '\\' . $m[1]);
return true;
}
else
{
$this->seek($s);
}
return false;
}
/**
* an import statement
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function import(&$out)
{
$s = $this->seek();
if (!$this->literal('@import'))
{
return false;
}
/*
* @import "something.css" media;
* @import url("something.css") media;
* @import url(something.css) media;
*/
if ($this->propertyValue($value))
{
$out = array("import", $value);
return true;
}
}
/**
* [mediaQueryList description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function mediaQueryList(&$out)
{
if ($this->genericList($list, "mediaQuery", ",", false))
{
$out = $list[2];
return true;
}
return false;
}
/**
* [mediaQuery description]
*
* @param [type] &$out [description]
*
* @return [type] [description]
*/
protected function mediaQuery(&$out)
{
$s = $this->seek();
$expressions = null;
$parts = array();
if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType))
{
$prop = array("mediaType");
if (isset($only))
{
$prop[] = "only";
}
if (isset($not))
{
$prop[] = "not";
}
$prop[] = $mediaType;
$parts[] = $prop;
}
else
{
$this->seek($s);
}
if (!empty($mediaType) && !$this->literal("and"))
{
// ~
}
else
{
$this->genericList($expressions, "mediaExpression", "and", false);
if (is_array($expressions))
{
$parts = array_merge($parts, $expressions[2]);
}
}
if (count($parts) == 0)
{
$this->seek($s);
return false;
}
$out = $parts;
return true;
}
/**
* [mediaExpression description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function mediaExpression(&$out)
{
$s = $this->seek();
$value = null;
if ($this->literal("(") && $this->keyword($feature) && ($this->literal(":")
&& $this->expression($value) || true) && $this->literal(")"))
{
$out = array("mediaExp", $feature);
if ($value)
{
$out[] = $value;
}
return true;
}
elseif ($this->variable($variable))
{
$out = array('variable', $variable);
return true;
}
$this->seek($s);
return false;
}
/**
* An unbounded string stopped by $end
*
* @param [type] $end [description]
* @param [type] &$out [description]
* @param [type] $nestingOpen [description]
* @param [type] $rejectStrs [description]
*
* @return boolean
*/
protected function openString($end, &$out, $nestingOpen = null, $rejectStrs = null)
{
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
$stop = array("'", '"', "@{", $end);
$stop = array_map(array("\\FOF30\\Less\\Less", "preg_quote"), $stop);
// $stop[] = self::$commentMulti;
if (!is_null($rejectStrs))
{
$stop = array_merge($stop, $rejectStrs);
}
$patt = '(.*?)(' . implode("|", $stop) . ')';
$nestingLevel = 0;
$content = array();
while ($this->match($patt, $m, false))
{
if (!empty($m[1]))
{
$content[] = $m[1];
if ($nestingOpen)
{
$nestingLevel += substr_count($m[1], $nestingOpen);
}
}
$tok = $m[2];
$this->count -= strlen($tok);
if ($tok == $end)
{
if ($nestingLevel == 0)
{
break;
}
else
{
$nestingLevel--;
}
}
if (($tok == "'" || $tok == '"') && $this->string($str))
{
$content[] = $str;
continue;
}
if ($tok == "@{" && $this->interpolation($inter))
{
$content[] = $inter;
continue;
}
if (in_array($tok, $rejectStrs))
{
$count = null;
break;
}
$content[] = $tok;
$this->count += strlen($tok);
}
$this->eatWhiteDefault = $oldWhite;
if (count($content) == 0)
return false;
// Trim the end
if (is_string(end($content)))
{
$content[count($content) - 1] = rtrim(end($content));
}
$out = array("string", "", $content);
return true;
}
/**
* [string description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function string(&$out)
{
$s = $this->seek();
if ($this->literal('"', false))
{
$delim = '"';
}
elseif ($this->literal("'", false))
{
$delim = "'";
}
else
{
return false;
}
$content = array();
// Look for either ending delim , escape, or string interpolation
$patt = '([^\n]*?)(@\{|\\\\|' . Less::preg_quote($delim) . ')';
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
while ($this->match($patt, $m, false))
{
$content[] = $m[1];
if ($m[2] == "@{")
{
$this->count -= strlen($m[2]);
if ($this->interpolation($inter, false))
{
$content[] = $inter;
}
else
{
$this->count += strlen($m[2]);
// Ignore it
$content[] = "@{";
}
}
elseif ($m[2] == '\\')
{
$content[] = $m[2];
if ($this->literal($delim, false))
{
$content[] = $delim;
}
}
else
{
$this->count -= strlen($delim);
// Delim
break;
}
}
$this->eatWhiteDefault = $oldWhite;
if ($this->literal($delim))
{
$out = array("string", $delim, $content);
return true;
}
$this->seek($s);
return false;
}
/**
* [interpolation description]
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function interpolation(&$out)
{
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = true;
$s = $this->seek();
if ($this->literal("@{") && $this->openString("}", $interp, null, array("'", '"', ";")) && $this->literal("}", false))
{
$out = array("interpolate", $interp);
$this->eatWhiteDefault = $oldWhite;
if ($this->eatWhiteDefault)
{
$this->whitespace();
}
return true;
}
$this->eatWhiteDefault = $oldWhite;
$this->seek($s);
return false;
}
/**
* [unit description]
*
* @param [type] &$unit [description]
*
* @return boolean
*/
protected function unit(&$unit)
{
// Speed shortcut
if (isset($this->buffer[$this->count]))
{
$char = $this->buffer[$this->count];
if (!ctype_digit($char) && $char != ".")
{
return false;
}
}
if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m))
{
$unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
return true;
}
return false;
}
/**
* a # color
*
* @param [type] &$out [description]
*
* @return boolean
*/
protected function color(&$out)
{
if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m))
{
if (strlen($m[1]) > 7)
{
$out = array("string", "", array($m[1]));
}
else
{
$out = array("raw_color", $m[1]);
}
return true;
}
return false;
}
/**
* Consume a list of property values delimited by ; and wrapped in ()
*
* @param [type] &$args [description]
* @param [type] $delim [description]
*
* @return boolean
*/
protected function argumentValues(&$args, $delim = ',')
{
$s = $this->seek();
if (!$this->literal('('))
{
return false;
}
$values = array();
while (true)
{
if ($this->expressionList($value))
{
$values[] = $value;
}
if (!$this->literal($delim))
{
break;
}
else
{
if ($value == null)
{
$values[] = null;
}
$value = null;
}
}
if (!$this->literal(')'))
{
$this->seek($s);
return false;
}
$args = $values;
return true;
}
/**
* Consume an argument definition list surrounded by ()
* each argument is a variable name with optional value
* or at the end a ... or a variable named followed by ...
*
* @param [type] &$args [description]
* @param [type] &$isVararg [description]
* @param [type] $delim [description]
*
* @return boolean
*/
protected function argumentDef(&$args, &$isVararg, $delim = ',')
{
$s = $this->seek();
if (!$this->literal('('))
return false;
$values = array();
$isVararg = false;
while (true)
{
if ($this->literal("..."))
{
$isVararg = true;
break;
}
if ($this->variable($vname))
{
$arg = array("arg", $vname);
$ss = $this->seek();
if ($this->assign() && $this->expressionList($value))
{
$arg[] = $value;
}
else
{
$this->seek($ss);
if ($this->literal("..."))
{
$arg[0] = "rest";
$isVararg = true;
}
}
$values[] = $arg;
if ($isVararg)
{
break;
}
continue;
}
if ($this->value($literal))
{
$values[] = array("lit", $literal);
}
if (!$this->literal($delim))
{
break;
}
}
if (!$this->literal(')'))
{
$this->seek($s);
return false;
}
$args = $values;
return true;
}
/**
* Consume a list of tags
* This accepts a hanging delimiter
*
* @param [type] &$tags [description]
* @param [type] $simple [description]
* @param [type] $delim [description]
*
* @return boolean
*/
protected function tags(&$tags, $simple = false, $delim = ',')
{
$tags = array();
while ($this->tag($tt, $simple))
{
$tags[] = $tt;
if (!$this->literal($delim))
{
break;
}
}
if (count($tags) == 0)
{
return false;
}
return true;
}
/**
* List of tags of specifying mixin path
* Optionally separated by > (lazy, accepts extra >)
*
* @param [type] &$tags [description]
*
* @return boolean
*/
protected function mixinTags(&$tags)
{
$s = $this->seek();
$tags = array();
while ($this->tag($tt, true))
{
$tags[] = $tt;
$this->literal(">");
}
if (count($tags) == 0)
{
return false;
}
return true;
}
/**
* A bracketed value (contained within in a tag definition)
*
* @param [type] &$value [description]
*
* @return boolean
*/
protected function tagBracket(&$value)
{
// Speed shortcut
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[")
{
return false;
}
$s = $this->seek();
if ($this->literal('[') && $this->to(']', $c, true) && $this->literal(']', false))
{
$value = '[' . $c . ']';
// Whitespace?
if ($this->whitespace())
{
$value .= " ";
}
// Escape parent selector, (yuck)
$value = str_replace($this->lessc->parentSelector, "$&$", $value);
return true;
}
$this->seek($s);
return false;
}
/**
* [tagExpression description]
*
* @param [type] &$value [description]
*
* @return boolean
*/
protected function tagExpression(&$value)
{
$s = $this->seek();
if ($this->literal("(") && $this->expression($exp) && $this->literal(")"))
{
$value = array('exp', $exp);
return true;
}
$this->seek($s);
return false;
}
/**
* A single tag
*
* @param [type] &$tag [description]
* @param boolean $simple [description]
*
* @return boolean
*/
protected function tag(&$tag, $simple = false)
{
if ($simple)
{
$chars = '^@,:;{}\][>\(\) "\'';
}
else
{
$chars = '^@,;{}["\'';
}
$s = $this->seek();
if (!$simple && $this->tagExpression($tag))
{
return true;
}
$hasExpression = false;
$parts = array();
while ($this->tagBracket($first))
{
$parts[] = $first;
}
$oldWhite = $this->eatWhiteDefault;
$this->eatWhiteDefault = false;
while (true)
{
if ($this->match('([' . $chars . '0-9][' . $chars . ']*)', $m))
{
$parts[] = $m[1];
if ($simple)
{
break;
}
while ($this->tagBracket($brack))
{
$parts[] = $brack;
}
continue;
}
if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@")
{
if ($this->interpolation($interp))
{
$hasExpression = true;
// Don't unescape
$interp[2] = true;
$parts[] = $interp;
continue;
}
if ($this->literal("@"))
{
$parts[] = "@";
continue;
}
}
// For keyframes
if ($this->unit($unit))
{
$parts[] = $unit[1];
$parts[] = $unit[2];
continue;
}
break;
}
$this->eatWhiteDefault = $oldWhite;
if (!$parts)
{
$this->seek($s);
return false;
}
if ($hasExpression)
{
$tag = array("exp", array("string", "", $parts));
}
else
{
$tag = trim(implode($parts));
}
$this->whitespace();
return true;
}
/**
* A css function
*
* @param [type] &$func [description]
*
* @return boolean
*/
protected function func(&$func)
{
$s = $this->seek();
if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('('))
{
$fname = $m[1];
$sPreArgs = $this->seek();
$args = array();
while (true)
{
$ss = $this->seek();
// This ugly nonsense is for ie filter properties
if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value))
{
$args[] = array("string", "", array($name, "=", $value));
}
else
{
$this->seek($ss);
if ($this->expressionList($value))
{
$args[] = $value;
}
}
if (!$this->literal(','))
{
break;
}
}
$args = array('list', ',', $args);
if ($this->literal(')'))
{
$func = array('function', $fname, $args);
return true;
}
elseif ($fname == 'url')
{
// Couldn't parse and in url? treat as string
$this->seek($sPreArgs);
if ($this->openString(")", $string) && $this->literal(")"))
{
$func = array('function', $fname, $string);
return true;
}
}
}
$this->seek($s);
return false;
}
/**
* Consume a less variable
*
* @param [type] &$name [description]
*
* @return boolean
*/
protected function variable(&$name)
{
$s = $this->seek();
if ($this->literal($this->lessc->vPrefix, false) && ($this->variable($sub) || $this->keyword($name)))
{
if (!empty($sub))
{
$name = array('variable', $sub);
}
else
{
$name = $this->lessc->vPrefix . $name;
}
return true;
}
$name = null;
$this->seek($s);
return false;
}
/**
* Consume an assignment operator
* Can optionally take a name that will be set to the current property name
*
* @param string $name [description]
*
* @return boolean
*/
protected function assign($name = null)
{
if ($name)
{
$this->currentProperty = $name;
}
return $this->literal(':') || $this->literal('=');
}
/**
* Consume a keyword
*
* @param [type] &$word [description]
*
* @return boolean
*/
protected function keyword(&$word)
{
if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m))
{
$word = $m[1];
return true;
}
return false;
}
/**
* Consume an end of statement delimiter
*
* @return boolean
*/
protected function end()
{
if ($this->literal(';'))
{
return true;
}
elseif ($this->count == strlen($this->buffer) || $this->buffer{$this->count} == '}')
{
// If there is end of file or a closing block next then we don't need a ;
return true;
}
return false;
}
/**
* [guards description]
*
* @param [type] &$guards [description]
*
* @return boolean
*/
protected function guards(&$guards)
{
$s = $this->seek();
if (!$this->literal("when"))
{
$this->seek($s);
return false;
}
$guards = array();
while ($this->guardGroup($g))
{
$guards[] = $g;
if (!$this->literal(","))
{
break;
}
}
if (count($guards) == 0)
{
$guards = null;
$this->seek($s);
return false;
}
return true;
}
/**
* A bunch of guards that are and'd together
*
* @param [type] &$guardGroup [description]
*
* @todo rename to guardGroup
*
* @return boolean
*/
protected function guardGroup(&$guardGroup)
{
$s = $this->seek();
$guardGroup = array();
while ($this->guard($guard))
{
$guardGroup[] = $guard;
if (!$this->literal("and"))
{
break;
}
}
if (count($guardGroup) == 0)
{
$guardGroup = null;
$this->seek($s);
return false;
}
return true;
}
/**
* [guard description]
*
* @param [type] &$guard [description]
*
* @return boolean
*/
protected function guard(&$guard)
{
$s = $this->seek();
$negate = $this->literal("not");
if ($this->literal("(") && $this->expression($exp) && $this->literal(")"))
{
$guard = $exp;
if ($negate)
{
$guard = array("negate", $guard);
}
return true;
}
$this->seek($s);
return false;
}
/* raw parsing functions */
/**
* [literal description]
*
* @param [type] $what [description]
* @param [type] $eatWhitespace [description]
*
* @return boolean
*/
protected function literal($what, $eatWhitespace = null)
{
if ($eatWhitespace === null)
{
$eatWhitespace = $this->eatWhiteDefault;
}
// Shortcut on single letter
if (!isset($what[1]) && isset($this->buffer[$this->count]))
{
if ($this->buffer[$this->count] == $what)
{
if (!$eatWhitespace)
{
$this->count++;
return true;
}
}
else
{
return false;
}
}
if (!isset(self::$literalCache[$what]))
{
self::$literalCache[$what] = Less::preg_quote($what);
}
return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
}
/**
* [genericList description]
*
* @param [type] &$out [description]
* @param [type] $parseItem [description]
* @param string $delim [description]
* @param boolean $flatten [description]
*
* @return boolean
*/
protected function genericList(&$out, $parseItem, $delim = "", $flatten = true)
{
$s = $this->seek();
$items = array();
while ($this->$parseItem($value))
{
$items[] = $value;
if ($delim)
{
if (!$this->literal($delim))
{
break;
}
}
}
if (count($items) == 0)
{
$this->seek($s);
return false;
}
if ($flatten && count($items) == 1)
{
$out = $items[0];
}
else
{
$out = array("list", $delim, $items);
}
return true;
}
/**
* Advance counter to next occurrence of $what
* $until - don't include $what in advance
* $allowNewline, if string, will be used as valid char set
*
* @param [type] $what [description]
* @param [type] &$out [description]
* @param boolean $until [description]
* @param boolean $allowNewline [description]
*
* @return boolean
*/
protected function to($what, &$out, $until = false, $allowNewline = false)
{
if (is_string($allowNewline))
{
$validChars = $allowNewline;
}
else
{
$validChars = $allowNewline ? "." : "[^\n]";
}
if (!$this->match('(' . $validChars . '*?)' . Less::preg_quote($what), $m, !$until))
{
return false;
}
if ($until)
{
// Give back $what
$this->count -= strlen($what);
}
$out = $m[1];
return true;
}
/**
* Try to match something on head of buffer
*
* @param [type] $regex [description]
* @param [type] &$out [description]
* @param [type] $eatWhitespace [description]
*
* @return boolean
*/
protected function match($regex, &$out, $eatWhitespace = null)
{
if ($eatWhitespace === null)
{
$eatWhitespace = $this->eatWhiteDefault;
}
$r = '/' . $regex . ($eatWhitespace && !$this->writeComments ? '\s*' : '') . '/Ais';
if (preg_match($r, $this->buffer, $out, null, $this->count))
{
$this->count += strlen($out[0]);
if ($eatWhitespace && $this->writeComments)
{
$this->whitespace();
}
return true;
}
return false;
}
/**
* Watch some whitespace
*
* @return boolean
*/
protected function whitespace()
{
if ($this->writeComments)
{
$gotWhite = false;
while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count))
{
if (isset($m[1]) && empty($this->commentsSeen[$this->count]))
{
$this->append(array("comment", $m[1]));
$this->commentsSeen[$this->count] = true;
}
$this->count += strlen($m[0]);
$gotWhite = true;
}
return $gotWhite;
}
else
{
$this->match("", $m);
return strlen($m[0]) > 0;
}
}
/**
* Match something without consuming it
*
* @param [type] $regex [description]
* @param [type] &$out [description]
* @param [type] $from [description]
*
* @return boolean
*/
protected function peek($regex, &$out = null, $from = null)
{
if (is_null($from))
{
$from = $this->count;
}
$r = '/' . $regex . '/Ais';
$result = preg_match($r, $this->buffer, $out, null, $from);
return $result;
}
/**
* Seek to a spot in the buffer or return where we are on no argument
*
* @param [type] $where [description]
*
* @return boolean
*/
protected function seek($where = null)
{
if ($where === null)
{
return $this->count;
}
else
{
$this->count = $where;
}
return true;
}
/* misc functions */
/**
* [throwError description]
*
* @param string $msg [description]
* @param [type] $count [description]
*
* @return void
*/
public function throwError($msg = "parse error", $count = null)
{
$count = is_null($count) ? $this->count : $count;
$line = $this->line + substr_count(substr($this->buffer, 0, $count), "\n");
if (!empty($this->sourceName))
{
$loc = "$this->sourceName on line $line";
}
else
{
$loc = "line: $line";
}
// TODO this depends on $this->count
if ($this->peek("(.*?)(\n|$)", $m, $count))
{
throw new exception("$msg: failed at `$m[1]` $loc");
}
else
{
throw new exception("$msg: $loc");
}
}
/**
* [pushBlock description]
*
* @param [type] $selectors [description]
* @param [type] $type [description]
*
* @return \stdClass
*/
protected function pushBlock($selectors = null, $type = null)
{
$b = new \stdClass;
$b->parent = $this->env;
$b->type = $type;
$b->id = self::$nextBlockId++;
// TODO: kill me from here
$b->isVararg = false;
$b->tags = $selectors;
$b->props = array();
$b->children = array();
$this->env = $b;
return $b;
}
/**
* Push a block that doesn't multiply tags
*
* @param [type] $type [description]
*
* @return \stdClass
*/
protected function pushSpecialBlock($type)
{
return $this->pushBlock(null, $type);
}
/**
* Append a property to the current block
*
* @param [type] $prop [description]
* @param [type] $pos [description]
*
* @return void
*/
protected function append($prop, $pos = null)
{
if ($pos !== null)
{
$prop[-1] = $pos;
}
$this->env->props[] = $prop;
}
/**
* Pop something off the stack
*
* @return [type] [description]
*/
protected function pop()
{
$old = $this->env;
$this->env = $this->env->parent;
return $old;
}
/**
* Remove comments from $text
*
* @param [type] $text [description]
*
* @todo: make it work for all functions, not just url
*
* @return [type] [description]
*/
protected function removeComments($text)
{
$look = array(
'url(', '//', '/*', '"', "'"
);
$out = '';
$min = null;
while (true)
{
// Find the next item
foreach ($look as $token)
{
$pos = strpos($text, $token);
if ($pos !== false)
{
if (!isset($min) || $pos < $min[1])
{
$min = array($token, $pos);
}
}
}
if (is_null($min))
break;
$count = $min[1];
$skip = 0;
$newlines = 0;
switch ($min[0])
{
case 'url(':
if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
{
$count += strlen($m[0]) - strlen($min[0]);
}
break;
case '"':
case "'":
if (preg_match('/' . $min[0] . '.*?' . $min[0] . '/', $text, $m, 0, $count))
{
$count += strlen($m[0]) - 1;
}
break;
case '//':
$skip = strpos($text, "\n", $count);
if ($skip === false)
{
$skip = strlen($text) - $count;
}
else
{
$skip -= $count;
}
break;
case '/*':
if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count))
{
$skip = strlen($m[0]);
$newlines = substr_count($m[0], "\n");
}
break;
}
if ($skip == 0)
{
$count += strlen($min[0]);
}
$out .= substr($text, 0, $count) . str_repeat("\n", $newlines);
$text = substr($text, $count + $skip);
$min = null;
}
return $out . $text;
}
}
| Java |
#ifndef _LOCKHELP_H
#define _LOCKHELP_H
#include <generated/autoconf.h>
#include <linux/spinlock.h>
#include <asm/atomic.h>
#include <linux/interrupt.h>
#include <linux/smp.h>
/* Header to do help in lock debugging. */
#if 0 //CONFIG_NETFILTER_DEBUG
struct spinlock_debug
{
spinlock_t l;
atomic_t locked_by;
};
struct rwlock_debug
{
rwlock_t l;
long read_locked_map;
long write_locked_map;
};
#define DECLARE_LOCK(l) \
struct spinlock_debug l = { SPIN_LOCK_UNLOCKED, ATOMIC_INIT(-1) }
#define DECLARE_LOCK_EXTERN(l) \
extern struct spinlock_debug l
#define DECLARE_RWLOCK(l) \
struct rwlock_debug l = { RW_LOCK_UNLOCKED, 0, 0 }
#define DECLARE_RWLOCK_EXTERN(l) \
extern struct rwlock_debug l
#define MUST_BE_LOCKED(l) \
do { if (atomic_read(&(l)->locked_by) != smp_processor_id()) \
printk("ASSERT %s:%u %s unlocked\n", __FILE__, __LINE__, #l); \
} while(0)
#define MUST_BE_UNLOCKED(l) \
do { if (atomic_read(&(l)->locked_by) == smp_processor_id()) \
printk("ASSERT %s:%u %s locked\n", __FILE__, __LINE__, #l); \
} while(0)
/* Write locked OK as well. */
#define MUST_BE_READ_LOCKED(l) \
do { if (!((l)->read_locked_map & (1UL << smp_processor_id())) \
&& !((l)->write_locked_map & (1UL << smp_processor_id()))) \
printk("ASSERT %s:%u %s not readlocked\n", __FILE__, __LINE__, #l); \
} while(0)
#define MUST_BE_WRITE_LOCKED(l) \
do { if (!((l)->write_locked_map & (1UL << smp_processor_id()))) \
printk("ASSERT %s:%u %s not writelocked\n", __FILE__, __LINE__, #l); \
} while(0)
#define MUST_BE_READ_WRITE_UNLOCKED(l) \
do { if ((l)->read_locked_map & (1UL << smp_processor_id())) \
printk("ASSERT %s:%u %s readlocked\n", __FILE__, __LINE__, #l); \
else if ((l)->write_locked_map & (1UL << smp_processor_id())) \
printk("ASSERT %s:%u %s writelocked\n", __FILE__, __LINE__, #l); \
} while(0)
#define LOCK_BH(lk) \
do { \
MUST_BE_UNLOCKED(lk); \
spin_lock_bh(&(lk)->l); \
atomic_set(&(lk)->locked_by, smp_processor_id()); \
} while(0)
#define UNLOCK_BH(lk) \
do { \
MUST_BE_LOCKED(lk); \
atomic_set(&(lk)->locked_by, -1); \
spin_unlock_bh(&(lk)->l); \
} while(0)
#define READ_LOCK(lk) \
do { \
MUST_BE_READ_WRITE_UNLOCKED(lk); \
read_lock_bh(&(lk)->l); \
set_bit(smp_processor_id(), &(lk)->read_locked_map); \
} while(0)
#define WRITE_LOCK(lk) \
do { \
MUST_BE_READ_WRITE_UNLOCKED(lk); \
write_lock_bh(&(lk)->l); \
set_bit(smp_processor_id(), &(lk)->write_locked_map); \
} while(0)
#define READ_UNLOCK(lk) \
do { \
if (!((lk)->read_locked_map & (1UL << smp_processor_id()))) \
printk("ASSERT: %s:%u %s not readlocked\n", \
__FILE__, __LINE__, #lk); \
clear_bit(smp_processor_id(), &(lk)->read_locked_map); \
read_unlock_bh(&(lk)->l); \
} while(0)
#define WRITE_UNLOCK(lk) \
do { \
MUST_BE_WRITE_LOCKED(lk); \
clear_bit(smp_processor_id(), &(lk)->write_locked_map); \
write_unlock_bh(&(lk)->l); \
} while(0)
#else
#define DECLARE_LOCK(l) spinlock_t l = SPIN_LOCK_UNLOCKED
#define DECLARE_LOCK_EXTERN(l) extern spinlock_t l
#define DECLARE_RWLOCK(l) rwlock_t l = RW_LOCK_UNLOCKED
#define DECLARE_RWLOCK_EXTERN(l) extern rwlock_t l
#define MUST_BE_LOCKED(l)
#define MUST_BE_UNLOCKED(l)
#define MUST_BE_READ_LOCKED(l)
#define MUST_BE_WRITE_LOCKED(l)
#define MUST_BE_READ_WRITE_UNLOCKED(l)
#define LOCK_BH(l) spin_lock_bh(l)
#define UNLOCK_BH(l) spin_unlock_bh(l)
#define READ_LOCK(l) read_lock_bh(l)
#define WRITE_LOCK(l) write_lock_bh(l)
#define READ_UNLOCK(l) read_unlock_bh(l)
#define WRITE_UNLOCK(l) write_unlock_bh(l)
#endif /*CONFIG_NETFILTER_DEBUG*/
#endif /* _LOCKHELP_H */
| Java |
namespace Rantory.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ChemicalType : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.ChemicalTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.ChemicalTypes");
}
}
}
| Java |
/*
AVFS: A Virtual File System Library
Copyright (C) 1998-2001 Miklos Szeredi <miklos@szeredi.hu>
This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
*/
#include <sys/types.h>
struct child_message {
int reqsize;
int path1size;
int path2size;
};
extern void run(int cfs, const char *codadir, int dm);
extern void child_process(int infd, int outfd);
extern int mount_coda(const char *dev, const char *dir, int devfd, int quiet);
extern int unmount_coda(const char *dir, int quiet);
extern void set_signal_handlers();
extern void clean_exit(int status);
extern void run_exit();
extern void user_child(pid_t pid);
| Java |
/*
Theme Name: Carry Gently
Adding support for language written in a Right To Left (RTL) direction is easy -
it's just a matter of overwriting all the horizontal positioning attributes
of your CSS stylesheet in a separate stylesheet file named rtl.css.
http://codex.wordpress.org/Right_to_Left_Language_Support
*/
/*
body {
direction: rtl;
unicode-bidi: embed;
}
*/ | Java |
using Windows.UI.Xaml.Navigation;
using Vocabulary;
using Vocabulary.ViewModels;
namespace Vocabulary.Views
{
public sealed partial class HomePage : PageBase
{
public HomePage()
{
this.ViewModel = new MainViewModel(8);
this.InitializeComponent();
}
public MainViewModel ViewModel { get; set; }
protected async override void LoadState(object navParameter)
{
await this.ViewModel.LoadDataAsync();
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.